ADR-0045: Unit tests, post-write data tests and pipeloom build¶
Architecture: Section 4, Configuration, section 5, Validation, section 7, Execution, and section 10, Data quality
Context¶
Expectations (ADR-0009, ADR-0028) judge each batch before it is written, and contracts (ADR-0044) fix its schema. Neither answers two questions users ask of a transformation. Does the body compute the right rows for a known input, without a warehouse? And does the written table hold together as a whole, for example every foreign key finds its parent? dbt answers the first with unit tests (given input rows, expect output rows, run on the warehouse without building parents) and the second with data tests (not_null, unique, relationships) run after the build; dbt 1.8 renamed the model key tests to data_tests to stop the two being confused (dbt unit tests, dbt data tests). dbt build runs both in DAG order.
Options¶
- Naming. A bare
testskey, orunit_testsanddata_tests. - Where cases live. On the model only, or also in separate files, with or without a new discovery path.
- Hashes. Cases in the plan and manifest, or kept out of both.
- Where a case runs. Through the full unit runner with a throwaway catalog, or by calling the body directly with in-memory inputs.
- Comparing rows. Ordered or as a multiset; with or without float tolerance; in the core or per engine.
- Data tests. As expectations with a new action, or as a separate list run against the written table.
build. A new scheduler that interleaves test nodes, ortestfollowed byrunwith data tests on.
Decision¶
Naming and config¶
unit_testsholds cases,data_testsholds post-write checks. There is no baretestskey. The roadmap text uses these names.- Under Python-first authoring (ADR-0050, point 15) unit tests live in the model's properties entry, as
unit_tests:besidedescription,config,columnsanddata_tests, and never on the decorator: rows are data, not code. The diagnostics point at the properties file. While the legacy YAML path coexists with Python-first (ADR-0050, point 19), a YAML model entry may also declareunit_tests:, and any YAML file undermodel_pathsmay hold a top-levelunit_tests:list whose entries name their model withmodel:(a missingmodel:is PLS105); both go away with the legacy path. There is no new discovery path and no new project key.unit_testsis a model key, not a setting: themodels:tree cannot set it. - A case is
{name, given: {alias: {rows | csv, columns?}}, expect: {rows | csv, columns?}}. Agivenkey is an input alias, which for a decorated function is the parameter name.rowsandcsvare mutually exclusive (PLS108). Every input alias of the model must be given, and only input aliases (PLR208). CSV paths are relative to the project dir and read with the standardcsvmodule; an empty field is null. Case names are unique per model (PLR208); an unknownmodel:is PLR208. - Cases stay out of
PlanNode, the manifest, the node checksum and the plan hash. Manifests and plan hashes are byte-identical with or without unit tests.
Types and comparison¶
- A given column's type comes from the given
columns, else from the upstream model's ADR-0044columns, else from inference. Inline values inferboolean,int64,float64,string,date,timestamp[us]andtimestamp[us, UTC]from their YAML type (a quoted date stays a string). CSV columns inferint64, thenfloat64, thenstring; dates and timestamps must be declared. An all-null column with no declared type is PLX115. - Comparison lives in
pipeloom.quality.rows, because the core may not importpipeloom.testing;pipeloom.testing.referencere-exports it. The compared columns are the keys ofexpect; extra output columns are ignored, a missing one fails the case. Expected values are cast to the output column's logical type. Rows compare as a multiset: order is ignored, duplicates count. Null equals NaN, floats are normalized to 12 significant digits, a naive timestamp is read as UTC, and decimals compare exactly. The diff lists missing and unexpected rows: 10 of each in the message, 50 in the event.
Running a case¶
- Given rows become relations through
EngineSession.from_rows(rows, schema). A SQL body runs through the existingsession.sql(body, inputs), which scopes the aliases to that query; a Python body is called asbuild(ctx, **inputs)withis_incremental=Falseand the model'sframe_api. The result is read back withEngineSession.to_rows(rel), which returns plain Python values. No materializer runs, no namespace is created and nothing touches the catalog or the state store. Ephemeral parents are not inlined: their alias is given like any other input. pipeloom testtakes--select,--exclude,--state,--target,--vars,--plugin,--project-dirand--log-format. It runs the cases of the selected models in plan order, takes no lock, writes no artifacts and creates no run id. Each case emitsunit_test.passedorunit_test.failed;unit_tests.completedcloses the invocation with the counts. A case whose rows differ is PLX114, a case that cannot run (a missing or unreadable CSV, a value that does not cast, an untyped all-null column, an engine withoutfrom_rowsorto_rows, a body that raises) is PLX115. Both travel as thecodeofunit_test.failed, which carries the diff, and count as errors of the invocation. Exit codes: 0 when every case passed, 1 when one failed, 2 for a usage error, 130 when stopped.
Engine protocol¶
- Plugin API (0, 5) gains
from_rows(rows, schema) -> Relation,to_rows(rel) -> list[dict]andorphans(rel, column, parent, field) -> intonEngineSession. They are additions to 0.5 before 0.9 ships, so a third-party 0.5 engine without them fails only when it is used, with PLX115, mirroring PLX117.pipeloom.engine.portablehas a narwhalsto_rowsand an anti-joinorphansthat polars and pandas reuse;from_rowsuses each engine's own logical-type map (polarspolars_dtype, pandasarrow_type), because a narwhals Decimal cannot carry a precision on every backend.MemoryEnginekeeps plain rows. Spark builds aStructTypefrom its logical-type map forcreateDataFrame, reads timestamps back throughunix_microsso they come out as aware UTC whatever the session time zone, and counts orphans with aleft_antijoin.
Data tests (implemented in the second half of 0.9)¶
data_tests: [{name, check: {not_null | unique | relationships: {column, to: {ref | source}, field}}, on_violation: warn | fail}]is a model key likecolumns. The decorator sets it withdata_tests=(a list ofpipeloom.DataTestobjects or mappings) and properties set it withdata_tests:; the decorator list (or, on the legacy path, the YAML model entry's) replaces the properties list whole. Being a model key, themodels:tree and its root+keyscannot set it, which keeps a relationship next to the model it describes. Diagnostics point at the list that won (ResolvedModel.data_tests_at).PlanNode.data_testsis left out of the manifest when absent; the node checksum and the plan hash cover it only when declared (the ADR-0044 pattern).- A relationships violation is a child row whose non-null
column(NaN counts as null) matches nofieldvalue of the parent; parent nulls never match.tois read like an input, through the runner's read and source specs, so--defer, intermediates and per-model catalogs behave the same; an unreadable parent is PLM204. The judge treatsrelationshipslikeunique: the violation count is the value.toreuses PLR201 and PLR203 for unknown names. - Data tests run inside the unit after the write and the watermark commit and before the attempt file, and also on the replay path, so a retry that replays the write token tests again. They read the whole written table, incremental models included. Tables, incremental, intermediate and view models take them;
data_testson an ephemeral model is PLP415, as is a relationshipstothat names the model itself, a descendant, an ephemeral model, an intermediate model, or that closes a cycle among edges of both kinds (inputs and relationships). An intermediate parent is rejected because its table exists only while a run that builds it is in progress: a run that selects the child alone would fail with PLM204. - Results are entries of
results[].expectationswithscope: "table". From 0.9 every entry carriesscope: batch entries get"batch", filled in when oldcommit_metareplays. The change is additive.warnadds towarnings[]; afailis PLQ303, permanent: the unit fails, its descendants are skipped, the run exits 1, and the data stays written. PLC510 also covers data tests on an engine withoutquality.
build¶
pipeloom buildruns the unit tests of the selected models first; any failure stops it with exit 1 before a run id exists and before any write, andinvocation.completedcounts each failed case as an error (RunOutcome.extra_errors). Then it runsrunwith data tests on. Relationship parents become extra scheduling edges at run time only (UnitGraph.from_parents);runandunit_parent_mapare unchanged.buildtakesrun's user-facing flags.rungets a hidden--data-tests true|falsethat the process executor passes to its children;args.data_testsis recorded inrun_results, andretry --frominherits it.
Non-goals for 0.9¶
- The Airflow and Databricks renderers do not pass
--data-testsyet.pipeloom testdoes not run data tests against existing tables.inittemplates are unchanged.
Since the legacy model path was removed in 0.9 (ADR-0050), cases come only from properties entries of resolved models, so a properties entry for an unknown model is PLR209 and PLR208 covers the case itself (a missing or unknown input alias, a duplicate case name). There are no SQL bodies: a model that calls ctx.sql runs it through the same translate and session.sql path as pipeloom run (point 7).
Consequences¶
- A body is testable on a laptop in milliseconds, on every engine, with the same properties file. A plain pytest call on the decorated function also works. The contract suite runs one passing and one failing case per engine.
- Unit tests never change a manifest or a plan hash, so adding them selects nothing under
state:modified. - Data tests scan the whole written table on every build, incremental models included;
on_violation: warnis available where that is too slow. - Type inference can surprise (a CSV id read as
int64where a string was meant); declaringcolumnson the given is the fix the guide documents. scopeon every expectation entry changes the run_results goldens and event payloads, additively.- Third-party 0.5 engines without the new methods fail only when a test runs.
Status¶
Accepted
Date¶
2026-11-16