# Data quality assertions

Google Cloud Cortex Framework provides declarative data validation built on
Dataform assertions in BigQuery. Instead of maintaining
standalone assertion scripts per environment, you declare standard or custom SQL
validation rules alongside each table in `table_settings.yaml`. During
`uv run cortex-build`, Cortex Framework compiles those rules into
BigQuery assertion views, wires DAG dependencies, and enforces
optional pipeline circuit breakers.

## How assertions work

Every assertion in Cortex Framework follows a **defect-query
contract**:

- **Zero rows = Pass** : The generated or custom `SELECT` query searches for **violating rows** , such as duplicate keys, unexpected `NULL` values, orphaned foreign keys, or cross-layer metric discrepancies.
- **One or more rows = Fail** : If the query returns at least one row, the Dataform assertion fails and BigQuery materializes a diagnostic view of the offending records in the configured assertion dataset (`dataform_assertions` by default).

Cortex Framework supports two enforcement modes controlled per
rule with `blocking: false` (default) or `blocking: true`. Execution behavior
depends on the architecture layer:

### Non-blocking audit (`blocking: false`, default)

With `blocking: false`, assertions run alongside downstream consumers without
halting pipeline execution. Failing rules record offending rows in
`dataform_assertions` and write error entries to Cloud Logging for monitoring
and triage.

### Downstream DAG gate (`blocking: true`)

For data products and Salesforce (`sfdc`) foundations, assertions evaluate
immediately after the target table materializes. Setting `blocking: true`
records the assertion in `includes/config.js` (`config.blockingAssertions`) and
injects Dataform DAG dependencies into every downstream model published
through `publisher.publish()` or `publisher.operate()` that calls `ctx.ref(...)`.
When defects appear, Dataform skips (`CANCELLED`) downstream consumers
before bad data propagates.

### Transactional target gate for SAP (`blocking: true`)

For SAP foundation tables (`sap_cdc.js`, published through
`publisher.operate()`), setting `blocking: true` provides **both** downstream
DAG gating **and** in-transaction target protection:

- **Incremental CDC (`MERGE`) and non-CDC full reloads (`DELETE` and
  `INSERT`)** : Blocking checks execute inside a BigQuery `BEGIN TRANSACTION ... COMMIT TRANSACTION` block. If any row violates a blocking rule, BigQuery executes `ROLLBACK TRANSACTION` and raises an error, preventing corrupt delta batches from committing to the foundation table.
- **Initial table creation (`CREATE OR REPLACE TABLE`)** : If a blocking check fails during the initial load, Cortex Framework executes `DROP TABLE IF EXISTS` on the newly created target table before raising the error so invalid initial loads don't persist.

## Before you begin

Before configuring and validating data quality assertions, verify the following
prerequisites:

### Enable Google Cloud APIs

Complete the local environment, authentication, and project setup in
[Prerequisites](https://docs.cloud.google.com/cortex/docs/prerequisites.md.txt). Then verify that the required
[Google Cloud services](https://docs.cloud.google.com/cortex/docs/prerequisites.md.txt#enable-services) are
enabled in your deployment projects, or pass `--enable-apis` during deployment:

```bash
gcloud services enable bigquery.googleapis.com \
    dataform.googleapis.com \
    --project=PROJECT_ID
```

Replace the following:

- `PROJECT_ID`: Google Cloud project ID hosting your Dataform repository and target datasets, for example: `my-cortex-project`.

### Get the required roles


To get the permissions that
you need to deploy and execute Cortex Framework data quality assertions,

ask your administrator to grant you the
following IAM roles:

- Deploy assertion datasets (`uv run cortex-build-and-deploy` or `uv run cortex-deploy` with `--create-datasets`):
  - [BigQuery Data Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataEditor) (`roles/bigquery.dataEditor`) on target projects hosting `data.defaultAssertionDataset`
  - [Dataform Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/dataform.md.txt#dataform.admin) (`roles/dataform.admin`) on `repositoryProjectId` for `dataform` deployment targets
  - [Service Usage Consumer](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage.md.txt#serviceusage.serviceUsageConsumer) (`roles/serviceusage.serviceUsageConsumer`) on `buildProjectId` and target projects
- Execute assertion workflows (Dataform service agent or custom workflow service account):
  - [BigQuery Data Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataEditor) (`roles/bigquery.dataEditor`) on `data.defaultAssertionDataset` and materialized foundation or product target datasets
  - [BigQuery Data Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataViewer) (`roles/bigquery.dataViewer`) on all foundation and data product datasets referenced by assertions
  - [BigQuery Job User](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.jobUser) (`roles/bigquery.jobUser`) on the Dataform repository project


For more information about granting roles, see [Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).


You might also be able to get
the required permissions through [custom
roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles) or other [predefined
roles](https://docs.cloud.google.com/iam/docs/roles-overview#predefined).

> [!NOTE]
> **Note:** You can substitute Dataform Editor (`roles/dataform.editor`) for `roles/dataform.admin` when the target Dataform repository already exists. For project-level `gcloud` role-binding commands across build, source, and target projects, see [Configure Identity and Access Management (IAM) roles](https://docs.cloud.google.com/cortex/docs/deployment.md.txt#roles-for-target-projects) in the Deployment guide.

### Prepare assertion dataset and local tools

- **Target assertion dataset (`data.defaultAssertionDataset`)** : Created in each target project hosting at least one materialized foundation or product target dataset (default: `dataform_assertions`). Provisioned automatically when you pass `--create-datasets` to `uv run cortex-deploy` or `uv run cortex-build-and-deploy` with an enabled `type: dataform` deployment target. When all enabled targets in `deployment.targets` use `type: git`, Google Cloud dataset creation is skipped and you must pre-create `data.defaultAssertionDataset` in each target project manually. Don't pass `--create-datasets` to `uv run cortex-build`, where it is deprecated and has no effect.
- **Local Dataform compiler (optional)** : To compile and verify the generated Dataform project and assertion graph locally with [`uv run cortex-compile`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-compile.md.txt), install Node.js (`npx`) or `@dataform/cli` in your `PATH`. See [Install Dataform CLI for offline compilation checks](https://docs.cloud.google.com/cortex/docs/prerequisites.md.txt#dataform-cli).

## Configure global assertion settings

Global assertion settings live under the `data` block of your deployment
configuration file (`config/config.yaml`):

```yaml
data:
  bigQueryLocation: US
  # Global kill-switch for all compiled data quality assertions (default: true).
  assertionsEnabled: true
  # Single BigQuery dataset in each target project where assertion views materialize.
  defaultAssertionDataset: dataform_assertions

  # Optional: Allowed severity labels (must match ^[a-zA-Z0-9_-]+$).
  assertionSeverities:
    - P0
    - P1
    - P2

  # Required when assertionSeverities is set; must be in assertionSeverities.
  defaultAssertionSeverity: P2
```

> [!NOTE]
> **Note:** `config/config.yaml` enforces strict `camelCase` schema validation (`extra="forbid"`). Using `snake_case` keys such as `assertions_enabled` or `default_assertion_dataset` fails configuration validation at build time.

The following table describes the global assertion settings in
`config/config.yaml`:

| Key | Type | Default | Description |
| `data.assertionsEnabled` | `boolean` | `true` | Global kill-switch controlling whether Cortex Framework emits Dataform assertion actions, downstream blocking dependencies, and in-transaction SAP CDC assertion checks across all foundations and products. Set to `false` to suppress all assertion execution without editing `table_settings.yaml`. Build-time schema, severity, and template validation still runs when set to `false`. |
| `data.defaultAssertionDataset` | `string` | `"dataform_assertions"` | Single BigQuery dataset in each target project where Dataform compiles all assertion views across foundation and product modules (no per-module or per-table override). Must be a valid BigQuery dataset identifier (`[A-Za-z0-9_]`, up to 1,024 characters). If you run multiple Cortex Framework deployments in the same Google Cloud project, configure a unique `defaultAssertionDataset` per deployment (or set `assertionsEnabled: false`) so assertion views don't overwrite each other. Renaming this dataset after deployment doesn't drop views created under the previous name. |
| `data.assertionSeverities` | `list[string]` | None | Allowed severity labels across all modules in the deployment (matching `^[a-zA-Z0-9_-]+$`). Commas and whitespace are rejected because resolved values are emitted as Dataform tags (`severity_<value>`). |
| `data.defaultAssertionSeverity` | `string` | None | Fallback severity applied to any rule that omits `severity`. Must be set whenever `data.assertionSeverities` is non-empty, and must appear in `data.assertionSeverities`. |
|---|---|---|---|

> [!NOTE]
> **Note:** Out-of-the-box assertions ship enabled with `blocking: false` on select SAP foundation tables (`makt` and `vbak`), SAP data product modules (including `sales_documents`, `purchasing_documents`, `universal_journal`, `financial_statements`, `accounts_payable_insights`, `accounts_receivable_insights`, `vendors`, `customers`, `business_partners`, and `addresses`), and the `cortex_samples` `sales_performance` products (SAP ERP and SAP BDC). The `cortex_samples` weather-risk products ship with `blocking: true` on primary-key (`unique_key`) and `non_null` rules for `inbound_delivery_insights`, `world_city_directory`, and `world_port_index_directory`, and `blocking: false` on their remaining rules. Set `data.assertionsEnabled: false` to disable all compiled assertions globally during initial onboarding.

Severity validation follows two build-time rules:

- **When `data.assertionSeverities` is omitted** : Setting `severity` on any rule in `table_settings.yaml` fails the build (`CortexConfigError`), preventing silent typos in unconfigured environments. No `severity_*` tag is emitted.
- **When `data.assertionSeverities` is configured** : Every rule without an explicit `severity` inherits `data.defaultAssertionSeverity`, and any rule declaring a `severity` outside `data.assertionSeverities` fails the build.

## Configure table-level assertions

Configure assertions per table in a module's custom `table_settings.yaml` file
(referenced through `tableSettings` on the module entry in `config/config.yaml`,
or inline through `inlineTableSettings`). All assertion configuration models
enforce strict key validation (`extra="forbid"`): unrecognized fields fail
`uv run cortex-build` immediately with an actionable error message.

### Placement by module type

The placement of the `assertions` block in `table_settings.yaml` depends on the
module schema structure.

#### SAP data products (`ecc`, `s4`, and `common` sections)

SAP data product schemas group tables under `ecc`, `s4`, or `common` section
keys:

```yaml
s4:
  sales_document_headers:
    enabled: true
    assertions:
      enabled: true
      lookbackDays: 7
      standardRules:
        - ruleType: unique_key
          blocking: true
          severity: P0
        - ruleType: non_null
          columns: [client_mandt, document_number_vbeln]
          blocking: true
          severity: P0
```

#### Flat data products (Salesforce, SAP BDC, and custom or generic products)

Flat product schemas map table names directly at the root of
`table_settings.yaml`. Top-level `ecc`, `s4`, and `common` section keys are
rejected:

```yaml
opportunities:
  enabled: true
  assertions:
    enabled: true
    standardRules:
      - ruleType: unique_key
        blocking: true
      - ruleType: non_null
        columns: [opportunity_id, account_id]
```

#### SAP and Salesforce foundations

Foundation `table_settings.yaml` files define lists of `source` and `target`
mappings. Configure assertions under `target.assertions` consistently across
both SAP and Salesforce foundations (entry-level `assertions` is also accepted
for compatibility, but `target.assertions` takes precedence when both are
present):

For SAP foundations, group table mappings under `ecc`, `s4`, or `common`.
Because a custom foundation `table_settings.yaml` file replaces
`table_settings.default.yaml` completely rather than merging per table, copy
`src/data_modules/cortex/sap/foundations/sap/table_settings.default.yaml` and
edit the relevant table entries in place:

```yaml
# SAP Foundation example (under ecc:, s4:, or common:)
common:
  - source:
      tableName: vbak
    target:
      tableName: vbak
      assertions:
        enabled: true
        standardRules:
          - ruleType: non_null
            columns: [mandt, vbeln]
            blocking: true
```

For Salesforce foundations, list table mappings at the root of
`table_settings.yaml`:

```yaml
# Salesforce Foundation example (root YAML list)
- source:
    tableName: Account
  target:
    tableName: account
    assertions:
      enabled: true
      standardRules:
        - ruleType: unique_key
          columns: [Id]
          blocking: true
```

#### Version 6 compatibility views (`cortex_v6_compatibility`)

Modules in the [v6 compatibility](https://docs.cloud.google.com/cortex/docs/v6-compatibility.md.txt) layer
(`src/data_modules/cortex_v6_compatibility/sap/products/`) declare their
published `PascalCase` BigQuery table and view names using
`tableName` in `table_settings.default.yaml` (such as `AccountsPayable` or
`SalesOrders_V2`) and project `PascalCase_SAPFIELD` column names (such as
`Client_MANDT` and `CompanyCode_BUKRS`).

Because data product overrides merge with `table_settings.default.yaml`, you can
attach declarative `assertions` directly under the `snake_case` YAML key (for
example, `sales_orders_v2` or `accounts_payable`) while preserving the default
`tableName` and referencing the model's `PascalCase_SAPFIELD` columns. You can
also configure assertions on the upstream `cortex.sap.foundations.sap`
foundation tables that feed the compatibility models.

### Enable, disable, and manage partial deployments

You can enable or disable validation at three levels:

- **Workspace level** : Set `data.assertionsEnabled: false` in `config/config.yaml` to suppress all compiled assertions, downstream blocking dependencies, and in-transaction SAP CDC assertion checks across the workspace without editing `table_settings.yaml`. For more information, see [Configure global assertion settings](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt#global-settings).
- **Table level** : Set `assertions.enabled: false` in `table_settings.yaml` to skip generating all assertions for that table.
- **Rule level** : Set `enabled: false` on an individual standard or custom rule to skip only that rule while keeping the rest of the table's assertions active.

Disabled rules still undergo static build-time checks:

- **Static authoring checks always run** : Schema syntax, unknown field checks, `templateFile` existence, `${param}` placeholder completeness, severity vocabulary membership, duplicate rule names, and BigQuery identifier length limits (`<= 1,024` characters) run even when `data.assertionsEnabled: false` or `enabled: false`, so disabled rules don't rot silently.
- **Upstream table references resolve in Dataform** : `parentTable` and `${ref(...)}` targets are resolved when Dataform compiles the project, and only enabled rules on enabled tables are compiled when `data.assertionsEnabled` is `true`. Foundation builds automatically retain parent tables required by enabled rules. If a partial deployment omits an upstream table in another module, set `enabled: false` on that rule instead of deleting its YAML block.

## Control pipeline gating, tags, and custom models

Cortex Framework separates **pipeline execution control**
(`blocking`) from **operational triage priority** (`severity`) and **selective
execution filtering** (`tags`).

The following table compares `blocking` and `severity`:

| Property | Purpose | Effect on BigQuery and Dataform execution |
| `blocking: true` | Pipeline circuit breaker | Halts downstream `publisher.publish()` and `publisher.operate()` consumers on failure. On SAP foundation tables, also rolls back incremental CDC and full-reload transactions (or drops initial loads) before corrupt data persists. Note that `cross_layer_parity` supports `blocking: false` only. |
| `blocking: false` (default) | Audit and observability mode | Materializes defect rows in `<defaultAssertionDataset>.<action_name>` (`dataform_assertions` by default) and marks the assertion action failed in workflow logs without halting downstream tables or rolling back merges. |
| `severity: <label>` | Operational classification | Adds tag `severity_<label>` to the compiled Dataform assertion action for selective execution (`--tags severity_P0`) and alert routing. Doesn't change blocking behavior on its own. |
|---|---|---|

### Automatically attached Dataform tags

Every compiled assertion action inherits any table-level `dataformTags` defined
on the table plus:

- `data_quality`
- `assertion`
- `severity_<value>` (when `data.assertionSeverities` is configured)
- Either `blocking_assertion` (when `blocking: true`) or `non_blocking_audit` (when `blocking: false`)
- Any additional rule-level `tags` declared on a `customRules` entry

### Publish custom models with `publisher.publish()` and `publisher.operate()`

Downstream DAG blocking gates operate at Dataform compile time through
`includes/publisher.js`. Any custom JavaScript definition file in a custom or
extended data product or foundation **must** publish through
`publisher.publish(...)` (for tables, incremental tables, and views) or
`publisher.operate(...)` (for SQL operations, as used by SAP foundation CDC
models) rather than Dataform's global `publish(...)` or `operate(...)`:

```javascript
const publisher = require("includes/publisher.js");

const tableName = "custom_sales_summary";
const publishConfig = {
  type: "table",
  name: tableName,
  uniqueKey: ["client_mandt", "document_number_vbeln"],
};

publisher.publish(tableName, publishConfig).query((ctx) => `
  SELECT
    client_mandt,
    document_number_vbeln,
    SUM(net_value_of_the_sales_document_in_document_currency_netwr) AS total_net_value
  FROM ${ctx.ref("sales_document_headers")}
  GROUP BY client_mandt, document_number_vbeln
`);
```

> [!NOTE]
> **Note:** Calling bare `publish(...)`, calling bare `operate(...)`, or authoring models as raw SQLX files compiles without error, **but bypasses
> `publisher.js` hooks** . Upstream `blocking: true` assertions won't gate those downstream models automatically.

## Configure standard assertion rules

Standard rules live under `assertions.standardRules` and accept common options
(`ruleType`, `name`, `enabled`, `blocking`, `severity`, `prunePartition`, and
`lookbackDays`) plus rule-specific fields.

> [!NOTE]
> **Note:** `table_settings.yaml` accepts both `camelCase` (recommended across Cortex Framework configuration files) and `snake_case` field names inside `assertions`, while rejecting unknown keys. Rule and metric `name` identifiers must match `^[a-zA-Z0-9_]+$`. Schema validation accepts dot-separated column paths matching `^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)*$` in `columns`, `parentColumns`, `parentFilter`, `childFilter`, and parity metric column fields (`column`, `parentColumn`, `currencyColumn`, and `parentCurrencyColumn`), and normalizes dots to `_` in derived assertion action names. However, `assertion_helper.js` quotes each column path as a single backticked identifier---so BigQuery nested `STRUCT` field checks require `customRules`---and emits raw column strings in the `cross_layer_parity` `metric` output column unless you configure an explicit metric `name`.

The following table summarizes the standard rule types:

| `ruleType` | Required fields | Optional rule fields | Supports `blocking: true` | Supports `prunePartition: true` | `NULL` handling |
| `non_null` | `columns` (`>= 1`) | None | Yes | Yes | Fails when **any** listed column `IS NULL`. |
| `unique_key` | None (inherits model keys if `columns` is omitted) | `columns` (`>= 1`) | Yes | Yes | Groups keys using BigQuery `GROUP BY` semantics (`NULL` tuples group together if present; pair with `non_null` on primary keys). |
| `range` | `columns` (exact length `1`), plus `minValue` or `maxValue` | `minValue`, `maxValue` (`int` or `float`) | Yes | Yes | `NULL` values pass; pair with `non_null` if required. |
| `foreign_key` | `columns` (`>= 1`), `parentTable` | `parentColumns` (same length as `columns`) | Yes | Yes (prunes child table) | Rows where **any** child key column `IS NULL` pass without probing the parent. |
| `accepted_values` | `columns` (`>= 1`), `allowedValues` (`>= 1` non-boolean literals) | None | Yes | Yes | `NULL` values pass; pair with `non_null` if required. |
| `cross_layer_parity` | `columns` (`>= 1`), `parentTable`, `metrics` (`>= 1`) | `parentColumns`, `tolerance`, `compareRowCounts`, `parentFilter`, `childFilter` | No | No | Aggregates metrics with `COALESCE(SUM(...), 0)` per key group. |
|---|---|---|---|---|---|

### Required columns (`non_null`) and keys (`unique_key`)

- **`non_null`** : Fails when any row contains `NULL` in one or more specified
  columns (`col1 IS NULL OR col2 IS NULL`):

  ```yaml
  - ruleType: non_null
    columns: [mandt, bukrs, belnr, gjahr]
    blocking: true
    severity: P0
  ```

  > [!NOTE]
  > **Note:** By default, `sap_cdc.js` filters out source rows with `NULL` primary keys (`WHERE key IS NOT NULL`). When you configure an enabled `blocking: true` `non_null` rule on a primary key column of an SAP foundation table, `sap_cdc.js` disables that silent filter for that column so `NULL` key records surface and fail the transaction explicitly.

- **`unique_key`** : Fails when duplicate rows exist across the key tuple
  (`GROUP BY ... HAVING COUNT(*) > 1`). If `columns` is omitted,
  Cortex Framework inherits the `uniqueKeys` passed to
  `publish_config.getPublishConfig(...)` (for products) or `keys` (for
  foundations). If neither the rule nor the table model defines primary keys,
  compilation fails explicitly. Use `unique_key` on SAP text tables such as
  `makt` (`[mandt, matnr, spras]`) to prevent multi-language join fan-out:

  ```yaml
  # Inherits primary keys automatically from the table model
  - ruleType: unique_key
    blocking: true
    severity: P0

  # Explicit composite key check with disambiguated name
  - ruleType: unique_key
    name: unique_document_line
    columns: [mandt, vbeln, posnr]
  ```

### Numeric bounds (`range`) and domains (`accepted_values`)

- **`range`** : Validates that a **single numeric column** falls within inclusive
  `[minValue, maxValue]` bounds (`int` or `float`, where `minValue` can't
  exceed `maxValue`). Multi-column `range` rules fail schema validation. For
  `DATE` or `TIMESTAMP` comparisons, write a
  [custom SQL rule](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt#custom-rules):

  ```yaml
  - ruleType: range
    columns: [discount_pct]
    minValue: 0.0
    maxValue: 100.0
    prunePartition: true
  ```
- **`accepted_values`** : Validates that every non-null value in each listed
  column belongs to `allowedValues` (a non-empty list of strings, integers, or
  finite floats). YAML booleans (`true` and `false`) are rejected; quote string
  flags such as `"X"` or `"Y"`:

  ```yaml
  - ruleType: accepted_values
    columns: [overall_processing_status, delivery_status]
    allowedValues: ["A", "B", "C", ""]
  ```

### Validate referential integrity (`foreign_key`)

`foreign_key` validates single-column or composite referential integrity against
`parentTable` using a positional `LEFT JOIN`:

- **`parentTable` coordinates** :
  - `<table_name>`: Resolved automatically across upstream module `sources` declared in `manifest.yaml` (or the current module's target dataset for intra-module joins).
  - `<bindingKey>.<table_name>`: Targets a specific `dependencyBindings` key when a module consumes multiple upstream foundations or products.
  - `<dataset>.<table_name>` or `<project>.<dataset>.<table_name>`: Explicit BigQuery Dataform target coordinates.
- **Column mapping and `NULL` semantics** : `parentColumns` is optional when parent and child share identical column names. Following SQL `MATCH SIMPLE` semantics, orphan checks evaluate only rows where every column in `columns` is `IS NOT NULL`.

The following example validates composite foreign keys against the SAP
foundation `kna1` table in `table_settings.yaml`:

```yaml
- ruleType: foreign_key
  columns: [client_mandt, sold_to_party_kunnr]
  parentTable: kna1
  parentColumns: [mandt, kunnr]
  prunePartition: true
  lookbackDays: 7
```

### Reconcile metrics across layers (`cross_layer_parity`)

`cross_layer_parity` reconciles aggregated numeric measures and row counts
between a child table (`${self()}`) and an upstream `parentTable` across shared
business keys, executing **a single aggregation scan per table** regardless of
how many metrics you compare:

- **Matching key data types** : Group keys are canonicalized with `FORMAT('%T', STRUCT(...))` for null-safe `FULL OUTER JOIN` matching. Ensure that key columns have matching BigQuery data types on both sides (for example, `STRING` `'000010'` doesn't match `INT64` `10`). For key type casts, use a [custom SQL template](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt#custom-rules).
- **Non-blocking full reconciliation** : `cross_layer_parity` evaluates full aligned key sets across both tables (`blocking: true` and `prunePartition: true` are rejected during schema validation).

The following table describes the options for `cross_layer_parity`:

| Option | Required | Default | Description |
| `columns` | Yes | None | Child grouping key columns (`>= 1`). |
| `parentTable` | Yes | None | Upstream reference table (`table`, `bindingKey.table`, `dataset.table`, or `project.dataset.table`). |
| `parentColumns` | No | `columns` | Parent grouping key columns matched positionally to `columns`. |
| `metrics` | Yes | None | Non-empty list of metric comparison definitions with unique `name` or `column` labels. |
| `tolerance` | No | `0` | Allowed absolute numeric delta (`>= 0`). A metric fails only when `ABS(actual - expected) > tolerance` (for example, `0.01` for floating-point rounding). |
| `compareRowCounts` | No | `true` | Emits a `row_count_mismatch` defect when child and parent aggregate different row counts for an existing key group. Set to `false` when rolling up line items to headers. |
| `parentFilter` | No | None | Map of `parent_column: [allowed_values]` compiled into `AND`-joined `IN (...)` predicates on `parentTable` (for example, restricting `vbak` to `vbtyp: ["C"]`). |
| `childFilter` | No | None | Map of `child_column: [allowed_values]` compiled into `AND`-joined `IN (...)` predicates on `${self()}`. |
|---|---|---|---|

The following table describes each entry under `metrics`:

| Field | Required | Default | Description |
| `column` | Yes | None | Numeric measure column on the child table (`${self()}`). |
| `parentColumn` | Yes | None | Corresponding numeric measure column on `parentTable`. |
| `name` | No | `column` | Label emitted in the output `metric` column when a defect occurs. Must be unique across `metrics` on the rule. |
| `conversion` | No | `"none"` | `"none"` or `"sap_currency_decimal_shift"` (applies SAP `tcurx` decimal scaling for currencies such as `JPY` or `KRW`). |
| `parentCurrencyColumn` | Conditional | None | Currency key column on `parentTable` (such as `waerk` or `waers`). Preferred when `conversion: sap_currency_decimal_shift`: shifts the raw SAP value using `tcurx`, catching child models that selected the wrong currency field. |
| `currencyColumn` | Conditional | None | Currency key column on `${self()}`. Use instead of `parentCurrencyColumn` when the raw SAP parent table lacks a row-level currency column (such as `ekpo`, whose currency comes from header `ekko`), reverse-shifting the product value for comparison. |
|---|---|---|---|

> [!NOTE]
> **Note:** Setting `conversion: sap_currency_decimal_shift` requires specifying either `parentCurrencyColumn` or `currencyColumn` (never neither or both). In addition, `tcurx` must be enabled in the bound upstream SAP foundation and an SAP module must be enabled so `currency.js` is staged in `includes/`. Cortex Framework automatically retains `tcurx` during foundation pruning and exposes it to the product module without requiring a manual entry in the product's `manifest.yaml`.

When discrepancies exist, the compiled assertion view returns one row per
offending `(row_key, metric)` pair with columns `row_key` (`STRING`), `metric`
(`STRING`, the metric name), `expected_value` (`NUMERIC`, parent sum),
`actual_value` (`NUMERIC`, child sum), `parent_row_count` (`INT64`),
`child_row_count` (`INT64`), and `defect` (`'missing_in_child'`,
`'missing_in_parent'`, `'row_count_mismatch'`, or `'value_mismatch'`).

The following example reconciles `sales_document_items` with `vbap` in
`table_settings.yaml`:

```yaml
s4:
  sales_document_items:
    assertions:
      enabled: true
      standardRules:
        - ruleType: cross_layer_parity
          name: parity_with_vbap
          columns: [client_mandt, document_number_vbeln, item_number_posnr]
          parentTable: vbap
          parentColumns: [mandt, vbeln, posnr]
          tolerance: 0.01
          metrics:
            - name: net_value
              column: net_value_of_the_sales_document_item_in_document_currency_netwr
              parentColumn: netwr
              conversion: sap_currency_decimal_shift
              parentCurrencyColumn: waerk
            - name: order_quantity
              column: cumulative_order_quantity_kwmeng
              parentColumn: kwmeng
```

## Author custom SQL rules and templates

For domain invariants that go beyond standard rules---such as date-order checks
(`delivery_date < order_date`), header-to-item cross-joins, fiscal period
continuity, or reference domain checks---define entries under
`assertions.customRules`. Each custom rule requires a unique `name` and either
an inline `sqlExpression` or an external `templateFile` (mutually exclusive).

### Inline SQL (`sqlExpression`)

Define a self-contained assertion query inline using `sqlExpression` in
`table_settings.yaml`:

```yaml
assertions:
  customRules:
    - name: delivery_after_order_date
      blocking: false
      severity: P1
      tags: [fulfillment_sla]
      sqlExpression: |
        SELECT mandt, vbeln, audat, vdatu
        FROM ${self()}
        WHERE vdatu IS NOT NULL
          AND audat IS NOT NULL
          AND vdatu < audat
```

### Reusable SQL templates (`templateFile` and `params`)

Author parameterized SQL template files once and instantiate them across
multiple tables:

```sql
-- assertions/valid_country_code.sql
SELECT DISTINCT
  child.`${country_column}` AS orphan_country_code
FROM ${self()} AS child
LEFT JOIN ${ref("t005")} AS countries
  ON child.`${client_column}` = countries.mandt
  AND child.`${country_column}` = countries.land1
WHERE child.`${country_column}` IS NOT NULL
  AND child.`${country_column}` NOT IN (${exempt_codes})
  AND countries.land1 IS NULL
```

Reference the template from `table_settings.yaml`:

```yaml
assertions:
  customRules:
    - name: valid_country_key
      templateFile: valid_country_code.sql
      params:
        client_column: mandt
        country_column: land1
        exempt_codes: [""]
```

### Reference placeholders and parameter resolution

Custom assertion SQL compiles through Dataform JavaScript includes,
resolving placeholders and registering referenced tables in the
Dataform DAG as described in the following table:

| Placeholder | Resolution behavior |
| `${self()}` | Resolves to the dataset-qualified target table (`ctx.ref(targetDatasetId, tableName)`, or the transactional target table inside `sap_cdc.js`), avoiding `Ambiguous Action name` collisions when multiple modules publish identically named tables. |
| `${ref("table_name")}` | Searches upstream `sources` table lists declared by the module's dependencies first, falling back to single-source dataset resolution or `targetDatasetId`. |
| `${ref("bindingKey", "table_name")}` | Resolves `table_name` inside the dataset bound to `bindingKey` in `dependencyBindings` (recommended when a product binds multiple upstream modules). |
| `${ref("dataset", "table_name")}` or `${ref("project", "dataset", "table_name")}` | Resolves explicit two-part or three-part Dataform target coordinates using quoted string literals. |
|---|---|

Parameter substitution and template discovery follow these rules:

- **Placeholder syntax** : Both `${param_name}` and `{{ param_name }}` are substituted at build time before `${self()}` and `${ref(...)}` references resolve. Any missing parameter key raises a `CortexConfigError`.
- **Automatic value formatting and escaping** :
  - Booleans (`true` and `false`) render as SQL `TRUE` and `FALSE`.
  - Lists (`["A", "B"]` or `[10, 20]`) render as comma-separated SQL literals with backslash, single-quote, newline (`\n`), and carriage-return (`\r`) escaping on string elements (`'A', 'B'` or `10, 20`), ready for `IN (${param})` clauses.
  - Single-quoted string parameters (`'${param}'`) automatically escape backslashes, single quotes, `\n`, and `\r`.
  - Backticked (`` `${country_column}` ``) or double-quoted (`"${param}"`) string parameters are validated against `^[a-zA-Z0-9_]+$` at build time to prevent invalid identifiers.
  - Unquoted integers, floats, and strings substitute directly so templates can inject numeric thresholds or SQL fragments.
- **Template search order** (first existing file wins for relative
  `templateFile` paths):

  1. `<module_dir>/<templateFile>` and `<module_dir>/assertions/<templateFile>`
  2. `<custom_table_settings_dir>/<templateFile>` and `<custom_table_settings_dir>/assertions/<templateFile>` (when `tableSettings` points to an external file)
  3. Legacy non-empty intermediate `<namespace>/<segment>/assertions/<templateFile>` directories (deprecated and emits a `DeprecationWarning`; planned for removal in v8.0)
  4. Active module's PEP-420 namespace root tiers (`<namespace_root>/assertions/<templateFile>`)
  5. Builder-declared shared assertion directories (`get_shared_assertion_dirs()`, such as `src/data_modules/cortex/assertions/`)
  6. The directory containing `config.yaml`, then the workspace root directory

### Standalone `assertions.sqlx` files (`--assertions`)

In addition to declarative `table_settings.yaml` rules, you can bundle a single
standalone Dataform `.sqlx` assertions file into the build output
by passing `--assertions` to `uv run cortex-build` or
`uv run cortex-build-and-deploy`:

```bash
uv run cortex-build \
    --config config/config.yaml \
    --assertions PATH_TO_ASSERTIONS_SQLX
```

Replace the following:

- `PATH_TO_ASSERTIONS_SQLX`: path to an existing standalone `.sqlx` file, for example: `config/custom_assertions.sqlx`.

The build copies the specified file to `dist/definitions/assertions/assertions.sqlx`.
Standalone `.sqlx` files aren't controlled by `data.assertionsEnabled` and don't
participate in `publisher.js` blocking gates.

### Built-in SAP and SAP BDC functional validation blueprints

Cortex Framework includes parameterized SAP and SAP Business Data
Cloud (BDC) validation blueprints and preconfigured `table_settings.default.yaml`
examples that you can enable or customize:

| Validation blueprint | Template or rule | Target models | What it validates |
| Zero-balance double-entry ledger parity | `zero_balance_ledger_parity.sql` (`products/universal_journal/assertions/`) | `universal_journal_entry_line_items` (S/4HANA) | Verifies that posted accounting documents balance to zero within `tolerance` across company code (`HSL`), global (`KSL`), and single-currency transaction (`WSL`) amounts, excluding carry-forward period `000` and configured statistical or parked statuses (`BSTAT`, `BLART`). |
| Financial Statement Version (FSV) account assignment | `fsv_account_assignment_check.sql` (`products/universal_journal/assertions/`) | `universal_journal_entry_line_items` (S/4HANA) | Checks that active G/L accounts in a chart of accounts (`T001.KTOPL`) resolve to one FSV node in `FAGL_011ZC` and `FAGL_011PC` for their debit or credit balance side, flagging unassigned or double-counted accounts. |
| Financial statement cumulative sign and period roll-forward | `cumulative_sign_reconciliation.sql` (`products/financial_statements/assertions/`) | `balance_sheet`, `profit_and_loss` (ECC and S/4HANA) | Verifies that `cumulative_sign_multiplier` is `1` or `-1`, confirms display cumulative amounts match signed local and target cumulative amounts within `0.0001`, flags accounts active on both debit (`S`) and credit (`H`) contra sides in the same period, and checks consecutive period cumulative roll-forward against `period_net_amount_in_local_currency`. |
| Order-to-Cash and Procure-to-Pay metric parity | Built-in `cross_layer_parity` rule with `sap_currency_decimal_shift` | `sales_document_items`, `purchasing_document_items` | Reconciles line-item net values (`NETWR` with `TCURX` scaling) and quantities (`KWMENG`, `MENGE`) between foundation tables (`vbap`, `ekpo`) and data product tables. |
| Sales document flow split cardinality | `document_flow_split_validation.sql` (`products/sales_documents/assertions/`) | `sales_document_flow` (ECC and S/4HANA) | Converts ordered quantities to base units (`UMVKZ` and `UMVKN`) and flags items where delivered quantities exceed overdelivery tolerance (`UEBTO`) or billed quantities exceed delivered quantities across delivery splits. |
| Master data ISO compliance and text coverage | `iso_domain_compliance.sql` and `master_text_coverage.sql` (`cortex/assertions/`) | `materials`, `customers`, `vendors` | Verifies that currencies (`TCURC`), countries (`T005`), and units of measure (`T006`) map to populated ISO codes, and checks that active master records meet a minimum description coverage ratio (such as `0.99` in `MAKT` for language `E`). |
| Fiscal period and special-period continuity | `fiscal_period_boundary_continuity.sql` (`cortex/assertions/`) | `universal_journal_entry_line_items`, `accounts_receivable`, `accounts_payable` | Confirms that every financial posting maps to a valid fiscal year variant (`T001.PERIV` to `T009`), preserves special closing periods (`013`--`016`) within `ANZBP + ANZSP`, and keeps posting dates (`BUDAT`) within valid date bounds. |
| Accounts payable aging and cash discount bounds | `aging_buckets_reconciliation.sql` and `discount_utilization_bounds.sql` (`products/accounts_payable_insights/assertions/`) | `accounts_payable_aging_by_vendor`, `cash_discount_utilization_by_fiscal_period` (ECC and S/4HANA) | Verifies that vendor overdue aging buckets reconcile to total overdue and open payables within `0.01`, and keeps cash discount utilization within `[0, 100]` with non-negative forfeited discounts. |
| Accounts receivable aging and DSO closing reconciliation | `aging_buckets_reconciliation.sql` and `aging_dso_closing_reconciliation.sql` (`products/accounts_receivable_insights/assertions/`) | `accounts_receivable_aging_by_customer` (ECC and S/4HANA) | Verifies that the four overdue aging buckets sum to `overdue_receivables_amount` and `open_not_yet_due_amount + overdue_receivables_amount` reconciles to `total_receivables_amount` within `0.01`, and checks that each customer's total receivables match the closing balance of their most recent DSO period in `days_sales_outstanding_by_fiscal_period` within `0.01` (enforcing `NULL` parity for open items without an exchange rate, and requiring `0` total receivables for customers without a DSO row). |
| Accounts receivable DSO balance roll-forward | `dso_balance_roll_forward.sql` (`products/accounts_receivable_insights/assertions/`) | `days_sales_outstanding_by_fiscal_period` (ECC and S/4HANA) | Verifies that each fiscal period's opening receivables equal the preceding period's closing receivables (`0` for the first period), checks that average receivables equal the mean of opening and closing balances, and reconciles `balance_to_sales_dso_days` within `0.01`. |
| Sales performance overdue delivery and signed net value invariants | **SAP ERP** : `overdue_delivery_invariants.sql` and `signed_net_value_bounds.sql` (`cortex_samples/sap/products/sales_performance/assertions/`) **SAP BDC** : `overdue_delivery_invariants.sql` (`cortex_samples/sap_bdc/products/sales_performance/assertions/`) | `sales_performance` (ECC, S/4HANA, and SAP BDC) | **SAP ERP** : Verifies that overdue items (`is_delivery_overdue = TRUE`) aren't rejected or return items, have a past `requested_delivery_date_vdatu`, have remaining undelivered quantity (`delivered_quantity_lfimg < cumulative_order_quantity_kwmeng`), and carry a non-blank `overall_item_delivery_status_lfgsa`. Also verifies that `signed_net_value_in_document_currency` is populated whenever `net_value_in_document_currency_netwr` is non-null, stays within `ABS(net_value_in_document_currency_netwr)`, and equals `0` for statistical items (`statistical_values_kowrr`). **SAP BDC** : Verifies that `is_delivery_overdue` isn't `NULL`, and that overdue items (`is_delivery_overdue = TRUE`) aren't rejected (`is_rejected`, `sales_document_rjcn_reason`) or return items (`is_returns_item`), have a past `requested_delivery_date`, have a positive `order_quantity`, and carry an open `total_delivery_status` (`A` or `B`). SAP BDC doesn't include `signed_net_value_bounds.sql`. |
| SAP BDC split-delivery net amount reconciliation | `split_delivery_net_amount_reconciliation.sql` (`cortex_samples/sap_bdc/products/supplier_plant_weather_risk_insights/assertions/`) | `inbound_delivery_insights` | Verifies that summed `delivery_proportional_net_amount` across split deliveries per purchase order item is non-negative and doesn't exceed `total_po_item_net_amount` scaled by the bounded delivery ratio (up to a 2x over-delivery ceiling) plus per-line rounding tolerance. |
| SAP BDC weather and D\&B ETA spend-at-risk consistency | `eta_and_spend_at_risk_consistency.sql` (`supplier_plant_weather_risk_insights/assertions/`) and `dnb_eta_and_spend_at_risk_consistency.sql` (`supplier_inbound_delivery_weather_risk_insights/assertions/`) | `supplier_plant_weather_risk_insights`, `supplier_inbound_delivery_weather_risk_insights` | Verifies that conservative P90 transit duration and arrival date aren't earlier than median P50 projections, and that `open_delivery_spend_past_scheduled_date` is non-negative and strictly `0` when delivered or when `route_delay_variance_days_p90 <= 0`. |
|---|---|---|---|

### Built-in Salesforce validation blueprints

Cortex Framework includes shared, parameterized Salesforce
(`sfdc`) SQL templates in `src/data_modules/cortex/assertions/` and
consumption product `assertions/` directories that you can reference by filename
in `table_settings.yaml` alongside built-in standard rules:

| Validation blueprint | Template or rule | Target models | What it validates |
| Cross-layer metric and soft-delete parity | Built-in `cross_layer_parity` rule | Source-aligned Salesforce tables (such as `opportunities`) and base consumption detail tables (`opportunity_pipeline`, `leads_capture_conversions`, `case_management`) | Reconciles row counts, primary key coverage, and numeric sums (such as `amount` against `Amount`) across layers. Because foundation and source-aligned CDC tables retain soft-deleted records (`IsDeleted` / `is_deleted`) in 1:1 parity, no soft-delete filter is required between those layers. |
| Advanced Currency Management (ACM) conversion accuracy | `acm_currency_conversion_check.sql` (`cortex/assertions/`) | `opportunities`, `opportunities_history` | Verifies that corporate-currency converted amounts match `ROUND(SAFE_DIVIDE(amount, COALESCE(dated_rate, static_rate)), DecimalPlaces)` within `tolerance` using `dated_conversion_rate` (`[StartDate, NextStartDate)`) and `currency_type`. Requires multi-currency tables deployed in `foundations/sfdc`; pass `effective_date_col: close_date` when validating `prev_amount_corporate_currency` on `opportunities_history`. |
| Polymorphic owner integrity (User compared with Queue) | `polymorphic_owner_integrity.sql` (`cortex/assertions/`) | `cases`, `leads`, `tasks` | Checks that non-null `owner_id` values start with `005` (`User`) or `00G` (`Group` / Queue), confirms that `005%` records resolve to `user` with matching `owner_name` and `owner_username`, and verifies that `00G%` queue-owned records leave user-only fields `NULL`. Use standard `foreign_key` rules against `user` for user-only SObjects (such as `accounts`, `contacts`, and `opportunities`). Don't apply this template to `events`, because `Event.OwnerId` allows shared or resource calendars (`023%`) rather than queues (`00G%`). |
| Lead conversion lifecycle completeness | `lead_conversion_completeness.sql` (`cortex/assertions/`) | `lead` (foundation), `leads` (source-aligned), `leads_capture_conversions` (consumption) | Verifies that converted leads (`is_converted = TRUE`) populate `converted_date`, `converted_account_id`, and `converted_contact_id`, and that unconverted leads keep all three columns `NULL`. Map parameter names to the target layer schema (pass `converted_date_col: lead_converted_date` on `leads_capture_conversions`, or `PascalCase` column names such as `ConvertedDate` on foundation `lead`). Keep `blocking: false` in Salesforce organizations that hard-delete Accounts or Contacts after conversion (such as for privacy erasure), which clears converted lookup IDs to `NULL`. |
| Opportunity pipeline consumption integrity | `opportunity_pipeline_integrity.sql` (`products/opportunity_pipeline/assertions/`) | `opportunity_pipeline` | Verifies that closed opportunities (`is_opportunity_closed = TRUE`) keep open-only velocity and hygiene flags `NULL` or `FALSE`, nested `stage_history`, `line_items`, and `contact_roles` arrays exclude soft-deleted rows and match count columns (including `has_decision_maker_contact` alignment with `decision_maker_contact_id`), corporate-currency net amount change reconciles within `tolerance`, discounts are non-negative with percentages from `0` to `100` (or `NULL` when the list price is zero or negative), and unpriced opportunities (`total_sale_amount IS NULL`) preserve `NULL` expected value columns. Pass `params` for `entity_key_col` (for example, `opportunity_id`) and `tolerance` (for example, `0.01`). |
| Sales activities consumption integrity | `sales_activities_integrity.sql` (`products/sales_activities/assertions/`) | `sales_activities` | Validates `Task` compared with `Event` activity types and `is_meeting_activity` alignment, polymorphic `owner_id` rules (`005%` User, `00G%` Queue on `Task`, and `023%` Calendar on `Event`), closed or soft-deleted compared with open overdue and completion velocity bounds, buying-committee engagement and open-only opportunity hygiene flags, nested `opportunity_contact_roles` array cardinality with soft-delete exclusion, and `NULL` expected values on unpriced opportunities (`total_sale_amount IS NULL`). |
| Case management consumption integrity | `case_management_integrity.sql` (`products/case_management/assertions/`) | `case_management` | Verifies polymorphic User (`005%`) compared with Queue (`00G%`) case ownership and `is_agent_assigned` alignment, omnichannel touchpoint arithmetic and nested array cardinality (`case_comments`, non-draft `email_messages`, `case_history`) with soft-delete exclusion, non-negative first-response and resolution SLA bounds, and First Contact Resolution (`is_first_contact_resolved`) criteria. |
| Leads capture and conversions consumption integrity | `leads_conversion_integrity.sql` (`products/leads_capture_conversions/assertions/`) | `leads_capture_conversions` | Checks polymorphic User (`005%`) compared with Queue (`00G%`) lead ownership and owner-performed activity guards, outreach activity count arithmetic and nested `lead_activities` and `opportunity_contact_roles` array cardinality with soft-delete exclusion, speed-to-lead SLA response bounds, and converted compared with unconverted lifecycle and opportunity handoff invariants, and verifies that unpriced opportunities (`total_sale_amount IS NULL`) preserve `NULL` expected value columns. |
|---|---|---|---|

> [!NOTE]
> **Note:** Any upstream foundation table referenced by an enabled rule---such as `currency_type` and `dated_conversion_rate` for `acm_currency_conversion_check.sql`, or `user` for `polymorphic_owner_integrity.sql` --- must be deployed in `foundations/sfdc`; otherwise, Dataform compilation fails with an unresolved reference (for example, during [`uv run cortex-compile`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-compile.md.txt) or deployment).

## Action and defect view naming conventions

Because all assertion views across a deployment materialize into
`data.defaultAssertionDataset`, Cortex Framework prefixes every
assertion action name with the owning `moduleId` to prevent cross-module
collisions (such as between SAP ECC and S/4HANA modules or between foundation
and product tables sharing a name):

    <moduleId>_<tableName>_assert_<resolvedRuleName>

Non-alphanumeric characters are normalized to `_`, and total identifier length
is validated at build time against BigQuery's **1,024-character
limit**.

Rule names never depend on list index order in `table_settings.yaml`, so adding
or reordering rules doesn't orphan existing BigQuery views. The
following table shows how `<resolvedRuleName>` is derived when `name` is
omitted:

| Rule configuration | Derived `<resolvedRuleName>` | Example view in `dataform_assertions` (`moduleId: sap_sales_documents`) |
| Any rule with explicit `name: my_check` | `my_check` | `sap_sales_documents_sales_document_headers_assert_my_check` |
| `unique_key` (inheriting model keys) | `unique_key` | `sap_sales_documents_sales_document_headers_assert_unique_key` |
| `unique_key` with `columns: [client_mandt, document_number_vbeln]` | `unique_key_client_mandt_document_number_vbeln` | `sap_sales_documents_sales_document_headers_assert_unique_key_client_mandt_document_number_vbeln` |
| `non_null`, `range`, or `accepted_values` with `columns` | `<ruleType>_<col1>_<col2>...` | `sap_sales_documents_sales_document_headers_assert_non_null_client_mandt_document_number_vbeln` |
| `foreign_key` (`columns: [client_mandt, sold_to_party_kunnr]`, `parentTable: sap.kna1`) | `foreign_key_<cols>_to_<leafParentTable>` | `sap_sales_documents_sales_document_headers_assert_foreign_key_client_mandt_sold_to_party_kunnr_to_kna1` |
| `cross_layer_parity` (`parentTable: vbak`) | `cross_layer_parity_to_<leafParentTable>` | `sap_sales_documents_sales_document_headers_assert_cross_layer_parity_to_vbak` |
|---|---|---|

> [!TIP]
> **Tip:** If two rules on the same table derive the same suffix (such as two `range` checks on one column or two `cross_layer_parity` checks against the same `parentTable`), set an explicit `name` on at least one rule.

## Optimize scan costs with partition pruning

To avoid full-table scans on multi-terabyte partitioned tables during
incremental runs, enable rolling partition pruning on standard rules (for
example, on `universal_journal_entry_line_items` in the `universal_journal`
S/4HANA data product):

```yaml
s4:
  universal_journal_entry_line_items:
    partitionDetails:
      column: posting_date_in_the_document_budat
      partitionType: time
      dataType: DATE
      timeGrain: MONTH
    assertions:
      enabled: true
      lookbackDays: 7          # Table-level default window (days >= 1)
      standardRules:
        - ruleType: non_null
          columns:
            - client_rclnt
            - company_code_rbukrs
            - accounting_document_number_belnr
            - year_of_posting_date_budat
          prunePartition: true # Uses table-level lookbackDays (7 days)
        - ruleType: range
          columns: [year_of_posting_date_budat]
          minValue: 1900
          maxValue: 2100
          prunePartition: true
          lookbackDays: 1      # Rule-level override (1 day)
```

Partition pruning follows these rules:

- **Opt-in activation** : `prunePartition` defaults to `false`. When `false` or when the table has no partition column, assertions scan the full table.
- **Lookback precedence** : Evaluates rule-level `lookbackDays` (`>= 1`) first, then table-level `assertions.lookbackDays` (`>= 1`), and finally the framework default of `3` days.
- **Automatic BigQuery type alignment** : `assertion_helper.js` uses `partitionDetails.dataType` (resolved from the source schema on foundations, or explicitly declared with `partitionType: time` and `dataType: DATE | DATETIME | TIMESTAMP` on data products) to emit a typed predicate without type-coercion errors. On data products, omitting `dataType` with `partitionType: time` is deprecated (planned for removal in v8.0): the builder omits `partitionDetails`, leaves the table unpartitioned, and disables partition pruning. On foundation tables, when source schema inspection doesn't expose the partition column and only `partitionType: time` is present without `dataType`, `assertion_helper.js` infers `TIMESTAMP` for known timestamp column names (`recordstamp`, `systemmodstamp`, `lastmodifieddate`, `createddate`, `source_last_updated_at`) and defaults to `DATE` otherwise. Where `LOOKBACK_DAYS` is your partition lookback window in days, for example `7`:
  - `DATE`: ``AND `col` >= DATE_SUB(CURRENT_DATE(), INTERVAL
    LOOKBACK_DAYS DAY)``
  - `TIMESTAMP`: ``AND `col` >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL
    LOOKBACK_DAYS DAY)``
  - `DATETIME`: ``AND `col` >= DATETIME_SUB(CURRENT_DATETIME(), INTERVAL
    LOOKBACK_DAYS DAY)``
  - Integer range partitions (`partitionType: integer`): emits no temporal `WHERE` filter.
- **Custom SQL pruning** : `prunePartition` applies to `standardRules` only. In `customRules`, write `WHERE` partition filters directly in your SQL or parameterize the window through `params`.

## Validate assertions locally and deploy

Schema validation, severity vocabulary checks, and custom SQL template
parameter validation run automatically during every `uv run cortex-build`. To
also compile and verify the full Dataform assertion graph before
deploying, run [`uv run cortex-compile`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-compile.md.txt)
prior to
[`uv run cortex-build-and-deploy`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-build-and-deploy.md.txt):

```bash
export CORTEX_CONFIG_FILE=config/config.yaml

# Option 1: Build into an ephemeral workspace and compile the Dataform graph
uv run cortex-compile --config $CORTEX_CONFIG_FILE

# Option 2: Compile a previously built dist/ directory strictly offline
uv run cortex-build --config $CORTEX_CONFIG_FILE
uv run cortex-compile --dist-dir dist

# Deploy compiled modules and assertions to enabled targets
uv run cortex-build-and-deploy --config $CORTEX_CONFIG_FILE
```

Running `uv run cortex-build` and `uv run cortex-compile` performs the
following verification checks:

- **Automatic build-time schema and template validation** : During `uv run cortex-build` (and ephemeral `uv run cortex-compile --config`), Cortex Framework enforces strict schema rules, template existence and parameter completeness, SQL identifier and dot-separated column path validation, and severity vocabulary membership---even when `data.assertionsEnabled: false`.
- **Full Dataform graph compilation (`dataform compile --json`)** : Runs the local Dataform compiler (`dataform` or `npx @dataform/cli`) across all generated JavaScript definitions and assertion actions to catch compilation errors and unresolved `ref()` dependencies before deployment. Use `--dist-dir` for strictly offline compilation without Google Cloud credentials (`--config` runs an ephemeral build that inspects source schemas when non-external foundations or catalogs are enabled).

## Monitor, run selectively, and upgrade assertions

After deploying assertions, you can inspect failing records in
BigQuery, execute targeted assertion subsets with
Dataform tags, configure alerts, and clean up legacy views.

### Inspect defect rows in BigQuery

When an assertion fails during a Dataform workflow invocation, query
the offending rows directly under `data.defaultAssertionDataset` (in the target
project hosting the asserted dataset):

```sql
SELECT *
FROM `PROJECT_ID.ASSERTION_DATASET.ASSERTION_VIEW_NAME`
LIMIT 100;
```

Replace the following:

- `PROJECT_ID`: your target Google Cloud project ID, for example: `my-target-project`.
- `ASSERTION_DATASET`: the dataset configured in `data.defaultAssertionDataset`, for example: `dataform_assertions`.
- `ASSERTION_VIEW_NAME`: the compiled `<moduleId>_<tableName>_assert_<ruleName>` view name, for example: `sap_sales_documents_sales_document_headers_assert_unique_key`.

### Run assertions selectively using Dataform tags

Scheduled workflows and CI/CD pipelines can execute targeted assertion subsets
in Dataform by filtering on [assertion tags](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt#assertion-tags):

- **All data quality assertions across modules** : `--tags assertion` (or `--tags data_quality`)
- **Critical severity tier only** : `--tags severity_P0`
- **Non-blocking audit sweep off the critical CDC path** : `--tags non_blocking_audit`

### Configure Logging and Cloud Monitoring alerts

Dataform workflow assertion failures write structured entries to
Logging under resource type `dataform.googleapis.com/Repository`.
Configure log-based alerts in Monitoring filtering for failed assertion
actions in your repository to route notifications without custom log exporters.
For details, see [Observability](https://docs.cloud.google.com/cortex/docs/observability.md.txt).

### Clean up legacy v7 assertion views after upgrading

Earlier Cortex Framework v7 builds created implicit
`<tableName>_assertions_uniqueKey` and `<tableName>_assertions_nonNull` views
directly inside each module's target BigQuery dataset when
`uniqueKeys` were present. Those implicit views are replaced by declarative
`table_settings.yaml` assertions centralized in `data.defaultAssertionDataset`.
After upgrading an existing environment, drop any orphaned
`*_assertions_uniqueKey` and `*_assertions_nonNull` views from your foundation
or product target datasets.

## Limitations

Declarative data quality assertions have the following limitations:

- **Live SQL and column existence checks** : `uv run cortex-compile` validates Dataform JavaScript compilation and table-level DAG dependencies without executing SQL against BigQuery. BigQuery SQL syntax errors and column-name typos on physical tables appear when Dataform executes against BigQuery.
- **`cross_layer_parity` constraints** : `cross_layer_parity` rules scan full aggregated key sets across both tables and reject `blocking: true` and `prunePartition: true`. The `sap_currency_decimal_shift` conversion applies only to SAP tables and requires foundation table `tcurx`.
- **`publisher.publish()` and `publisher.operate()` requirement for blocking
  gates** : Downstream models must use `publisher.publish()` or `publisher.operate()` (`includes/publisher.js`) to inherit upstream `blocking: true` assertion dependencies automatically. Custom models written as raw SQLX files or calling bare `publish()` or `operate()` bypass compile-time ref hooks unless you declare explicit dependencies.

## What's next

- [Deployment configuration](https://docs.cloud.google.com/cortex/docs/deployment-configuration.md.txt)
- [Data product module creation](https://docs.cloud.google.com/cortex/docs/extensibility-guide-data-product.md.txt)
- [Observability](https://docs.cloud.google.com/cortex/docs/observability.md.txt)
- [Version 6 compatibility](https://docs.cloud.google.com/cortex/docs/v6-compatibility.md.txt)