One contract file, published once and enforced at three key points across the medallion architecture using dbt and Unity Catalog.
If you've worked in data engineering long enough, you've likely lived through this scenario: an operational team tweaks a schema or refactors an upstream service, and suddenly downstream reports, ML models, and executive dashboards break without warning. At its core, this stems from tight, unmanaged coupling between operational systems ("data on the inside") and analytical consumers ("data on the outside"), to borrow Pat Helland's terms.
Data contracts offer a clear way forward, and the Open Data Contract Standard (ODCS) has emerged as their shared language. However, many contract initiatives fall short at execution: contracts sit quietly in Git, tables live in Unity Catalog, and the dbt transformation logic building your silver and gold tables reads neither.
This is the situation in our own Databricks projects. We consume data from upstream teams, and the flexibility the platform allows means contract enforcement is up to each project to design. As a result, data issues are often not caught within our pipeline but by the oversight bodies themselves, who are the external consumers of our reports. We'd like to detect these issues proactively, before submissions reach the authorities, by enforcing data contracts at both ends of the product: on the data we consume and on the outputs we publish. We want to do this in a clean and maintainable way, so we can keep that flexibility without compromising reliability.
This post shows how to close that gap with tools most Databricks teams already run. Think of ODCS as the specification, dbt as your compiler, and Unity Catalog as the runtime environment. By publishing a contract once to a Unity Catalog volume, we enforce it at three points: during dbt compilation, when Delta writes rows, and before downstream consumers read the data.
Contracts belong on the ports
In Data Mesh architecture, we treat a data product as an architectural quantum (Zhamak Dehghani's term), the smallest unit that can safely deploy and evolve independently. To keep things clean and modular, we interact with it through three defined ports:
- Input ports bring data into the product.
- Output ports serve refined data to consumers.
- Control ports expose operational metadata and health metrics.
This separation gives your team the freedom to refactor internal logic without breaking external commitments. The medallion architecture provides physical homes for these concepts, while dbt interacts across each layer:
| Layer | Role in the data product | Who makes the promise | What checks it |
|---|---|---|---|
| Bronze | Input port | The upstream producer | The producer's contract, as dbt source tests or pipeline expectations |
| Silver | Private core | No one outside the team | dbt tests, changed freely |
| Gold | Output port | The data product team | The product's contract, at all three gates |
| Shares and exports | Output port outside the workspace | The data product team | The same contract, tested on what the consumer receives |
A common pitfall to avoid here is slapping a formal contract on every single internal table. Doing so on a silver table turns internal implementation details into strict promises, forcing unnecessary coordination for routine refactoring.
As a rule of thumb: place contracts specifically at boundary points where external teams consume your data.
ODCS v3: one file for meaning and storage
ODCS is an open YAML standard maintained by Bitol, a Linux Foundation project, and is at v3.2.0 at the time of writing. A contract records the dataset's owner, schema, quality rules, service levels, classifications, and servers.
Version 3 separates the semantic model from the syntax model.
Think of the logicalType as the platform-agnostic type of a field, such as string, number, date, or timestamp. It gives producers and consumers a shared understanding of what kind of value the field holds, regardless of how it is stored. The physicalType, in contrast, is the exact type on a given target, which tells the engine how to store and query the data. Business meaning lives in fields such as description, businessName, and authoritativeDefinitions. Keeping the two layers apart lets you share one logical model across targets and publish a physical variant for each, for example one for a Kafka topic and one for a Snowflake table.
Here is an ODCS v3.2.0 contract for version 2 of a gold orders table. It passes datacontract lint:
apiVersion: v3.2.0
kind: DataContract
id: checkout.customer_orders
version: 2.1.0
status: active
domain: checkout
dataProduct: customer_orders
team:
name: checkout-data
members:
- username: checkout-data@example.com
role: owner
servers:
- server: prod
type: databricks
catalog: checkout
schema: gold
- server: audit
type: databricks
catalog: checkout
schema: audit
schema:
- name: customer_orders
physicalName: customer_orders_v2
physicalType: table
properties:
- name: order_id
logicalType: string
physicalType: string
primaryKey: true
required: true
- name: customer_email
logicalType: string
physicalType: string
required: true
classification: restricted
tags: [pii]
- name: total_amount
logicalType: number
physicalType: decimal(10,2)
required: true
logicalTypeOptions:
exclusiveMinimum: 0
- name: actual_timestamp
logicalType: timestamp
physicalType: timestamp_ntz
required: true
- name: processing_timestamp
logicalType: timestamp
physicalType: timestamp_ntz
required: true
quality:
- type: library
metric: duplicateValues
arguments:
properties: [order_id]
mustBe: 0
- type: sql
query: SELECT COUNT(*) FROM customer_orders_v2 WHERE processing_timestamp < actual_timestamp
mustBe: 0
slaProperties:
- property: latency
value: 1
unit: h
element: customer_orders.processing_timestamp
datacontract lint original.yaml
╭────────┬────────────────────────────────────────────┬───────┬─────────╮
│ Result │ Check │ Field │ Details │
├────────┼────────────────────────────────────────────┼───────┼─────────┤
│ passed │ Data contract is valid against ODCS v3.2.0 │ │ │
╰────────┴────────────────────────────────────────────┴───────┴─────────╯
🟢 Data contract is valid. Ran 1 checks. Took 0.008359 seconds.
Four things in that contract matter for the rest of this post:
- Row-level vs. Table-level validation: Notice how single-row conditions like
requiredorlogicalTypeOptionscan be enforced directly by Delta upon writing a row. In contrast, rules that inspect full datasets, such asduplicateValuesor customSQLqueries, require complete table scans and are best run during your automated test suite. - Contract metadata drives platform behavior: Fields like
classificationandtagscan directly automate data masking policies,teamestablishes governance ownership, andslaPropertiesfeed into operational monitoring and alerting. - Design for bitemporality: Always capture both business execution time and system ingestion time. Standard practice is to preserve historical snapshots in an append-only table, since Delta time travel capabilities have retention limits and aren't supported on tables with dynamic masking or row-level filtering.
- Explicit target routing: Always include the major version explicitly in your physical table target (e.g.,
customer_orders_v2) and leverage dedicatedauditservers so builds can undergo thorough testing before production publication.
Where dbt fits
A dbt contract (contract: {enforced: true}) is a local, build-time check. It verifies the shape of your model, making sure column names and basic data types match, though it skips finer details like precision, scale, or overall dataset rules. When you work on Databricks, it also translates your not_null and check definitions into native Delta table constraints. Simply put, the dbt contract acts as one specific compile target derived from your broader ODCS contract.
The open-source Data Contract CLI generates it from the ODCS file:
datacontract export dbt-models customer_orders.v2_1.odcs.yaml --server prod
This creates your model YAML with enforced types and adds a not_null constraint across your required columns, along with a unique constraint for your primary key. One catch: Delta cannot enforce uniqueness directly, and dbt-databricks will reject that constraint when use_materialization_v2 is enabled. In practice, you'll want your CI pipeline to strip uniqueness from the generated YAML and let your automated contract tests handle it instead. Range rules map to dbt_expectations tests, while broader table-level rules are intentionally omitted here, which is exactly why we set up a third validation gate downstream.
Remember that dbt also guards the input side of your promises. When your data product reads bronze inputs as dbt sources, running datacontract export dbt-sources converts the upstream producer's contract directly into source definitions, complete with column types, tests, ownership details, and PII tags. You'll just need to manually add source freshness settings based on the contract's SLA. That way, if an upstream team breaks their contract, your source tests fail early and protect your models from running on bad data.
How each ODCS element maps to dbt at build time and to Unity Catalog and Delta at run time:
| ODCS element | dbt, at build time | Unity Catalog and Delta, at run time |
|---|---|---|
| servers[].catalog, servers[].schema, schema[].name | database and schema (set by hand), model name | Three-level namespace |
| physicalType, required | contract: {enforced: true}, data_type, not_null | Delta schema enforcement and NOT NULL |
| logicalTypeOptions and other single-row rules | check constraints, added by hand (the export emits tests) | Delta CHECK constraints |
| Table-level and sql quality rules | Not compiled | datacontract test, before publish |
| classification, tags | databricks_tags, column_mask, row_filter (set by hand) | Governed tags, column masks and row filters |
| team, roles, description | grants, description, persist_docs | Grants, table and column comments |
| version | Model versions, latest_version, deprecation_date | Versioned tables behind a stable view |
| slaProperties | Source freshness, job schedule | Data quality monitoring and alerts |
The blueprint: one file, three gates

Figure 1. A unified contract file, published once and consumed by every port across your data product.
Publish contracts to a Unity Catalog volume
We recommend keeping contracts in Git under producer ownership, treating and reviewing them just like application code. Your CI pipeline should run datacontract lint and check for breaking changes against prior releases via datacontract breaking. Keep in mind that breaking treats any new rule as breaking, even at warning severity, so tune your CI checks to handle severity promotions.
Upon merging, CI publishes the contract file directly to a designated Unity Catalog volume within the table's native schema. This establishes clear domain ownership right where the data lives:
/Volumes/<catalog>/<schema>/data_contracts/<table>.v<major>_<minor>.odcs.yaml
Using a Unity Catalog volume has practical advantages over external services or custom registries. Any Unity Catalog compute engine can read the standard path natively, access is governed by Unity Catalog grants, just like your tables, and updating contract specifications becomes as simple as writing a file. Pipelines can pin specific versions directly in their paths, preventing unwanted breaking changes until teams are ready to upgrade.
Gate 1, compile: the dbt contract
During compilation, CI pulls the pinned contract file (using databricks fs cp dbfs:/Volumes/...) and regenerates the corresponding dbt model configuration, failing if it differs from the committed YAML. If the model's SQL no longer matches that YAML, say, a developer accidentally drops a column or alters a data type, dbt build immediately halts execution before writing a single row.
Gate 2, write: Delta constraints
Enable dbt-databricks' use_materialization_v2 flag so dbt creates target tables with not_null and check constraints before data insertion begins. Without this flag, constraints apply post-write, so bad records are already in the table by the time the check fails. With early enforcement enabled, Delta rejects invalid writes at the storage layer regardless of whether they originate from dbt, interactive notebooks, or manual fixes.
Gate 3, audit before publish: the contract test
While Delta constraints catch row-level issues, verifying uniqueness or dataset-wide business rules requires full-table queries. To handle this, we employ the Audit-Write-Audit-Publish (AWAP) pattern using a multi-task Databricks job workflow:
# Task 1 (dbt): build into the audit schema; gates 1 and 2 run here
dbt build --select customer_orders --target audit
# Task 2 (Python): test the audit table against the published contract (gate 3)
from datacontract.data_contract import DataContract
CONTRACT_PATH = "/Volumes/checkout/gold/data_contracts/customer_orders.v2_1.odcs.yaml"
test_run = DataContract(
data_contract_file=CONTRACT_PATH,
server="audit",
spark=spark,
).test()
# Warnings pass; only failures and errors stop the job
if test_run.result in ("failed", "error"):
raise RuntimeError(f"Contract test {test_run.result}")
-- Task 3 (SQL), only if task 2 passed: publish the audited rows in one Delta commit
INSERT OVERWRITE checkout.gold.customer_orders_v2 (
order_id,
customer_email,
...
)
SELECT
order_id,
customer_email,
...
FROM checkout.audit.customer_orders_v2
If Task 2 catches a contract failure, production consumers are unaffected and keep reading the last valid snapshot. Make sure Task 3 runs with an identity that is exempt from the masking and row filter functions, so the copy keeps clear values and every row. List the columns in the same order in the INSERT and the SELECT, because Databricks matches them by position, or use BY NAME on Databricks Runtime 13.3 LTS and above. Finally, the CLI evaluates only freshness and retention service levels, so it skips our latency SLA (see the CLI docs). Add a monitor on the published table to check it.
Ingestion pipelines: matching expectations
For streaming ingestion workloads managed via Lakeflow Spark Declarative Pipelines rather than dbt, single-row contract rules map directly to declarative expectations (such as CONSTRAINT positive_amount EXPECT (total_amount > 0) ON VIOLATION DROP ROW). Use FAIL UPDATE for critical rules that must stop ingestion, and standard logging actions for non-critical warnings.
Running contracts day to day
Contracts also move PII governance left, into the contract definitions. Producers label sensitive fields with classification and tags, while CI enforces these metadata requirements. When combined with dbt-databricks' use_materialization_v2, the column_mask and row_filter settings you declare on the model apply those policies in Unity Catalog.
When introducing new rules, consider starting them as warnings (severity: warning) to observe compliance patterns before elevating them to hard errors. If a dataset can't satisfy a constraint immediately, document an explicit waiver in customProperties with an owner and target resolution date rather than deleting the rule outright.
Test what consumers receive, not only what you build. External file exports and Delta Sharing endpoints act as output ports too. Ensure shared tables carry published contracts, and materialize external data exports as distinct dbt models to test them directly against format expectations before transmission.
Versioning without breaking consumers
Contracts follow Semantic Versioning. Each major or minor update should produce a new version file alongside the existing one, leaving only minor documentation updates to be edited in place. For a breaking change:
- Publish the new major version (e.g.,
customer_orders.v3_0.odcs.yaml) and runcustomer_orders_v3concurrently with v2 during an agreed migration window. Use dbt'slatest_versionanddeprecation_dateto give downstream consumers a clear upgrade path. - Provide a stable, unversioned view (e.g.,
customer_orders) for standard SQL queries that don't require pinned versions. - Before decommissioning an older table version, check Unity Catalog's column lineage (
system.access.column_lineage) to find active consumers and agree on a retirement date with them.
Start with one gold table
Data Mesh lets domain teams ship on their own schedule, and contracts keep that from breaking the teams downstream. ODCS gives us a shared specification, dbt validates transformations at build time, Delta enforces row integrity, and automated contract tests audit dataset health before publication. Unity Catalog binds everything together with central contract delivery, access policies, and end-to-end lineage tracking.
If you're looking to get started, pick a single key gold table that downstream teams heavily rely on today. Draft its contract, publish it to a Unity Catalog volume, generate its dbt model constraints, and add an audit gate to its pipeline workflow. From there, expanding contract coverage becomes a predictable, manageable process: one pull request at a time.
FAQ
-
What is the Open Data Contract Standard (ODCS)?
ODCS is an open YAML standard maintained by Bitol, a Linux Foundation project. A contract records a dataset's owner, schema, quality rules, service levels, classifications and servers.
-
Where should data contracts be enforced in a medallion architecture?
At the boundary points where external teams consume data: bronze input ports, gold output ports, and shares or exports. Silver tables stay internal and are covered by dbt tests that the team can change freely.
-
What are the three gates for enforcing an ODCS contract on Databricks?
Compile, with a dbt contract generated from the ODCS file; write, with Delta NOT NULL and CHECK constraints; and audit before publish, with a contract test on the audit table before rows reach production.
-
Why publish data contracts to a Unity Catalog volume?
Any Unity Catalog compute engine can read the path natively, access is governed by Unity Catalog grants like your tables, and pipelines can pin specific contract versions in their paths.





