# SAP ERP integration for Cortex Framework

> [!IMPORTANT]
> **Important:** The requirements on this page apply to production [deployments](https://docs.cloud.google.com/cortex/docs/deployment.md.txt) of Google Cloud Cortex Framework. For a [demo deployment](https://docs.cloud.google.com/cortex/docs/demo-deployment.md.txt), you can skip these steps.

The Cortex Framework
[data foundation layer](https://docs.cloud.google.com/cortex/docs/overview.md.txt#data_foundation_layer) for SAP ERP
connects to raw source tables replicated into BigQuery from **SAP ECC**
or **SAP S/4HANA**.

Before deploying Cortex Framework modules, replicate the required
SAP ERP application tables and SAP Data Dictionary (DDIC) metadata tables into a
dedicated [raw layer](https://docs.cloud.google.com/cortex/docs/overview.md.txt#raw_layer) dataset in
BigQuery for Change Data Capture (CDC) processing. You can use
any replication tool that lands raw table structures in BigQuery,
including the
[BigQuery Connector for SAP](https://docs.cloud.google.com/sap/docs/bq-connector/latest/overview.md.txt)
(requires SAP Landscape Transformation Replication Server) and the
[BigQuery Toolkit for SAP](https://docs.cloud.google.com/sap/docs/abap-sdk/on-premises-or-any-cloud/latest/bq-toolkit-for-sap-overview.md.txt).

## SAP replication rules

Verify that your SAP ERP replication pipeline satisfies the following
requirements in BigQuery:

- **Raw data structure**: Land data from SAP ECC or SAP S/4HANA in BigQuery with the same table granularity, column names, and semantics as the base tables in SAP without applying business transformations during ingestion.
- **Table configuration** : By default, the SAP data foundation reads `src/data_modules/cortex/sap/foundations/sap/table_settings.default.yaml`. To customize table settings, reference a custom YAML file using `tableSettings` (relative to `config/`, for example, `cortex/sap/foundations/sap/table_settings.yaml`) or define the table list directly with `inlineTableSettings` on the foundation module entry in `config/config.yaml` (`tableSettings` and `inlineTableSettings` are mutually exclusive). For foundation modules, `tableSettings` and `inlineTableSettings` replace `table_settings.default.yaml` completely rather than merging with it. Copy `src/data_modules/cortex/sap/foundations/sap/table_settings.default.yaml` into `config/` and edit the relevant entries in place so you don't drop tables required by enabled prebuilt SAP data products. If your replication pipeline adds prefixes or aliases to raw table names, map them to canonical SAP table names with `source.sapTableName`, and set `source.keys` whenever you need to override primary keys resolved from `DD03L`, as described in [Map custom or prefixed raw table names](https://docs.cloud.google.com/cortex/docs/source-system-integration/sap-erp.md.txt#custom-raw-table-names).
- **SAP DDIC metadata tables** : Replicate `DD03L` into your raw dataset (`dataSourceId` in `config/config.yaml`) because both `uv run cortex-build` (for `external: false` foundations) and `uv run cortex-metadata` require it to resolve primary keys and ABAP data types. Under the default `table_settings.default.yaml`, six DDIC tables (`dd01l`, `dd03l`, `dd04t`, `dd07l`, `dd07t`, and `dd08l`) are materialized in the SAP foundation dataset with `isCdc: false`, `deployAlways: true`, and `dataformTags: [sap,
  foundation, it, sap_basis, once]`. Four additional DDIC tables (`DD03T`, `DD02L`, `DD02T`, and `DD05S`) remain raw-only enrichments read directly from the raw dataset by `uv run cortex-metadata` (pair `DD08L` and `DD05S` for foreign-key joins). For more information about default foundation behavior, table schemas, and fallback behavior, see [SAP Data Dictionary (DDIC) metadata tables](https://docs.cloud.google.com/cortex/docs/source-system-integration/sap-erp.md.txt#sap-ddic-metadata-tables).
- **Lowercase table names** : Create replicated SAP tables in BigQuery with **lowercase** table names (for example, SAP `MARA` becomes `mara`). For DDIC tables, `uv run cortex-build` checks lowercase `dd03l` first and falls back to uppercase `DD03L`, while `uv run cortex-metadata` matches all `DD*` table names case-insensitively.
- **Column names and special characters** : For SAP namespaced tables and fields (`/NAMESPACE/FIELD`), remove the leading `/` and replace remaining `/` characters with an underscore `_` (for example, `/GOOG/TEST` becomes `goog_test` and `/OPT/Z_TABLE` becomes `opt_z_table`). The SAP foundation builder mirrors this normalization when matching raw columns against `DD03L` and projects all replicated raw columns verbatim into conformed foundation tables. Note that first-party SAP foundation annotations and prebuilt SAP data products exclude SAP industry add-on prefixes (`fsh_`, `arun_`, `vso_`, and `dsd_`) because those extensions aren't uniformly present across SAP landscapes.
- **CDC propagation fields** : Include the following technical CDC columns on replicated raw tables when `isCdc: true` (the default):
  - `operation_flag` (`STRING`): Indicates the row change type (`L` = initial load, `I` = insert, `U` = update, `D` = delete). `sap_cdc.js` relies strictly on `operation_flag` (`'D'` triggers `DELETE`) and `recordstamp`.
  - `recordstamp` (`TIMESTAMP`): Records the extraction or replication timestamp used to deduplicate the latest state per primary key.
  - `is_deleted` (`BOOL`, optional): Not read by `sap_cdc.js` during foundation `MERGE` processing; only checked by `uv run cortex-metadata` when filtering deleted rows in CDC-replicated SAP DDIC tables.
  - **Downstream incremental data product deletes** : While `sap_cdc.js` applies hard deletes (`operation_flag = 'D'`) immediately to conformed SAP foundation tables during `MERGE` runs, downstream `incremental` SAP data product tables merge new and updated foundation records by watermark without propagating physical foundation row deletions. Schedule a periodic Dataform full refresh (`--full-refresh`, plus `--vars=cortex_full_refresh=true` when RLS/CLS security governance is enabled) after SAP data archiving runs or physical source deletions to purge deleted records from incremental data product tables.
- **Required data type mappings** : Map SAP temporal types in your replication
  connector during ingestion. Because `sap_cdc.js` passes raw columns through
  verbatim without type conversion, **`DATS` columns must land as
  BigQuery `DATE`** (with initial SAP `'00000000'` values
  converted to `NULL` by the replication connector); landing `DATS` as `STRING`
  fails `uv run cortex-build` partition validation on default `DATE`-partitioned
  SAP tables (such as `bkpf`, `ekko`, `ekpo`, `likp`, and `vbak`):

  | SAP data type | BigQuery data type | Description |
  | `DATS` | `DATE` | Calendar date; the replication connector must map `DATS` to `DATE` and convert initial SAP `'00000000'` values to `NULL` during ingestion. |
  | `TIMS` | `TIME` (or `STRING` `HHMMSS`) | Time-of-day field. |
  |---|---|---|

- **Recommended precision mappings**:

  - Map `CURR` (Currency) and `QUAN` (Quantity) to `NUMERIC` or `BIGNUMERIC`. Avoid `FLOAT64` to prevent rounding drift in financial calculations.
  - Map `NUMC` (Numeric Character) to `STRING` to preserve leading zeros on document numbers and item keys during joins.
- **Deactivated payload compression** : Disable payload compression (or enable
  **Send Uncompressed** ) in your replication connector so empty SAP initial
  values (spaces or zeros) land faithfully rather than converting to `NULL`.

## SAP Data Dictionary (DDIC) metadata tables

Both `uv run cortex-build` and the `uv run cortex-metadata` CLI inspect SAP Data
Dictionary (DDIC) tables directly in the SAP foundation's raw
BigQuery dataset (the `data.datasets` entry referenced by
`dataSourceId` in `config/config.yaml`).

By default,
`src/data_modules/cortex/sap/foundations/sap/table_settings.default.yaml` maps
six of the ten DDIC tables into the SAP foundation dataset as non-CDC
full-snapshot tables (`isCdc: false`, `deployAlways: true`,
`dataformTags: [sap, foundation, it, sap_basis, once]`): `dd01l`, `dd03l`,
`dd04t`, `dd07l`, `dd07t`, and `dd08l`. The remaining four DDIC tables
(`DD03T`, `DD02L`, `DD02T`, and `DD05S`) remain in the raw dataset only and
aren't materialized in the SAP foundation dataset by default. If you need any
of those four raw-only tables in the foundation dataset for custom SQL---or want
to omit optional `deployAlways: true` DDIC tables you haven't replicated---copy
`table_settings.default.yaml` into a custom `tableSettings` file (or
`inlineTableSettings`) and edit the table entries accordingly.

Both `uv run cortex-build` (for `external: false` foundations) and
`uv run cortex-metadata` require `DD03L` in the raw dataset (`cortex-build`
checks lowercase `dd03l` first and falls back to uppercase `DD03L`, while
`cortex-metadata` matches all `DD*` table names case-insensitively). The other
five `deployAlways: true` DDIC tables (`dd01l`, `dd04t`, `dd07l`, `dd07t`, and
`dd08l`) are optional for `uv run cortex-metadata` and don't trigger a
`CortexBuildError` during `uv run cortex-build` if absent (because
`isCdc: false` doesn't require primary-key discovery). However, `cortex-build`
still generates unconditional Dataform `operate()` actions for
them with fallback stub columns (`mandt`, `recordstamp`, and `operation_flag`),
and executing those Dataform actions fails at runtime if the raw
tables aren't replicated. Either replicate all six default DDIC tables or remove
the un-replicated entries from your custom `tableSettings` (or
`inlineTableSettings`). Pair `DD08L` and `DD05S` together for foreign-key joins
in `cortex-metadata erd`.

The following table lists the SAP DDIC tables used by
Cortex Framework and
[`uv run cortex-metadata`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-metadata.md.txt), their default
foundation materialization status (`deployAlways: true` versus raw-only), the
columns read from each table, where the extracted metadata is stored in the
local metadata cache, and fallback behavior when a table is absent:

| DDIC table | Metadata requirement | Default in foundation | Used for | Columns read | Stored in metadata cache as | Behavior if missing |
| `DD03L` | **Required** | Materialized (`deployAlways: true`, `isCdc: false`) | Table fields: field position, primary key flag, ABAP data type, length, decimals, data element, domain, check table, and currency or unit reference. | `tabname`, `fieldname`, `position`, `keyflag`, `rollname`, `domname`, `datatype`, `leng`, `decimals`, `checktable`, `reftable`, `reffield` | `tableProperties.primaryKeys`, `columns[].sap.*` (`position`, `abapType`, `length`, `decimals`, `dataElement`, `domain`, `checkTable`, `refTable`, `refField`) | `uv run cortex-build` fails with `CortexBuildError` for `external: false` foundations when neither `dd03l` nor `DD03L` is found. `uv run cortex-metadata` logs `[ERROR]` and produces no DDIC metadata (exits with code `1` when running `cortex-metadata fetch --strict` on a single raw table). |
| `DD04T` | Optional | Materialized (`deployAlways: true`, `isCdc: false`) | Data element descriptions and short, medium, long, and heading UI labels. | `rollname`, `ddlanguage`, `ddtext`, `reptext`, `scrtext_s`, `scrtext_m`, `scrtext_l` | `columns[].description`, `columns[].sap.labels` | Fewer column descriptions and no data-element screen labels are recorded. Generated foundation action fails at runtime unless `dd04t` is replicated or removed from `tableSettings`. |
| `DD03T` | Optional | Raw-only | Direct field descriptions for table fields that don't reference a data element or lack `DD04T` text. | `tabname`, `fieldname`, `ddlanguage`, `ddtext` | `columns[].description` (with `columns[].sap.textSource: DD03T`) | Fields without a named data element receive no column description. |
| `DD01L` | Optional | Materialized (`deployAlways: true`, `isCdc: false`) | Domain-level conversion routines (such as `ALPHA` leading-zero padding). | `domname`, `convexit` | `columns[].sap.conversionExit` | No domain conversion exit metadata is recorded. Generated foundation action fails at runtime unless `dd01l` is replicated or removed from `tableSettings`. |
| `DD07L` | Optional | Materialized (`deployAlways: true`, `isCdc: false`) | Fixed domain value codes and value ranges (capped at 200 values per field). | `domname`, `valpos`, `domvalue_l`, `domvalue_h` | `columns[].sap.domainValues[]` (sets `domainValuesTruncated: true` if capped) | No enumerated domain values are recorded. Generated foundation action fails at runtime unless `dd07l` is replicated or removed from `tableSettings`. |
| `DD07T` | Optional | Materialized (`deployAlways: true`, `isCdc: false`) | Language-dependent descriptions for fixed domain values in `DD07L`. | `domname`, `valpos`, `ddlanguage`, `ddtext` | `columns[].sap.domainValues[].text` | Domain values are cached without human-readable descriptions. Generated foundation action fails at runtime unless `dd07t` is replicated or removed from `tableSettings`. |
| `DD02L` | Optional | Raw-only | SAP table classification (transparent, cluster, pool, or view) and delivery class. | `tabname`, `tabclass`, `contflag` | `tableProperties.sap.tableClass`, `tableProperties.sap.deliveryClass` | No SAP table class or delivery class is recorded. |
| `DD02T` | Optional | Raw-only | Language-dependent table descriptions. | `tabname`, `ddlanguage`, `ddtext` | Table `description` (populated when the BigQuery table has no description) | No fallback DDIC table description is populated. |
| `DD08L` | Optional (pair with `DD05S`) | Materialized (`deployAlways: true`, `isCdc: false`) | Declared foreign-key header relationships and cardinality. | `tabname`, `fieldname`, `checktable`, `frkart`, `cardleft`, `card` | `tableProperties.sap.foreignKeys[]` | No foreign-key relationship objects are recorded (per-field `checkTable` still resolves from `DD03L`). Generated foundation action fails at runtime unless `dd08l` is replicated or removed from `tableSettings`. |
| `DD05S` | Optional (pair with `DD08L`) | Raw-only | Composite foreign-key join column mappings for relationships declared in `DD08L`. | `tabname`, `fieldname`, `primpos`, `fortable`, `forkey` (plus `checktable`, `checkfield` when present) | `tableProperties.sap.foreignKeys[].fields[]` | Foreign keys lack multi-column join predicates, so `cortex-metadata erd` adds a note instead of drawing those edges. |
|---|---|---|---|---|---|---|

### DDIC filtering and language rules

When reading replicated DDIC tables from BigQuery, the metadata
extractor applies the following rules automatically:

- **Active dictionary state** : Retains only active ABAP Dictionary rows (`as4local = 'A'`) and the current object version (`as4vers` blank or `'0000'`) whenever those columns exist on the replicated DDIC table.
- **CDC deduplication** : If your replication tool lands DDIC tables with CDC metadata, the extractor keeps the latest row per DDIC key ordered by `recordstamp` and drops rows marked deleted (`is_deleted = TRUE` or `operation_flag = 'D'`).
- **Language fallback** : For text tables (`DD04T`, `DD03T`, `DD07T`, and `DD02T`), the extractor prefers English (`ddlanguage = 'E'`) and falls back to the first available language (`textLanguage`) when English texts aren't present.
- **Missing-table diagnostics and un-replicated tables** : Any missing optional DDIC tables produce a single grouped `[WARN]` summary naming the skipped metadata attributes. If a table exists in `DD03L` (enriched by any available optional DDIC tables) even though the physical application table hasn't been replicated to BigQuery yet, `uv run cortex-metadata fetch
  RAW_DATA_SOURCE_ID --table
  TABLE_NAME` (for example, `uv run cortex-metadata fetch sap_raw --table mara`) still caches its DDIC definition with `tableProperties.tableType: DDIC_ONLY` (`sourceType: sap_ddic`) so you can inspect keys and schemas before ingestion.

### Recommended DDIC replication tiers

Choose the replication scope that matches your workflow:

- **Minimum build tier (`DD03L`)** : Replicate `DD03L` when you only need `cortex-build` to resolve primary keys and technical field definitions for foundation CDC models.
- **Semantic documentation and AI agent tier (`DD03L`, `DD04T`, `DD03T`,
  `DD02T`)** : Add the text tables so [agentic skills](https://docs.cloud.google.com/cortex/docs/agentic-skills-for-data-product-building.md.txt), [Knowledge Catalog](https://docs.cloud.google.com/cortex/docs/knowledge-catalog.md.txt), and [conversational analytics](https://docs.cloud.google.com/cortex/docs/conversational-analytics.md.txt) data agents receive business-friendly table and column descriptions.
- **Full modeling, validation, and ERD tier (all 10 DDIC tables)** : Replicate `DD08L` and `DD05S` together to render SAP foreign-key relationships in `uv run cortex-metadata erd`, and include `DD01L`, `DD07L`, `DD07T`, and `DD02L` to expose `ALPHA` conversion exits, allowed domain values for [data quality assertions](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt), and table delivery classes.

## Configure SAP ERP modules

In `config/config.yaml`, register the `cortex.sap.foundations.sap` foundation
module and bind downstream SAP data products under `data.modules.products`:

```yaml
data:
  modules:
    foundations:
      - moduleId: erp
        modulePath: cortex.sap.foundations.sap
        dataSourceId: sap_raw
        dataTargetId: sap_foundation
        # Optional custom table settings file (relative to 'config/') or
        # inlineTableSettings; replaces table_settings.default.yaml completely:
        # tableSettings: "cortex/sap/foundations/sap/table_settings.yaml"
        moduleSettings:
          sapVersion: s4
          mandt: "100"
    products:
      - moduleId: sap_addresses
        modulePath: cortex.sap.products.addresses
        dataTargetId: sap_products
        dependencyBindings:
          sapModule: erp
      - moduleId: sap_customers
        modulePath: cortex.sap.products.customers
        dataTargetId: sap_products
        dependencyBindings:
          sapModule: erp
```

## Hard deletes and incremental refresh cadence

When your SAP replication pipeline marks a source record as physically deleted
(`operation_flag = 'D'`), the SAP data foundation CDC merge (`sap_cdc.js`)
removes the row from the foundation table. However, downstream data products
configured with `materializationType: incremental` run upsert-only merges and
don't delete rows removed from foundation tables.

This behavior also applies to SAP ECC open-item tables (`vendor_open_items`
backed by `BSIK` and `customer_open_items` backed by `BSID`): when an open item
is cleared in SAP ECC, SAP deletes the record from `BSIK` or `BSID` and inserts
it into `BSAK` or `BSAD`. Downstream consumption products such as
`accounts_payable_insights` and `accounts_receivable_insights` reconcile open
versus cleared images automatically, but the source-aligned `vendor_open_items`
and `customer_open_items` tables retain cleared rows until refreshed.

For incremental SAP data products backed by tables subject to physical deletes
or open-item clearing, schedule a periodic Dataform full refresh
(see [Run a targeted full refresh](https://docs.cloud.google.com/cortex/docs/upgrade/overview.md.txt#execute-full-refresh))
or override `materializationType` to `table` in a sparse product
`tableSettings` override file.

## Map custom or prefixed raw table names

Enterprise replication tools frequently land SAP tables in
BigQuery under system-prefixed or aliased physical names (for
example, `raw_bkpf` or `sap_s4d_but000` instead of `bkpf` or `but000`). To
ingest those tables without renaming them in your raw landing dataset, specify
both `source.tableName` and `source.sapTableName` in your custom SAP foundation
`table_settings.yaml` file (wired with `tableSettings` in `config/config.yaml`)
or under `inlineTableSettings`.

> [!IMPORTANT]
> **Important:** On foundation modules, `tableSettings` and `inlineTableSettings` replace `src/data_modules/cortex/sap/foundations/sap/table_settings.default.yaml` completely rather than merging with it. Copy `table_settings.default.yaml` into your `config/` directory and edit the relevant table entry in place; declaring only a single table drops all other SAP foundation tables and fails validation for enabled prebuilt SAP data products.

You can also declare `source.keys` to override primary keys resolved from
`DD03L`. The following excerpt shows a customized `bkpf` entry under `common:`
in a copied `table_settings.yaml` file:

```yaml
common:
  # Retain the remaining entries copied from table_settings.default.yaml.
  - source:
      tableName: RAW_BQ_TABLE_NAME
      sapTableName: CANONICAL_SAP_TABLE
      # Optional: override primary keys read from DD03L:
      # keys: [mandt, bukrs, belnr, gjahr]
    target:
      tableName: TARGET_FOUNDATION_TABLE
      clusterDetails:
        columns: [mandt, bukrs, belnr, gjahr]
```

Replace the following:

- `RAW_BQ_TABLE_NAME`: the physical table name in your raw BigQuery dataset, for example: `raw_bkpf`.
- `CANONICAL_SAP_TABLE`: the canonical SAP table name in `DD03L` and `annotations/*.yaml`, for example: `bkpf` (defaults to `source.tableName` when omitted).
- `TARGET_FOUNDATION_TABLE`: optional conformed output table name in your SAP foundation dataset, for example: `bkpf` (defaults to `source.sapTableName`, or `source.tableName` if `sapTableName` isn't set).

When `source.sapTableName` is configured, Cortex Framework reads
physical columns from `source.tableName` in BigQuery, looks up
primary keys in `DD03L` using `SAPTABLENAME` (uppercase) unless `source.keys`
overrides them, attaches field descriptions from
`annotations/<sapVersion>/<sapTableName>.yaml` (falling back to
`annotations/<sapTableName>.yaml`), and publishes the conformed table using the
canonical name so downstream data products don't require SQL changes.