# Data product module creation

In Google Cloud Cortex Framework, a [data product](https://docs.cloud.google.com/cortex/docs/data-product.md.txt) module
packages SQL transformations, schema annotations, and BigQuery table
settings into a deployable Dataform workflow. While
Cortex Framework includes prebuilt data products for SAP and
Salesforce, you can create custom data product modules to implement your own
business logic, KPIs, and cross-source analytical models.

A custom data product module can query tables from any combination of upstream
sources:

- **Data foundation datasets** : Conformed tables from prebuilt (`cortex.sap`, `cortex.sfdc`) or [custom data foundations](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-foundation.md.txt).
- **Upstream data products** : Reusable source-aligned data products (such as `customers`, `delivery_documents`, or `accounts`).
- **External zero-copy catalogs** : Linked datasets from [BigQuery sharing](https://docs.cloud.google.com/cortex/docs/source-system-integration/analytics-hub.md.txt) (`analytics_hub`) or Delta Sharing tables from [SAP Business Data Cloud](https://docs.cloud.google.com/cortex/docs/source-system-integration/sap-bdc.md.txt) (`lakehouse_delta_share`).

> [!NOTE]
> **Note:** You can follow the manual steps in this guide, or use the prepackaged AI agent skills (`/create-data-product`, `/extend-data-product`, and `/validate-data-product`) to scaffold and verify custom modules automatically. For details, see [Build data products with agent skills](https://docs.cloud.google.com/cortex/docs/agentic-skills-for-data-product-building.md.txt).

## Prerequisites

Before creating a custom data product module, verify the following requirements:

- **Set up a custom namespace** : Always create custom data product modules inside a dedicated [custom namespace](https://docs.cloud.google.com/cortex/docs/extensibility-guide-namespaces.md.txt) (rather than the `cortex` namespace) so framework upgrades don't overwrite your models.
- **Confirm upstream dependencies exist** : Verify that all upstream tables referenced by your module are enabled in your [data foundation](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-foundation.md.txt) dataset, upstream data products, or registered external catalogs (`analytics_hub` or `lakehouse_delta_share`).

## Module folder and file structure

A custom data product module lives inside your custom namespace under
`src/data_modules/` and is registered in `config/config.yaml`:

    config/
    └── config.yaml                                           # Registers the module instance and binds upstream dependencies
    src/data_modules/<custom_namespace>/<system_type>/products/<product_name>/
    ├── manifest.yaml                                         # Declares module metadata, builder type, and upstream dependencies
    ├── table_settings.default.yaml                           # Configures materialization, partitioning, clustering, tags, and assertions
    ├── annotations/                                          # Table and column descriptions merged into BigQuery schemas
    │   └── [ecc/|s4/]<table_name>.yaml
    └── definitions/                                          # Dataform JavaScript (.js) transformation definitions
        └── [ecc/|s4/]<table_name>.js

The following table summarizes the artifacts that define a custom data product
module:

| File or directory | Purpose |
| `manifest.yaml` | Declares the module `displayName`, `category` (`source_aligned_product` or `consumption_product`), compiler `builder`, upstream `dependencies`, and governance `labels`. The leaf directory name identifies the module automatically. |
| `table_settings.default.yaml` | Configures default BigQuery table settings---including `materializationType`, `partitionDetails`, `clusterDetails`, `bigQueryLabels`, `dataformTags`, and declarative [data quality assertions](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt). |
| `annotations/*.yaml` | Provides business descriptions for the table and each projected column. During compilation, Cortex Framework merges these descriptions into Dataform and BigQuery table metadata. |
| `definitions/*.js` | Contains Dataform JavaScript definitions that query bound upstream datasets and publish target tables or views. |
| `config/config.yaml` | Registers the module instance under `data.modules.products`, maps logical dependency keys to deployed module or catalog IDs (`dependencyBindings`), and assigns the target dataset (`dataTargetId`). |
|---|---|

## Creation of a data product module

To create a custom data product module, configure the module files inside your
custom namespace and register the module in `config/config.yaml`.

### Create `manifest.yaml` and choose a builder

Create `manifest.yaml` in the root of your module directory to declare the
module `category` (`source_aligned_product` or `consumption_product`),
`builder`, `dependencies`, and optional `displayName`, `description`,
`documentation`, and governance `labels`. `manifest.yaml` and its
`dependencies` entries enforce strict camelCase schema validation
(`extra="forbid"`, rejecting unknown or `snake_case` keys). Don't set the
deprecated `type:` field---it emits a deprecation warning and is ignored because
the leaf directory name identifies the module automatically:

```yaml
displayName: Sales Performance Summary
description: Sales performance analytical data product.
category: consumption_product
builder: sap_product
dependencies:
  sapModule:
    modulePath: cortex.sap.foundations.sap
    supportedVersions:
      - ecc
      - s4
    tables:
      common:
        - vbak
        - vbap
labels:
  line_of_business: sales
  sap_module: sap_sd
```

When you configure `supportedVersions` under `dependencies` in `manifest.yaml`,
the following rules apply:

- **Any dependency key in `consumption_product` manifests** : You can set `supportedVersions` on any dependency key, not only `sapModule`. For example, `financial_statements/manifest.yaml` sets `supportedVersions: [ecc]` on `sapAccountingDocuments` and `sapGeneralLedgerItems`, and `supportedVersions: [s4]` on `sapUniversalJournal`. Similarly, `accounts_receivable_insights/manifest.yaml` sets `supportedVersions: [ecc]` on `sapAccountsReceivableEcc` and `supportedVersions: [s4]` on `sapAccountsReceivableS4`.
- **Dialect-scoped dependency bindings** : Setting `supportedVersions` on a product dependency, such as `[ecc]` or `[s4]`, scopes the dependency to the listed dialects. The `uv run cortex-build` command activates and requires the corresponding `dependencyBindings` entry only when building a matching dialect.
- **Manifest and value restrictions** : Foundation and `source_aligned_product` manifests can't use `supportedVersions` on unsectioned table lists because `validate_foundation_dependencies` rejects that configuration. In addition, any manifest (including `consumption_product`) whose dependency targets a `foundation` module with `supportedVersions` must declare a sectioned `tables:` mapping (`common:`, `ecc:`, `s4:`) rather than an unsectioned list or omitted `tables:`. You also can't include `common` inside `supportedVersions`.

Select the built-in SDK `builder` that matches your module's upstream
dependencies and directory layout:

| `builder` value | Directory layout (`definitions/` and `annotations/`) | `table_settings.default.yaml` format | `materializationType` guidance | Primary use case |
| `flat_product` (`FlatProductBuilder`) | Flat root files (`definitions/*.js`, `annotations/*.yaml`) | Flat top-level table keys (`FlatProductTableSettings`; rejects `common:` and version section wrappers) | Set explicitly on each table (`table`, `incremental`, or `view`; defaults to `incremental` if omitted) | Custom-namespace Salesforce products, SAP Business Data Cloud Delta Sharing products (set `materializationType: view`), custom-source products, and multi-source composite products |
| `versioned_product` (`VersionedProductBuilder`) | Shared root (`definitions/`, `annotations/`), optional `definitions/common/`, plus variant subfolders (`definitions/<variant>/`, `annotations/<variant>/`) | Sectioned under `common:` plus `<variant>:` (`VersionedProductTableSettings`) | Set explicitly per table (`table`, `incremental`, or `view`) | Custom multi-variant data products whose SQL or settings vary by upstream source edition or version |
| `sap_product` (`SapProductBuilder`) | Shared root or version-specific `ecc/` and `s4/` subfolders | Sectioned under `ecc:`, `s4:`, or `common:` (`SapProductTableSettings`) | Set explicitly per table (`table`, `incremental`, or `view`; defaults to `incremental` if omitted) | SAP ECC and SAP S/4HANA data products (single-source or cross-source when at least one dependency resolves an SAP version) |
|---|---|---|---|---|

> [!NOTE]
> **Note:** `sfdc_product` is scoped strictly to the built-in `cortex` namespace; custom namespaces building or extending Salesforce data products must use `builder: flat_product` with an explicit `materializationType` on each table. Legacy aliases `generic_product`, `composite_product`, `generic_composite_product`, and `sap_bdc_product` are deprecated in version 7.1 (scheduled for removal in version 8.0)---use `builder: flat_product` instead (`sap_bdc_product` no longer defaults to `view`).

### Create `table_settings.default.yaml`

Create `table_settings.default.yaml` in the module root to configure
materialization, partitioning, clustering, labels, tags, and assertions (see
[Table settings schema](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt#config-table-settings-yaml)).

- **Flat top-level format (`flat_product`)** : Declare each table key directly at
  the top level of the file with an explicit `materializationType`.
  `FlatProductTableSettings` rejects `common:` and version-section wrappers. For
  time-partitioned data product tables, specify both `partitionType: time` and
  `dataType` (`DATE`, `DATETIME`, or `TIMESTAMP`)---omitting `dataType` on a
  product table emits a deprecation warning and leaves the table unpartitioned:

  ```yaml
  # Flat top-level table key format (flat_product)
  custom_sales_summary:
    materializationType: "table"
    bigQueryLabels:
      - key: line_of_business
        value: sales
    dataformTags: ["custom", "sales", "reporting"]
    partitionDetails:
      column: "created_date"
      partitionType: "time"
      dataType: "DATE"
      timeGrain: "day"
    clusterDetails:
      columns:
        - "customer_id"
  ```
- **Version-sectioned format (`sap_product`, `versioned_product`)** : Group table
  keys under `ecc:` and `s4:` (or `common:` plus `<variant>:`) to match your
  supported source versions. For an example, see
  [Create `table_settings.default.yaml`](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-product.md.txt#example-step-3-table-settings).

### Create column annotations (`annotations/*.yaml`)

Create an annotation file in
`annotations/TABLE_NAME.yaml` for each
table in your module. For `versioned_product` and `sap_product` modules, you can
override annotations per variant in
`annotations/VARIANT/TABLE_NAME.yaml`
(for example, `annotations/ecc/` or `annotations/s4/` for SAP ERP);
Cortex Framework falls back to
`annotations/TABLE_NAME.yaml` when no
variant-specific file exists. Cortex Framework validates each file
against the strict `TableAnnotation` schema (`extra="forbid"`, rejecting unknown
keys and duplicate field names; nested `STRUCT` subfields use `fields:` or
`subfields:` and flatten into dot-delimited column keys) and merges these
descriptions into the compiled Dataform and BigQuery
table schemas:

```yaml
description: "Description of the table or view purpose."
fields:
  - name: "customer_id"                     # column name
    description: "Unique customer identifier." # column description
  - name: "created_date"
    description: "Transaction creation date."
```

### Create Dataform definitions

Create a Dataform JavaScript file in `definitions/<table_name>.js` for
each table in your module (or in `definitions/ecc/<table_name>.js` and
`definitions/s4/<table_name>.js` when an SAP ERP model requires version-specific
SQL):

- Resolve bound upstream datasets from `moduleConfig.sources.<dependency_key>.datasetId` and reference upstream tables with `ctx.ref(...)`.
- Build the Dataform action configuration with `publish_config.getPublishConfig(...)` and publish the model using `publisher.publish(...)` (for all product builders: `flat_product`, `versioned_product`, and `sap_product`) rather than `.sqlx` or bare Dataform `publish(...)`, so `table_settings.default.yaml` properties and upstream `blocking: true` assertions attach automatically and [row- and column-level security](https://docs.cloud.google.com/cortex/docs/row-and-column-security.md.txt) governance hooks (column policy tags, row-level security post-operations DDL, and zero-fail-open refreshes) apply when security is configured.

For complete `.js` model implementations, see
[Create `definitions/flights_usd.js`](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-product.md.txt#example-step-5-definitions) and
[Example: Build a composite data product](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-product.md.txt#generic-product-example).

### Register the module in `config/config.yaml`

Register your custom namespace under `data.namespaces` (alongside `- name:
cortex`, because `data.namespaces` acts as a strict allowlist and local custom
namespaces aren't auto-discovered) and add your module under
`data.modules.products` in `config/config.yaml` to bind its upstream
dependencies and target dataset:

```yaml
data:
  namespaces:
    - name: cortex
    - name: CUSTOM_NAMESPACE
      path: ../src/data_modules/CUSTOM_NAMESPACE

  # Configuration for data foundation and product modules.
  modules:
    # List of data product modules.
    products:
        # Recommended naming for PRODUCT_MODULE_ID:
        # CUSTOM_NAMESPACE_PRODUCT_NAME
      - moduleId: PRODUCT_MODULE_ID
        # Path of the data product (namespaced).
        modulePath: CUSTOM_NAMESPACE.SYSTEM_TYPE.products.PRODUCT_NAME
        # Map of module dependencies declared in manifest.yaml.
        dependencyBindings:
          sapModule: erp
        # Reference to the target dataset ID.
        dataTargetId: product_target
        # Whether the module is enabled.
        # enabled: true
        # Whether to sync this data product to Knowledge Catalog.
        # syncToKc: true
        # Optional sparse table settings override file, relative to the 'config/'
        # directory (merged field-by-field onto table_settings.default.yaml).
        # Recommended path: '{custom_namespace}/{system_type}/products/{product_name}/table_settings.yaml'
        # If omitted, uses table_settings.default.yaml from the resolved module directory.
        # tableSettings: "{custom_namespace}/{system_type}/products/{product_name}/table_settings.yaml"
```

Replace the following:

- `PRODUCT_MODULE_ID`: unique instance identifier, for example: `custom_sales_summary`.
- `CUSTOM_NAMESPACE`: custom namespace registered under `data.namespaces`, for example: `sap_bookingdatamodel` or `acme_corp`.
- `SYSTEM_TYPE`: source system folder, for example: `sap`, `sfdc`, `sap_bdc`, or a custom source identifier.
- `PRODUCT_NAME`: leaf folder name of your custom data product module, for example: `sales_performance_summary`.

For data product modules (unlike data foundation modules), both `tableSettings`
and `inlineTableSettings` are sparse field-by-field overrides merged onto the
module's `table_settings.default.yaml` rather than full replacements. Omit
`path:` under `data.namespaces` for installed wheel packages; see
[Register the namespace](https://docs.cloud.google.com/cortex/docs/extensibility-guide-namespaces.md.txt#step-a-register-the-namespace)
for details.

## Column naming and annotation conventions

Keep column names consistent, traceable to source schemas, and synchronized
between your Dataform `.js` definitions and `annotations/*.yaml` files.

### General requirements for all data products

Apply the following baseline conventions to every data product table:

- **Lowercase `snake_case` and 1:1 annotation parity** : Every projected column in `definitions/[ecc|s4/]*.js` must use lowercase `snake_case` (`^[a-z0-9_]+$`) and have a matching entry in `annotations/[ecc|s4/]*.yaml` with no missing or orphan fields.
- **Semantic affixes for calculated and conformed columns** : Use `_id` for identifiers, `_code` for codes, `_date` for dates, `_timestamp` or `_at` for timestamps, and `is_` or `has_` for boolean indicators.
- **Mandatory audit columns** : Every data product model must project both of the following audit columns:
  - `source_last_updated_at` (`TIMESTAMP`): Derived from `recordstamp` in SAP or `SystemModstamp` in Salesforce (use `CreatedDate` for append-only `*History` SObjects). When joining multiple source tables, compute the maximum watermark with `GREATEST(IFNULL(..., TIMESTAMP('1900-01-01 00:00:00+00')), ...)`.
  - `bq_loaded_at` (`TIMESTAMP`): Populated with `CURRENT_TIMESTAMP() AS bq_loaded_at`.

### SAP ERP column naming rules (`sap_product`)

When aliasing SAP foundation columns in `sap_product` models, append the exact
lowercase SAP DDIC field name as the suffix (`<business_name>_<sap_field>`),
such as `company_code_bukrs` (from `bukrs`) or `sales_document_vbeln` (from
`vbeln`). Follow the SAP suffix rules in the following table:

| Rule | Requirement | Examples |
| Alphanumeric and localized fields | Preserve digit-letter boundaries verbatim without inserting extra underscores. | - `zbd1p` → `cash_discount_percentage1_zbd1p` (not `..._zbd_1p`) - `j_1aindxp` → `inflation_index_j_1aindxp` (not `..._j_1_aindxp`) |
| Multi-token DDIC suffixes | Keep abbreviated tokens inside the DDIC suffix intact without expanding them. | - `coco_num` → `condition_contract_coco_num` - `service_doc_id` → `service_document_service_doc_id` - `qty_diff` → `quantity_qty_diff` |
| Component prefixes and custom fields | Retain SAP component prefixes, and replace `/` with `_` on namespace-prefixed or custom append fields. | - `bev1_rpcont` → `number_category_3_bev1_rpcont` - `ZZCUSTOM_FIELD` → `custom_field_zzcustom_field` - `/BIC/ZFOO` → replicates with `_` in place of `/` |
| System field exclusion | Exclude internal SAP S/4HANA aging columns from both `.js` definitions and `annotations/*.yaml`. | Omit `_dataaging` |
| Canonical grain exceptions | Use standardized column names for multi-client isolation and cross-version ECC and S/4HANA parity (confirm table-specific client keys such as `adrc.client` with `cortex-metadata show`). | - `mandt` and `acdoca.rclnt` → `client_mandt` - `acdoca.rbukrs` → `company_code_bukrs` |
|---|---|---|

### Salesforce and SAP BDC column naming rules

Format columns for Salesforce and SAP Business Data Cloud models as follows:

- **Salesforce (prebuilt `cortex` products and custom `flat_product` models)** : Convert `PascalCase` SObject API names 1:1 to `snake_case` (`StageName` maps to `stage_name`, and `Id` maps to `<entity>_id` such as `opportunity_id`), keeping literal abbreviations intact (`Org` maps to `org`, `Doc` maps to `doc`). Map custom `*__c` fields to `<snake_case>__c` (such as `Discount_Rate__c` to `discount_rate__c`), and project human-readable lookup names adjacent to foreign-key `*_id` columns (such as `account_name` and `owner_name`).
- **SAP Business Data Cloud (`flat_product` with `materializationType: view`)** : Preserve shared `snake_case` column names from Delta Sharing tables as-is (such as `sales_order` or `product`) without appending synthetic `_id` or `_number` suffixes.

## Data product module example (`sap_product`)

The following walkthrough implements the `flights_usd` data product in the
`sap_bookingdatamodel` namespace from the
[Extensibility guide scenario](https://docs.cloud.google.com/cortex/docs/extensibility-guide.md.txt#example-scenario).
It joins the custom `sflight` foundation table with the prebuilt SAP currency
exchange rates table (`tcurr`) to convert flight prices into USD.

### Register the module in `config/config.yaml`

Ensure `sap_bookingdatamodel` is registered alongside `cortex` under
`data.namespaces` (so `cortex-build` discovers the local namespace) and register
the `sap_bookingdatamodel_flights_usd` module under `data.modules.products` in
`config/config.yaml`:

```yaml
data:
  namespaces:
    - name: cortex
    - name: sap_bookingdatamodel
      path: ../src/data_modules/sap_bookingdatamodel
  modules:
    products:
      - moduleId: sap_bookingdatamodel_flights_usd
        modulePath: sap_bookingdatamodel.sap.products.flights_usd
        dependencyBindings:
          sapModule: erp
          sapModuleCustNS: sap_bookingdatamodel
        dataTargetId: product_target
```

### Create `manifest.yaml`

Create `manifest.yaml` in
`src/data_modules/sap_bookingdatamodel/sap/products/flights_usd/` declaring the
upstream `tcurr` and `sflight` table dependencies:

```yaml
displayName: Flights USD
description: Flight scheduling and pricing USD data product.
category: consumption_product
dependencies:
  sapModule:
    modulePath: cortex.sap.foundations.sap
    supportedVersions:
      - ecc
      - s4
    tables:
      common:
        - tcurr
  sapModuleCustNS:
    # Type of the dependent Module.
    # use cortex.sap.foundations.sap if you followed "Configure multiple instances of a data foundation module"
    # /cortex/docs/deployment-configuration#multiple-data-foundation-instances
    modulePath: cortex.sap.foundations.sap
    # use sap_bookingdatamodel.sap.foundations.sap if you are connecting to custom-data foundation module:
    # /cortex/docs/extensibility-guide-data-foundation
    #modulePath: sap_bookingdatamodel.sap.foundations.sap
    supportedVersions:
      - ecc
      - s4
    tables:
      common:
        - sflight
builder: sap_product
labels:
  line_of_business: sales
```

Both bound SAP foundation instances (`sapModule` and `sapModuleCustNS`) must
have the same `moduleSettings.sapVersion` (`ecc` or `s4`), otherwise validation
fails with a conflicting-variant error. This module uses `builder: sap_product`
for SAP ECC and SAP S/4HANA version routing; use `builder: flat_product` for
non-SAP or unversioned data products.

### Create `table_settings.default.yaml`

Create `table_settings.default.yaml` in
`src/data_modules/sap_bookingdatamodel/sap/products/flights_usd/` (including
optional declarative
[data quality assertions](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt)):

```yaml
common:
  flights_usd:
    materializationType: incremental
    bigQueryLabels:
      - key: data_class
        value: transactional
    dataformTags: [sap, dataproduct]
    assertions:
      standardRules:
        - ruleType: unique_key
          columns: [client_mandt, airline_code_carrid, flight_connection_number_connid, flight_date_fldate]
          blocking: true
```

Use `common:` when table settings are identical across SAP ECC and SAP S/4HANA,
and use `ecc:` or `s4:` for version-specific settings. A table can't appear in
both `common:` and `ecc:` or `s4:`.

### Create `annotations/flights_usd.yaml`

Create `annotations/flights_usd.yaml` in
`src/data_modules/sap_bookingdatamodel/sap/products/flights_usd/`:

```yaml
description: "Flight scheduling and pricing information, including currency conversion to USD."
fields:
  - name: "client_mandt"
    description: "Client (Mandant)"
  - name: "airline_code_carrid"
    description: "Airline Carrier ID"
  - name: "flight_connection_number_connid"
    description: "Flight Number"
  - name: "flight_date_fldate"
    description: "Flight Date"
  - name: "airfare_price"
    description: "Airfare in local currency"
  - name: "local_currency_currency"
    description: "Local currency of airline"
  - name: "price_usd"
    description: "Price in USD"
  - name: "source_last_updated_at"
    description: "Timestamp of the most recent source record update"
  - name: "bq_loaded_at"
    description: "Timestamp when the record was materialized in BigQuery"
```

### Create `definitions/flights_usd.js`

Create `definitions/flights_usd.js` in
`src/data_modules/sap_bookingdatamodel/sap/products/flights_usd/`. Use
`publish_config.getPublishConfig(...)` and `publisher.publish(...)` from
`includes/` rather than Dataform's global `publish(...)` so table
settings and any upstream `blocking: true` assertions are injected automatically
into the model's `dependencies`, and
[row- and column-level security](https://docs.cloud.google.com/cortex/docs/row-and-column-security.md.txt)
governance hooks (column policy tags, row-level security post-operations DDL,
and zero-fail-open refreshes) apply when security is configured. Pass
`moduleContext.moduleId + "_" + tableConfig.tableName` as the
Dataform action name so multiple instances of the module can
coexist in one workspace without collisions (`publishConfig` sets
`name: tableConfig.tableName` so the materialized BigQuery table
name remains `tableConfig.tableName`):

```javascript
// ___MODULE_CONTEXT___
// ___TABLE_CONFIG___

const incremental = require("includes/incremental.js");
const publish_config = require("includes/publish_config.js");
const publisher = require("includes/publisher.js");
const sql_helper = require("includes/sql_helper.js");

const moduleConfig = config.product[moduleContext.moduleId];
const sapModuleConfigDatasetId = moduleConfig.sources.sapModule.datasetId;
const sapModuleCustNSConfigDatasetId = moduleConfig.sources.sapModuleCustNS.datasetId;

const materializationType = tableConfig.materializationType || "incremental";
const publishConfig = publish_config.getPublishConfig(
  materializationType,
  tableConfig,
  moduleConfig,
  [
    "client_mandt",
    "airline_code_carrid",
    "flight_connection_number_connid",
    "flight_date_fldate",
  ]
);

publisher.publish(moduleContext.moduleId + "_" + tableConfig.tableName, publishConfig).query(
  (ctx) => `
WITH flight_base AS (
  SELECT
    mandt,
    carrid,
    connid,
    fldate,
    price,
    currency,
    recordstamp,
    -- Format flight DATE as a YYYYMMDD integer to calculate SAP's inverted date key
    CAST(99999999 - CAST(FORMAT_DATE('%Y%m%d', fldate) AS INT64) AS STRING) AS inverted_fldate
  FROM ${ctx.ref(sapModuleCustNSConfigDatasetId, "sflight")}
),
ranked_exchange_rates AS (
  SELECT
    f.mandt,
    f.carrid,
    f.connid,
    f.fldate,
    f.price,
    f.currency,
    t.ukurs,
    GREATEST(
      IFNULL(f.recordstamp, TIMESTAMP('1900-01-01 00:00:00+00')),
      IFNULL(t.recordstamp, TIMESTAMP('1900-01-01 00:00:00+00'))
    ) AS source_last_updated_at,
    -- Window function to grab the closest historical exchange rate
    ROW_NUMBER() OVER (
      PARTITION BY f.mandt, f.carrid, f.connid, f.fldate
      ORDER BY t.gdatu ASC
    ) AS latest_rate_rank
  FROM flight_base AS f
  LEFT JOIN ${ctx.ref(sapModuleConfigDatasetId, "tcurr")} AS t
    ON f.mandt = t.mandt
    AND t.kurst = 'M'       -- 'M' is the standard SAP default for average exchange rates
    AND t.fcurr = f.currency
    AND t.tcurr = 'USD'
    -- Chronological (rate_date <= flight_date) translates to (t.gdatu >= inverted_fldate)
    AND t.gdatu >= f.inverted_fldate
)
SELECT
  mandt AS client_mandt,
  carrid AS airline_code_carrid,
  connid AS flight_connection_number_connid,
  fldate AS flight_date_fldate,
  price AS airfare_price,
  currency AS local_currency_currency,
  -- Currency Conversion Logic
  CASE
    WHEN currency = 'USD' THEN price
    WHEN ukurs IS NULL THEN NULL -- Handles cases where no exchange rate is found
    -- Indirect quotation (1 USD = X Local): divide by ABS(ukurs)
    WHEN ukurs < 0 THEN ROUND(price / ABS(ukurs), 2)
    -- Direct quotation (1 Local = X USD): multiply by ukurs
    ELSE ROUND(price * ukurs, 2)
  END AS price_usd,
  source_last_updated_at,
  CURRENT_TIMESTAMP() AS bq_loaded_at
FROM ranked_exchange_rates
${sql_helper.buildDynamicWhere([
  "latest_rate_rank = 1",
  incremental.getFilter(ctx, ["source_last_updated_at"], {
    timestampColumn: "source_last_updated_at",
  }),
])}
`
);
```

This simplified example multiplies or divides directly by `tcurr.ukurs` and
omits SAP `tcurx` decimal shifts and `tcurf` exchange-rate factors. For
production SAP models, use the prebuilt
`cortex.sap.products.currency_conversion` data product and
`includes/currency.js`.

> [!NOTE]
> **Note:** For SAP ERP products whose SQL differs between SAP ECC and SAP S/4HANA, place version-specific definitions inside `definitions/ecc/` and `definitions/s4/`. If you add standalone `.sqlx` or `.js` files directly inside a remote Dataform workspace in the Google Cloud console, keep them under `definitions/custom/` (or add their paths to `targetSettings.ignoredPaths` for `type: dataform` or `targetSettings.ignorePatterns` for `type: git`) so deployments don't prune them.

## Add declarative data quality assertions

You can attach built-in `standardRules` (`non_null`, `unique_key`, `range`,
`foreign_key`, `accepted_values`, `cross_layer_parity`) and parameterized SQL
`customRules` to any custom data product table in `table_settings.default.yaml`
or in an environment-specific `table_settings.yaml` override under `config/`.
Assertion schemas and custom SQL templates validate automatically during
`cortex-build`. Build the Dataform package locally and compile the
generated graph offline before deploying (`uv run cortex-build` connects to
Google Cloud and BigQuery to validate build inputs,
whereas `uv run cortex-compile --dist-dir dist` compiles offline):

```bash
export CORTEX_CONFIG_FILE=config/config.yaml
uv run cortex-build --config $CORTEX_CONFIG_FILE
uv run cortex-compile --dist-dir dist
```

For complete rule schemas, SAP `tcurx` cross-layer parity examples, and custom
SQL template search-path precedence, see
[Data quality assertions](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt).

## Build composite data products

Use the built-in `FlatProductBuilder` (`builder: flat_product`) to create
custom, multi-source, or composite consumption data products without writing a
custom Python builder. `FlatProductBuilder` replaces the deprecated
`GenericProductBuilder` compatibility shim (`generic_product`,
`composite_product`, and `generic_composite_product` are legacy aliases of
`flat_product`), decouples custom data products from SAP ERP version routing
(`ecc` and `s4`), and supports combining foundations, upstream data products,
and external zero-copy catalogs:

- **Flat module directory structure** : Place all Dataform definitions in `definitions/<table_name>.js`, column descriptions in `annotations/<table_name>.yaml`, and table settings at the top level of `table_settings.default.yaml` (`FlatProductTableSettings` rejects `common:` and version-section wrappers).
- **Explicit `materializationType` per table** : Specify `materializationType` explicitly on every table in `table_settings.default.yaml`:
  - Use `materializationType: "view"` when querying zero-copy Delta Sharing catalogs directly.
  - Use `materializationType: "table"` for full-refresh composite tables without `uniqueKeys`.
  - Use `materializationType: "incremental"` together with `uniqueKeys` in `publish_config.getPublishConfig(...)` for watermarked incremental models. (If omitted on `ProductTableItem`, `materializationType` defaults to `incremental`.)
- **Programmatic custom builders without table settings YAML** : `FlatProductBuilder` sets `table_settings_schema = FlatProductTableSettings` and requires either `table_settings.default.yaml` or configured `tableSettings` / `inlineTableSettings`. If you write a custom Python subclass of `FlatProductBuilder` that generates definitions programmatically without a table settings file, set `table_settings_schema = None` on the builder class.
- **Flexible `dependencies` and `dependencyBindings`** : Declare any combination of free-form dependency keys under `dependencies:` in `manifest.yaml` and bind each key under `dependencyBindings` in `config/config.yaml`, as shown in the following table:

| Upstream source type | `manifest.yaml` declaration | `config/config.yaml` binding (`dependencyBindings`) | Resolution in `definitions/*.js` |
| Foundation modules | `cortex.sfdc.foundations.sfdc` or `cortex.sap.foundations.sap` (with required `tables`) | Bound foundation `moduleId` (for example, `sfdc_foundation`) | `moduleConfig.sources.<dependency_key>.datasetId` resolves to the bound foundation's `dataTargetId` (or `dataSourceId` when `external: true`). |
| Upstream data product modules | Product `modulePath` (such as `cortex.sap.products.customers` or `cortex.sfdc.products.accounts`). If `tables` is omitted, all enabled tables from the bound module are resolved automatically. | Bound data product `moduleId` (for example, `sap_delivery_documents`) | `moduleConfig.sources.<dependency_key>.datasetId` resolves to the bound data product's `dataTargetId`. |
| External zero-copy catalogs (`CatalogBuilder`: `analytics_hub` or `lakehouse_delta_share`) | Catalog `modulePath` (such as `cortex.external.weathernext`) | `ResolvedCatalogBinding` reference: `<catalog_id>.<schema_name>` (2-part Delta Sharing or BigQuery sharing table binding), `<catalog_id>.<share_id>.<schema_name>` (3-part Delta Sharing), or `<catalog_id>` (1-part BigQuery sharing catalog) | `moduleConfig.sources.<dependency_key>.projectId`, `.datasetId`, and `.tables`---reference tables with `ctx.ref(source.projectId, source.datasetId, "<table>")`. |
|---|---|---|---|

### Example: Build a composite data product

To build a composite or multi-source data product with `flat_product`:

1. Declare your upstream foundation, data product, or external catalog
   dependencies in `manifest.yaml` with `builder: flat_product`:

   ```yaml
   displayName: Delivery Weather Risk Summary
   description: Combines SAP delivery headers, Salesforce accounts, and WeatherNext forecasts.
   category: consumption_product
   builder: flat_product
   dependencies:
     sapDeliveries:
       modulePath: cortex.sap.products.delivery_documents
       tables:
         - delivery_document_headers
     sfdcFoundation:
       modulePath: cortex.sfdc.foundations.sfdc
       tables:
         - account
     weatherNext:
       modulePath: cortex.external.weathernext
   labels:
     line_of_business: supply_chain
   ```
2. Bind each dependency key in `config/config.yaml` under
   `data.modules.products`:

   ```yaml
   data:
     modules:
       products:
         - moduleId: acme_corp_delivery_weather_risk
           modulePath: acme_corp.sap.products.delivery_weather_risk
           dataTargetId: product_target
           dependencyBindings:
             sapDeliveries: sap_delivery_documents
             sfdcFoundation: sfdc_foundation
             weatherNext: ah_weathernext_catalog.weathernext_3_0_0
   ```

   > [!NOTE]
   > **Note:** Avoid naming a custom namespace `custom`, because `type: dataform` deployment targets ignore `definitions/custom` by default (`targetSettings.ignoredPaths`). If you use a namespace named `custom`, set `targetSettings.ignoredPaths: []` so `uv run cortex-deploy` uploads its compiled definitions.

3. Reference each bound dependency in `definitions/<table_name>.js` using
   `ctx.ref(...)` (passing `(projectId, datasetId, "<table>")` for external
   catalog sources registered through `CatalogBuilder` and
   `ResolvedCatalogBinding`). When joining multiple sources in an incremental
   model, compute `source_last_updated_at` with `GREATEST(...)` across all
   joined watermark columns and pass the table-qualified watermark columns to
   `incremental.getFilter(ctx, [...])` (or pass `{ timestampColumn, targetColumn }`
   when joining custom non-SAP and non-Salesforce sources):

   ```javascript
   // ___MODULE_CONTEXT___
   // ___TABLE_CONFIG___

   const incremental = require("includes/incremental.js");
   const publish_config = require("includes/publish_config.js");
   const publisher = require("includes/publisher.js");
   const sql_helper = require("includes/sql_helper.js");

   const moduleConfig = config.product[moduleContext.moduleId];
   const sapDeliveriesDataset = moduleConfig.sources.sapDeliveries.datasetId;
   const sfdcDataset = moduleConfig.sources.sfdcFoundation.datasetId;
   const weatherSource = moduleConfig.sources.weatherNext;

   const materializationType = tableConfig.materializationType || "incremental";
   const publishConfig = publish_config.getPublishConfig(
     materializationType,
     tableConfig,
     moduleConfig,
     ["sap_delivery_vbeln"]
   );

   publisher.publish(moduleContext.moduleId + "_" + tableConfig.tableName, publishConfig).query(
     (ctx) => `
   SELECT
     d.document_number_vbeln AS sap_delivery_vbeln,
     d.ship_to_party_kunnr AS sap_ship_to_party_kunnr,
     a.Id AS sfdc_account_id,
     a.Name AS sfdc_account_name,
     w.precipitation_probability AS weather_precipitation_probability,
     GREATEST(
       IFNULL(d.source_last_updated_at, TIMESTAMP('1900-01-01 00:00:00+00')),
       IFNULL(a.SystemModstamp, TIMESTAMP('1900-01-01 00:00:00+00'))
     ) AS source_last_updated_at,
     CURRENT_TIMESTAMP() AS bq_loaded_at
   FROM ${ctx.ref(sapDeliveriesDataset, "delivery_document_headers")} AS d
   LEFT JOIN ${ctx.ref(sfdcDataset, "account")} AS a
     ON d.ship_to_party_kunnr = a.SAP_Customer_Number__c
   LEFT JOIN ${ctx.ref(
     weatherSource.projectId,
     weatherSource.datasetId,
     "weathernext_3_0_0"
   )} AS w
     ON d.unloading_point_ablad = w.location_id
   ${sql_helper.buildDynamicWhere([
     incremental.getFilter(ctx, [
       "d.source_last_updated_at",
       "a.SystemModstamp",
     ]),
   ])}
   `
   );
   ```

### Customize product compilation with a Tier 3 SDK builder

If a custom namespace requires bespoke Python compilation logic beyond
`FlatProductBuilder` or `VersionedProductBuilder`, subclass `FlatProductBuilder`
or `VersionedProductBuilder` from `common.sdk` inside
`src/data_modules/<CUSTOM_NAMESPACE>/builders/<builder_name>.py`. Set
`plugin_id` (plus optional `module_settings_schema_cls` and
`table_settings_schema`) and override any of the supported lifecycle hooks:

- `get_effective_table_settings(self, resolved_module: ResolvedProductModule)` and `load_default_table_settings(self, resolved_module)`
- `discover_definitions(self, resolved_module: ResolvedProductModule)` and `discover_definition_files(cls, module_dir, active_variant=None, *, warn_overrides=False)`
- `load_annotations(self, resolved_module, table_name)`
- `build_table_config(self, *, table_name, t_config, module_id, module_path, manifest, ...)`
- `build_module_context(self, resolved_module)`
- `process_definition_file(self, file_path, table_config, module_context)`
- `get_includes_dirs(cls)` and `get_shared_assertion_dirs(cls)`

For example, the following custom builder adds typed `moduleSettings` validation
and injects them into `moduleContext` while restricting discovery to `.js`
definitions:

```python
# src/data_modules/acme_corp/builders/finance_product_builder.py
import pathlib
from typing import Any, ClassVar
import pydantic

from common.sdk import (
    CortexBaseModel,
    FlatProductBuilder,
    FlatProductTableSettings,
    ResolvedProductModule,
)


class FinanceModuleSettings(CortexBaseModel):
    reporting_currency: str = pydantic.Field(alias="reportingCurrency")


class AcmeFinanceProductBuilder(FlatProductBuilder):
    plugin_id: ClassVar[str | None] = "acme_finance_product"
    module_settings_schema_cls = FinanceModuleSettings
    table_settings_schema = FlatProductTableSettings

    def discover_definitions(
        self, resolved_module: ResolvedProductModule
    ) -> dict[str, pathlib.Path]:
        defs_dir = resolved_module.module_dir / "definitions"
        return {p.name: p for p in sorted(defs_dir.glob("*.js")) if p.is_file()}

    def build_module_context(
        self, resolved_module: ResolvedProductModule
    ) -> dict[str, Any]:
        context = super().build_module_context(resolved_module)
        if isinstance(resolved_module.module_settings, FinanceModuleSettings):
            context["reportingCurrency"] = (
                resolved_module.module_settings.reporting_currency
            )
        return context
```

For complete catalog setup and pre-flight validation rules, see
[BigQuery sharing integration](https://docs.cloud.google.com/cortex/docs/source-system-integration/analytics-hub.md.txt)
and
[SAP Business Data Cloud integration](https://docs.cloud.google.com/cortex/docs/source-system-integration/sap-bdc.md.txt).

## Verification of custom namespace extension

Verify your custom Cortex Framework data product module:

1. Run [Cortex Framework deployment](https://docs.cloud.google.com/cortex/docs/deployment.md.txt#execute_deployment)
   referencing your updated `config.yaml` file:

   ```bash
   export CORTEX_CONFIG_FILE=config/config.yaml
   uv run cortex-build-and-deploy --config $CORTEX_CONFIG_FILE
   ```
2. Complete the [Post-deployment steps](https://docs.cloud.google.com/cortex/docs/post-deployment-steps.md.txt) to
   execute the Dataform actions and inspect the materialized rows in
   BigQuery.

## What's next

- Previous step: [Data foundation module creation](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-foundation.md.txt)
- Next step: [Post-deployment steps](https://docs.cloud.google.com/cortex/docs/post-deployment-steps.md.txt)
- Back to [Extensibility guide overview](https://docs.cloud.google.com/cortex/docs/extensibility-guide.md.txt)