Transformation as Code: Models and Tests

A transformation starts life as a question someone asked of a database: how much revenue did each order produce, which customers were active last week. The first answer is usually a query pasted into a console. The query becomes useful the day another query depends on its result, and it becomes dangerous the day someone changes it without knowing who else depends on it. Transformation as code is the set of practices that make this situation manageable: each transformation lives in a file, the dependencies between files are explicit, assertions about the results run automatically, and a change reaches production through the same review and deployment path as any other code.

This article follows that idea through dbt, a widely documented tool for SQL transformations, because its model, test, and dependency concepts are small enough to examine in full. The goal is not to teach dbt commands. It is to explain what a model is, how a dependency graph is derived from SQL, what a data test can and cannot prove, why an incremental model can quietly disagree with a full rebuild, and what deployment means when the thing being deployed is a set of SQL files plus a warehouse that already contains state. It assumes the orchestration ideas from Apache Airflow Fundamentals (a scheduled run has a data interval, a task can be retried) and the retry-safety ideas from Building Incremental and Idempotent Pipelines (an operation can be repeated safely only if its identity, inputs, and destination rule are defined). Scheduling and recovery are the subject of the next article, Airflow Operations; this article stays with the transformation layer.

Versions matter for tooling articles, so here is the evidence base. The behavior described below comes from the dbt documentation pages read in early October 2026 and from runs of dbt-core 1.12.5 with the dbt-duckdb adapter 1.11.0 on a local DuckDB database (Python package duckdb 1.5.6). Outputs labeled as runs were produced by those versions on small invented tables; they illustrate how the tool behaves, and other adapters can differ, particularly in incremental strategies and constraint enforcement.

From a SELECT statement to a model

In dbt, a model is a file containing one SELECT statement. The file name is the model name. When the project is built, dbt wraps the statement in the DDL that persists it, create view as or create table as, and creates an object with the file name in the target schema. By default the object is a view; the persistence choice is configuration, not SQL. A model materialization is the strategy that decides what the warehouse stores: a view stores only the query, a table stores the computed rows and is rebuilt on every run, an incremental model keeps its previous rows and adds or updates a selected subset, and an ephemeral model is inlined as a common table expression and stores nothing.

The reason this is described as code rather than as a collection of queries is what a file gives you. A file can be reviewed, diffed, tested before it is merged, reverted, and owned. The name of the object in the warehouse is derived from the file, so two engineers cannot disagree about which query produced a table. And because the SELECT is the only thing the author writes, the tool, not the author, takes responsibility for creation order, for replacing the previous object, and for pointing the same code at different schemas in different environments.

That last point depends on a single function. Instead of naming a relation directly, a model refers to another model with ref. The dbt documentation describes two effects: the function interpolates the schema into the SQL so that the deployment schema can be changed by configuration, and the references between models are used to build the dependency graph, which determines the order in which models are built. Here is a minimal chain used for the runs in this article. The source is a seed table of payments, invented for the illustration.

-- models/stg_payments.sql : a thin cleanup layer over the raw table
select payment_id, order_id,
       cast(amount as integer)      as amount,
       cast(updated_at as date)     as updated_at
from {{ ref('raw_payments') }}

-- models/fct_payments_full.sql : the same rows, rebuilt from scratch on each run
select * from {{ ref('stg_payments') }}

Compiling fct_payments_full replaces the ref call with the fully qualified name of the other model’s relation, for example "demo"."main"."stg_payments" in the local run. The same source text compiled against a different target would produce a different schema name. This indirection is why the code can be promoted between environments without edits, a property the follow-up article on pipeline CI/CD and environment promotion relies on.

SQL model dependencies

The graph is derived, not declared

No one writes the dependency graph by hand. dbt parses each model, collects the ref and source calls, and records an edge from each referenced node to the referencing model. The result is a directed acyclic graph: edges have a direction (the upstream model must exist before the downstream model can be built) and no path may return to its start. The word DAG appears in Airflow as well, and the two should not be confused. An Airflow DAG is a graph of tasks that run at scheduled times. A dbt graph is a graph of relations in a warehouse, and a single Airflow task might run the whole of it or a slice of it.

Because the graph is derived from SQL text, it is only as complete as the references the parser sees. A model that selects from a hard-coded relation name, such as main.stg_payments written literally, builds correctly if the relation happens to exist, but contributes no edge. Nothing then guarantees that the upstream model is built first, and a selection of “everything downstream of stg_payments” will not include it. This follows from how ref creates dependencies and is why references between models should always go through ref or source. The same limit applies to dependencies that appear only at execution time, such as a value read through a variable or an environment variable: the documentation on state comparison notes that dbt cannot identify lineage through a changed var or env_var.

Cycles, ordering, and selection

A graph that contains a cycle has no valid build order, so dbt rejects it. In a local run with two models, a and b, each referencing the other, compiling failed at the graph stage:

Compilation Error
  Found a cycle: model.demo.a --> model.demo.b

The message identifies the models in the loop. Parsing the project alone did not report the cycle in that run; the error appeared when the command needed the graph (compile, run, build, or list). The practical consequence is that a continuous integration job should execute a command that builds the graph, not merely check that the files parse.

The graph also supports selecting part of a project. A + in front of a model name selects the model and everything upstream; a + after the name selects the model and everything downstream. Using the small project above, listing models downstream of the staging model and upstream of the full fact model gave:

dbt ls -s "stg_payments+" --resource-type model
demo.fct_payments_full
demo.fct_payments_inc
demo.stg_payments

dbt ls -s "+fct_payments_full" --resource-type model
demo.fct_payments_full
demo.stg_payments

Selection is how a team runs a change safely without rebuilding the world. It is also how an incident is scoped: if stg_payments was wrong, the downstream selection is the list of relations that may hold wrong data. That is the same question that data lineage answers at organization scale, and the model graph is the smallest honest version of it: exact for what the SQL references, silent about everything outside the project, such as a dashboard that reads a table directly.

Layers are a convention

Most projects arrange models in layers: a staging layer that renames, casts, and cleans one source table each, an intermediate layer that joins and reshapes, and a marts layer that exposes business entities such as orders or customers. This is a common convention, not something the tool enforces, and its value is in what it limits. Only staging models read raw tables, so a change in a source’s column names is absorbed in one place. Marts depend on staging and intermediate models, never on raw data, so every business definition passes through the same cleaned inputs. The convention fails when a team skips layers for speed: a mart that reads a raw table directly creates a second place that must be updated when the source changes, and the graph shows it only if the reference is a ref or source call.

Reusable transformations

Reuse in SQL has two distinct forms, and they solve different problems. The first is reuse of data: a model that computes a cleaned or enriched set of rows, which many other models read through ref. The second is reuse of expressions: a fragment of SQL, such as a currency conversion or a fiscal-calendar calculation, that many models need to apply in the same way. In dbt the second form is a macro. The documentation describes macros as pieces of Jinja that are analogous to functions, defined in .sql files, usually in a macros directory, and expanded before the SQL is sent to the warehouse.

-- macros/to_major_units.sql
{% macro to_major_units(column_name, scale=2) %}
    round({{ column_name }} / 100.0, {{ scale }})
{% endmacro %}

-- models/payments_major.sql
select payment_id, {{ to_major_units('amount') }} as amount_major
from {{ ref('stg_payments') }}

Compiling the second file in the local run produced plain SQL with the macro body expanded in place:

select payment_id,
    round(amount / 100.0, 2)
 as amount_major
from "demo"."main"."stg_payments"

Nothing about the macro survives into the warehouse. That has consequences for choosing between the two forms. A macro is the right tool when the logic is an expression that must be identical wherever it appears, because changing the macro changes every caller at the next build. The same property is its risk: a change to a macro can alter many models at once, and dbt’s state comparison treats any resource that depends on a changed macro, directly or through another macro, as modified. A reviewer must therefore read a macro change as a change to every caller. A model is the right tool when the result is a set of rows that other models should share, because the rows are computed once, can be tested once, and can be inspected in the warehouse. Putting row-producing logic in a macro duplicates computation and hides it from the graph; putting a one-line expression in a model forces an extra join or an extra relation for no benefit.

Reusable assertions follow the same idea. A generic data test, described below, is a parameterized query that takes a model and a column and can be attached anywhere. The documentation notes that generic tests tend to make up the bulk of a test suite for exactly this reason. The cost of all this abstraction is legibility: a reader who sees {{ to_major_units('amount') }} must open another file to learn that amounts are integer minor units. Keep macros small, name them for the business rule rather than the SQL function, and prefer a visible model whenever the logic is more than an expression.

Data tests: queries that return failing rows

A data test in dbt is a SELECT statement that returns the rows which disprove an assertion. If the query returns zero rows, the test passes. The documentation states this directly: asserting that a column is unique means the test selects duplicates, and asserting that a column is never null means the test selects nulls. Two forms exist. A singular test is a query saved in the tests directory, usable once. A generic test is a parameterized query defined in a test block and referenced by name in YAML. Four generic tests ship with dbt: unique, not_null, accepted_values, and relationships, the last being a referential-integrity check between a column and a column in another model.

models:
  - name: fct_payments_inc
    columns:
      - name: payment_id
        data_tests: [unique, not_null]

In the run, the two tests on payment_id passed. What did that establish? Only that, at the moment the tests ran, no two rows in the tested relation shared an identifier and none was missing one. Three limits are worth stating plainly because they are where confidence is most often misplaced.

  • Tests inspect the current contents, not the change. A passing unique test says nothing about whether the right rows are present. The incremental drift shown later in this article passed both tests while holding a stale amount.
  • A test can only detect what its query can express. A row that should exist but does not leaves no failing row for a not_null test to find. Completeness needs a comparison against an independent quantity, such as a source count or a total from another system.
  • A test on an upstream model gates downstream work only if the pipeline is run that way. The documentation for dbt build says it runs models, tests, snapshots, and seeds in dependency order and that a failing test on an upstream resource causes downstream resources to be skipped. Running dbt run and then dbt test as separate steps lets bad data flow downstream before any assertion has looked at it.

Severity is a decision, not a default. The same page notes that a test can be configured to warn instead of error, which stops it from blocking downstream models. A warning is appropriate for a heuristic (a row count within an expected range) and wrong for an invariant (an order has exactly one customer). When every failure is an error, teams learn to bypass the suite; when every failure is a warning, nothing is enforced. Deciding which assertions are invariants is part of the model’s design, and the list of invariants is, in effect, the part of a data contract that must block publication.

Unit tests check the logic, data tests check the data

Data tests run after a model has been built, against whatever data the warehouse holds. Unit tests, available from dbt 1.8 according to the documentation, run a model’s SQL against a small set of static input rows and compare the output to expected rows, before the model is materialized in production. The two answer different questions. A data test asks whether today’s data satisfies an assertion. A unit test asks whether the transformation does what its author intended, including on inputs that have not yet occurred. The generic idea is the one described in unit and integration tests, with a fixture supplying the controlled input.

unit_tests:
  - name: day1_excludes_the_next_day_boundary
    model: day1_total
    given:
      - input: ref('stg_payments')
        rows:
          - {payment_id: 1, order_id: 1, amount: 10, updated_at: 2024-10-01}
          - {payment_id: 2, order_id: 2, amount: 5,  updated_at: 2024-10-01}
          - {payment_id: 3, order_id: 3, amount: 7,  updated_at: 2024-10-02}
    expect:
      rows:
        - {total: 15, n: 2}

The model under test sums payments with updated_at >= date '2024-10-01' and updated_at < date '2024-10-02'. The fixture is built around the one row that distinguishes a correct boundary from an incorrect one: a payment at the first instant of the next day. With the correct half-open interval the test passed. To check that the test can fail, the comparison < was changed to <=, a one-character edit that real code review misses easily. The run reported:

actual differs from expected:
@@ ,total,n
+++,22   ,3
---,15   ,2

The output reads as a diff: the actual result has total 22 over 3 rows, the expected result total 15 over 2 rows, so the boundary row was wrongly counted. This is the behavior to look for in any unit test, that a nearby wrong implementation fails. A fixture that every plausible implementation satisfies tests nothing. A data test would not have caught this mistake at all, because the wrong total is a perfectly valid number; only the intent, written down as an expected row, distinguishes the two.

The dbt documentation lists what is currently out of scope: only SQL models in the current project can be unit tested, materialized views and recursive SQL are unsupported, and the inputs of every ref and source must be given. It also advises where to spend the effort: logic with regular expressions, date arithmetic, window functions, or many case when branches; behavior that has previously produced bugs; and models with high criticality. It advises against unit testing built-in functions such as min(), which the warehouse already tests. Because the inputs are static, the documentation recommends running unit tests in development and continuous integration and excluding them from production builds, since repeating them in production spends compute without new information.

Incremental correctness

What an incremental model computes

A table model recomputes everything on each run. When that becomes too slow or expensive, an incremental model processes only a selected subset and merges it into the table that already exists. The documentation defines is_incremental() as true only when three conditions hold: the model already exists as a table, the run is not a full refresh, and the model is configured as incremental. The model’s SQL must be valid in both modes, and the author writes the filter that decides which source rows an incremental run selects. The usual filter is “rows newer than the maximum timestamp already in this table.”

The word “incremental” suggests that the tool works out what changed. It does not. The tool applies whatever filter the author wrote and then inserts, updates, or replaces the rows that filter selected, according to the configured strategy. Correctness therefore has a precise statement. An incremental model is correct when, for every source state the pipeline can encounter, the table after the incremental run equals the table a full rebuild would produce from the same source. A model that satisfies this is a performance optimization. A model that does not is a second, different transformation that happens to share a name.

A drift, step by step

The first experiment shows a model that is correct on its first run and wrong afterwards. The source has three payments. The incremental model selects rows with a later updated_at than the table already holds, and a comparison test checks it against the full model with an except in both directions.

-- models/fct_payments_inc.sql
{{ config(materialized='incremental', unique_key='payment_id') }}
select * from {{ ref('stg_payments') }}
{% if is_incremental() %}
where updated_at > (select max(updated_at) from {{ this }})
{% endif %}

-- tests/inc_matches_full.sql  (returns the rows on which the two models disagree)
(select * from {{ ref('fct_payments_full') }} except select * from {{ ref('fct_payments_inc') }})
union all
(select * from {{ ref('fct_payments_inc') }} except select * from {{ ref('fct_payments_full') }})

On the first build the table did not exist, so the whole filter was skipped, all seven nodes passed (seed, three models, three tests), and the comparison test returned zero rows. This is the most important sentence in the section: a first build exercises only the full path. The branch inside is_incremental() had not run at all.

Then the source changed in two ways, both ordinary. Payment 1 was corrected from 40 to 45 by the source system, which did not change its updated_at value. And a new payment 4 arrived dated 2024-10-03. The incremental run selected only rows with updated_at later than 2024-10-02, so it saw payment 4 and missed the correction. The comparison test now failed with two rows, one from each side of the difference. The two relations afterwards:

fct_payments_inc (after the incremental run)      fct_payments_full (view over the current source)
(1, 100, 40, 2024-10-01)   <- stale amount        (1, 100, 45, 2024-10-01)
(2, 101, 25, 2024-10-01)                           (2, 101, 25, 2024-10-01)
(3, 102, 10, 2024-10-02)                           (3, 102, 10, 2024-10-02)
(4, 103, 30, 2024-10-03)                           (4, 103, 30, 2024-10-03)

The unique and not-null tests on the incremental model passed throughout. The model was internally consistent and externally wrong, which is the signature of incremental drift. The failure is silent in production because no error is raised, and it grows: every correction that does not advance the filter column is lost, and nothing reconciles the table until someone compares it with the source.

Repairs, and what each one assumes

The fix chosen has to match how the source behaves, and each fix is a claim about that behavior.

  • A lookback window. Select rows from a few days before the table’s maximum instead of strictly after it, and rely on a unique key so that re-selected rows replace their earlier versions. In the run, changing the filter to updated_at >= (select max(updated_at) - interval 3 day from {{ this }}) repaired payment 1 and the comparison test passed. The assumption is that corrections arrive within the window; a correction to a row older than three days is still missed. The idea is general and covered in late data and lookback.
  • A change timestamp. If the source maintains a reliable modification time, filter on that rather than on the business date. This removes the window assumption but depends on the source updating the column on every change, including deletes of any kind, which many systems do not record.
  • A bounded rebuild. Replace whole partitions (see partition overwrite) when the unit of correction is a date range, which requires the replacement to contain every row that belongs in the range.
  • A periodic full refresh. Rebuild from scratch on a schedule to bound the age of any undetected drift. This trades compute for a stated upper bound on staleness. The documentation says to run a full refresh of an incremental model and its downstream models whenever the logic of the incremental model changes.

The unique key decides what a repeated selection does

The lookback repair works only because a unique key was declared. The documentation explains that with a unique_key, a selected row whose key already exists replaces the old row, and a row with a new key is inserted. Without one, most adapters append, “without regard for whether the rows represent duplicates.” The same lookback filter, run once with no unique_key on top of the four rows already in the table, produced this:

select count(*), count(distinct payment_id) from fct_payments_inc
(8, 4)        -- after the lookback run with no unique_key: every selected row appeared twice

-- after dbt run --full-refresh
(4, 4)

Eight rows for four payments: the rows selected by the window were inserted again on top of the rows already present. A full refresh restored four. The compiled SQL for the keyed model in this adapter version shows the mechanism, a delete of matching keys followed by an insert from a temporary relation:

delete from "demo"."main"."fct_payments_inc"
where (payment_id) in (
    select (payment_id) from "fct_payments_inc__dbt_tmp..."
);

insert into "demo"."main"."fct_payments_inc" (payment_id, order_id, amount, updated_at)
(select payment_id, order_id, amount, updated_at from "fct_payments_inc__dbt_tmp...")

The temporary relation name is abbreviated. Other strategies exist, and the documentation lists append, merge, delete+insert, insert_overwrite, and microbatch with support that varies by adapter; the strategy used above was the one the adapter applied by default. A merge matches on the key and applies update and insert actions; the semantics of key matching, including what happens with duplicate keys in the incoming batch, are described in upsert and merge. The documentation adds a warning that matters in practice: key columns should not contain nulls, because a null cannot match, and a key that is not truly unique in the existing table or the incoming rows can make the run fail or produce duplicates depending on the strategy.

Declaring a key makes the run repeatable in the sense of idempotency: selecting the same rows twice leaves the same table, because the second selection replaces what the first inserted. It does not by itself make the result correct. A repeatable operation applied to the wrong selection is repeatably wrong, which is what the drift run demonstrated.

Schema changes and deletions

Incremental tables carry their column list with them. The documentation describes the on_schema_change option: ignore is the default, fail raises an error when source and target schemas diverge, append_new_columns adds new columns without removing missing ones, and sync_all_columns adds new columns and removes those no longer present. It adds that none of these backfills values in old rows for a new column. Two runs show the default and one alternative. A new column amount_cents was added to the select list:

on_schema_change='ignore' (default)
columns: payment_id, order_id, amount, updated_at              <- new column silently absent

on_schema_change='append_new_columns'
columns: payment_id, order_id, amount, updated_at, amount_cents
(1, 100, 45, 2024-10-01, 4500) ...

Under the default, the run succeeded and the new column never appeared, so a downstream model that referenced it would have failed later, far from the cause. In a second run, with the column removed from the select list while the table still had it and the option still at ignore, the run failed: Binder Error: Referenced column "amount_cents" not found in FROM clause!, which matches the documentation’s statement that removing a column fails under the default. In the append case the earlier rows would only receive values for the new column if they are re-selected; the table in this small run was fully re-selected because the lookback window covered every row, which is why every row shows a value. In a large table the older rows would hold nulls until a full refresh or an explicit update.

Deletions are the other hole. A filter that selects new or changed rows cannot select a row that no longer exists, so a source delete never reaches an incremental table unless the design includes a replacement of the affected range or an explicit delete step. Whether stale rows are acceptable depends on the meaning of the table: an event log should keep them, a current-state table should not.

Testing incremental behavior

The comparison test above, a difference in both directions between the incremental model and a full rebuild of the same logic, is the direct test of the correctness statement. It has costs and limits that decide where it can run. It needs the full computation to exist, which is affordable on a sample or a bounded date range and not on the largest tables. It tests only the source states you present; the drift appeared because the second state contained a correction, so a test suite must include at least one run in which previously seen rows change. And it has to run after at least one incremental execution, since a fresh build tests only the full path. For a model that matters, a repeatable sequence is build, mutate the source in each way the real source can change (late rows, corrections, deletes, a new column), run incrementally, and compare with a full rebuild. On production-sized tables, the comparison becomes a reconciliation on counts and aggregates over a window, which is weaker evidence and should be described that way.

The documentation points to a related facility for continuous integration: dbt clone can copy the production state of incremental models into a development schema on warehouses that support zero-copy cloning, so that a CI run exercises the incremental branch against realistic state without a costly full refresh. Without such state, CI executes only the first-build path.

Data tests and deployment

Deployment of transformation code has an unusual property: the code is deployed to a place that already contains data. Merging a pull request changes SQL files; the effect on the warehouse happens when the next scheduled run builds the changed models, and what that build does depends on the table already there. A view is replaced instantly and cheaply. A table model is rebuilt, which is safe if the logic is correct and the rebuild completes. An incremental model is not rebuilt at all unless a full refresh is requested, so a change in its logic applies only to newly selected rows, and the table becomes a mixture of old and new logic. This is why the documentation instructs a full refresh of the model and its downstream models whenever the incremental logic changes, and why that instruction belongs in the deployment procedure and not in someone’s memory.

A defensible deployment sequence follows from the pieces above. Each step names what it protects.

  1. Parse and compile the whole graph. This catches cycles, missing references, and invalid configuration, none of which require data.
  2. Run unit tests. They need no warehouse data, so they are cheap and catch logic errors on boundary rows. Exclude them from production runs.
  3. Build the changed models and everything downstream into an isolated schema, with tests. The documentation for dbt platform CI describes this: it builds and tests the modified resources and their downstream dependencies in a temporary schema unique to the pull request. The state comparison that selects “modified” resources has documented caveats: changes to tags and metadata do not count, a changed macro marks its dependents, and a changed variable may not be detected. A test that selects from both a modified and an unmodified model may read across two environments when upstream references are deferred, so referential tests deserve a check on whether they make sense on sampled data.
  4. Run the comparison and data tests against realistic state. For incremental models, that means state that has already been through an incremental run.
  5. Promote by running the same code against production with dbt build. Because build runs tests in graph order and skips the downstream of a failing upstream test, a bad batch stops where it was detected instead of reaching every consumer. Unit tests are excluded here by resource type, as the documentation recommends.
  6. Apply the full refresh or migration step the change requires, deliberately and in order. This is the step most often left to chance; its design is the subject of the article on pipeline CI/CD, promotion, and rollback, two articles ahead.

How these steps are triggered is a separate design choice. A single orchestrator task can invoke the entire build, which keeps the graph logic inside dbt and gives the orchestrator one thing to retry. Alternatively each model can be exposed as its own orchestrator task, which gives per-model retries, pools, and alerts at the price of translating the graph into the orchestrator’s vocabulary and keeping the two in sync. Neither choice is documented as a best practice; they are a trade between observability and simplicity, and the second is justified only when the orchestrator’s per-task controls are actually needed. Either way, the interval the orchestrator assigns to the run must reach the SQL, for example as a variable, so that a rerun of an old interval selects the old interval’s rows rather than the latest ones; the mechanics and failure modes of that handoff are in Airflow Operations: Retries, Backfills, and Safe Recovery.

A contract is the last guard in the sequence. A dbt model can declare an enforced contract listing every column’s name and type; the documentation says dbt then runs a preflight check that the query returns matching columns before building, and includes the types and any supported constraints in the DDL. Contracts are supported for table, view, and incremental models (with on_schema_change set to append_new_columns or fail), not for ephemeral models or materialized views, and constraint enforcement varies by platform. They prevent an accidental rename from reaching consumers; they cannot say whether a column’s meaning has changed. The producer’s wider promises, including meaning and freshness, belong in a data contract, and structure changes over time are classified in schema evolution and compatibility. The article on pipeline CI/CD returns to contracts as tests between producers and consumers.

Failure modes and limits

The table collects the failures that this article’s mechanisms produce, with the evidence that exposes each and the repair. It is organized by mechanism, not by tool feature.

FailureMechanismHow it shows upRepair
Incremental driftFilter selects only rows with a later timestamp; corrections keep the old timestampPasses unique and not-null; comparison with a full rebuild failsLookback or change-timestamp filter with a unique key; periodic full refresh; comparison test after a mutated source
Duplicate rowsNo unique key, or a key containing nulls, under an append or matching strategyRow count exceeds distinct key count (8 versus 4 in the run)Declare a non-null unique key; test uniqueness; full refresh to repair
Only the first-build path is testedA fresh CI schema makes is_incremental() falseCI is green; the first production incremental run fails or driftsClone production state into CI or run a second, incremental build in CI
Silent schema divergenceon_schema_change left at ignoreNew column absent; removed column breaks the runChoose an explicit option; enforce a contract; plan a backfill for old rows
Missing graph edgeLiteral relation name instead of ref or sourceBuild order wrong; selection by lineage omits the modelUse references everywhere between models
Test gives false comfortAssertion cannot express the property (completeness, meaning)All tests pass while totals are wrongReconcile against an independent source; add unit tests for logic
Bad data flows downstreamModels run and tests run as separate, ungated stepsConsumers read a table that a test would have rejectedBuild in graph order so a failing test skips downstream
Macro change with wide effectOne macro used by many modelsMany models change from a one-file diffReview callers; run the modified selection; keep macros small

Two limits apply to everything above. First, all of the run output in this article comes from small invented tables on a local database. It shows behavior, not performance: the cost of a full refresh, the speed of a merge, and the effect of a lookback window on scan volume depend on data size, warehouse, and strategy, and none was measured. Second, dbt is one implementation of the idea. The principles (derive the graph from references, treat tests as queries over failing rows, define incremental correctness as equality with a full rebuild, deploy against existing state) apply to other tools, but their defaults and failure messages will differ, and an adapter’s incremental strategies should be read from its own documentation before they are trusted.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.