guide
guide7 min read

How to write dbt model contracts (and when to fail CI on them instead of tests)

Five steps to enforce a model's shape in dbt, and a rule for which failures belong in CI

To write a dbt model contract, set contract: {enforced: true} under the model's config in its YAML file and declare a name and data_type for every column. dbt then compares the columns and types your SQL returns against that declaration and fails the build before anything is materialized if they differ, as described in the dbt model contracts documentation. A contract guards the shape of a model. A data test checks the values inside it. That difference decides which one should fail your CI build.

Key Takeaways

  • •A dbt model contract enforces column names, data types and optional constraints at build time, before the model is materialized.
  • •A dbt data test runs after the model is built and checks values: uniqueness, nulls, accepted values, relationships.
  • •Fail CI on contracts for any model other teams consume, because a shape change there is a breaking change for them.
  • •Keep value-level checks as tests, and decide per test whether it blocks a merge or only alerts.
  • •Contracts only protect you if CI actually builds the changed models and the models downstream of them.

How to write dbt model contracts: the short version

A contract is a promise about the interface of a model. Downstream models, dashboards and other dbt projects depend on that interface, not on your SQL. When someone renames customer_id or changes order_total from a decimal to a string, the query still runs. Everything that reads it breaks later, usually at the worst moment.

Contracts move that failure to the pull request. The steps below follow the order we use when we add a contract to an existing model. They assume a recent dbt version. Contracts shipped in dbt 1.5, and support for individual constraints varies by warehouse, so check the docs for yours.

Step 1: Pick the models that deserve a contract

Do not put contracts on every model. A contract adds friction on purpose: every column needs a declared type and every schema change needs a deliberate edit to the YAML. That friction pays off where other people depend on the output.

Our rule of thumb is to start with models that have a consumer you do not control. That means the marts that feed dashboards, the models exposed to other dbt projects, and anything a machine learning feature pipeline reads. dbt pairs contracts with access: public for models that other projects reference. Staging and intermediate models usually stay uncontracted, because you own every consumer and can fix them in the same PR.

Step 2: Declare every column with a data_type

Enforcement requires a complete column list. Under the model in your properties YAML, add the config and list every column the model returns, each with a data_type. A model with contract: {enforced: true} and a missing column definition fails at build time, which is the behavior you want.

  • •Use the exact type names your warehouse reports, such as varchar, integer, numeric(18,2) or timestamp. Aliases that look equivalent to you may not match the warehouse's own type names.
  • •List columns in the same names the SQL produces. A casing or alias mismatch is a contract violation, not a cosmetic issue.
  • •Keep the description on each column. The contract file doubles as the documentation consumers read.

If you are retrofitting a contract, run the model once and read the column types from the warehouse's information schema. Then copy them into the YAML rather than guessing.

Step 3: Add constraints where the warehouse can enforce them

Beyond names and types, dbt supports a constraints block per column or per model: not_null, unique, primary_key, foreign_key, check and custom expressions. The important caveat is in the dbt constraints documentation. dbt writes the constraints into the table DDL, but whether the warehouse enforces them depends on the platform. Some warehouses enforce only not_null and treat the rest as informational metadata.

So treat constraints as a layered tool. Use not_null freely because it is widely enforced. For uniqueness and key relationships, keep a data test alongside the constraint unless you have confirmed your warehouse rejects violating rows. A constraint that is never enforced reads like a guarantee and provides none.

Step 4: Decide what fails CI: contract or test

This is the part most teams skip. Contracts and tests both stop a bad deploy, but they stop different bad deploys at different times. The table is our working rule, and it is our opinion rather than a dbt requirement.

QuestionContractData test
What does it check?Column names, types, declared constraintsValues in the built data
When does it fail?During the build, before the model is materializedAfter the model is built
What does a failure mean?The interface changed, so consumers will breakThe data is wrong, so consumers may get bad numbers
Should it block a merge?Yes, for any model with outside consumersOnly for invariants you would roll back for
Typical examplesDropped column, renamed column, type changedDuplicate keys, null rates, accepted values, freshness

The deciding question is whether the failure is a property of the code change or of the data. A contract violation is always a property of the code change: you can see it in the diff. It is deterministic, cheap to detect and safe to block on. A test failure is often a property of the data that arrived this morning. If every flaky upstream value blocks merges, engineers learn to ignore CI or retry until it passes.

So we fail pull requests on contract violations and on a short list of invariant tests, such as primary key uniqueness on contracted models. Distribution checks, row-count swings and freshness go to alerting, not to merge gates.

Step 5: Run contracts in CI against modified models and their children

A contract only fails when the model is built. If CI runs dbt parse or dbt compile, a type change sails through. CI has to build the changed models. The standard pattern is slim CI: compare against the production manifest and build only what changed plus everything downstream, using dbt build --select state:modified+ --defer --state <path-to-prod-manifest>. The dbt state-based selection docs cover the state: selectors, including variants that isolate contract changes.

  • •Build into a throwaway schema per pull request, so a failed contract never touches production objects.
  • •Use dbt build, not dbt run followed by dbt test, so contracts, tests and downstream models run in dependency order and a failure stops the dependents.
  • •Store the production manifest as a CI artifact after every deploy. A stale manifest makes state:modified select the wrong models.
  • •When a contract change is intentional, version the model. dbt model versions let consumers migrate on their own schedule instead of breaking on merge.

What a contract does not catch

A contract says a column exists and has a type. It cannot tell you that revenue silently changed meaning, that row counts dropped 40% overnight, or that a join key stopped matching after a migration. Those are the questions that still land on an engineer: "Why did row counts drop 40% overnight?" and "Is the customer_id join safe after the migration?" Contracts and tests narrow the search. They do not answer it.

There is also a maintenance cost that is easy to underestimate. Every contracted model carries a YAML file that must match the SQL exactly. Teams that adopt contracts on twenty models are fine. Teams that adopt them on four hundred models spend real time keeping the declarations in sync, and the work is mechanical enough that people skip it.

Enforcing contracts with an agent workflow

The mechanical parts of this tutorial are where an AI coding agent earns its place: reading the warehouse's actual column types, generating the YAML, and checking the blast radius of a change before the PR opens. We built Data Workers so that capability runs from inside Claude Code or Cursor. Every agent is an MCP server, and the Model Context Protocol is the interface your coding agent already speaks.

In practice the workflow looks like this. You ask your coding agent to contract a mart. Our Pipeline Agent reads the model and the live column types, writes the contract block, and runs the slim CI selection locally. Our Catalog Agent) supplies the consumers of the model, so the question "What's the blast radius if I drop this column?" gets an answer listing the dashboards and downstream models, not a guess. The open-source edition is read-only by default, so it proposes changes and you review them. Writes and approval workflows are in Pro.

We covered how Data Workers keeps catalog metadata current in a separate post, and the same context is what makes the contract check meaningful: an agent that knows who consumes a column can tell a harmless change from a breaking one. If a contract fails in CI, our Incidents Agent can trace the failing change back to the commit that caused it. We think that is a better use of an engineer's time than reading a type-mismatch error and diffing YAML by hand.

Frequently Asked Questions

What is the difference between a dbt model contract and a dbt test? A contract validates the structure of a model (column names, data types, constraints) during the build, before the model is materialized. A test runs a query against the built model and checks the values. Contracts catch interface changes, and tests catch bad data.

Should dbt contracts fail my CI build? Yes for models that other teams or tools consume, because a shape change there is a breaking change you can detect from the diff. For models you fully own, a contract is optional, and a failing downstream build may be enough.

Do dbt contracts replace tests? No. A contract cannot see values, so it cannot catch duplicate keys, unexpected nulls or out-of-range numbers unless your warehouse enforces the matching constraint. Keep tests for value-level invariants and use contracts for the interface.

Does every column need a data_type when a contract is enforced? Yes. dbt requires the full column list with types for a model with an enforced contract, and it fails the build if the SQL returns columns that are not declared or declares types that do not match.

How do I change a contracted model without breaking consumers? Treat it as a breaking change. Create a new model version, keep the old version available during a deprecation window, and let downstream owners move on their own schedule. Data Workers can list those consumers before you merge, so you know who needs to move.