Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 2

Lab: Declarative Checks on Raw and Modeled Data

Gate a partner file at ingestion with Great Expectations, then test the sources and models with dbt: schema, not-null, unique, accepted values, relationships, a distribution check against a baseline, freshness and volume, with warn and error severities and stored failures. A deliberately broken batch shows which checks catch what.

Contentsand lesson path

What you will learn

  • Implement schema, constraint, referential and distribution checks with a framework (dbt tests, Great Expectations or Soda) at ingestion and after transformation.

01. Goal and setup

A partner sends a file of orders every morning. In this lab you check that data twice. At ingestion, before the file is loaded, a Great Expectations suite checks what the file alone can tell you: its columns, its size and the values in each row. After transformation, dbt tests check what needs the warehouse: uniqueness across days, references to other tables, the distribution of values compared with history, and freshness. Then a file with five planted problems arrives: which check catches each?

The lab was tested with Python 3.12, Great Expectations (GX Core) 1.25.0, dbt Core 1.12.7, dbt-duckdb 1.11.1 and DuckDB 1.5.6. DuckDB plays the warehouse. It assumes you know dbt sources, models and dbt build from the dbt sources lab, and the quality dimensions from the previous lesson. Save requirements.txt in dq-checks after the first command below.

Text · requirements.txt
dbt-core==1.12.7
dbt-duckdb==1.11.1
duckdb==1.5.6
great-expectations==1.25.0
Terminal
mkdir dq-checks && cd dq-checks
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
mkdir -p models tests
Folder layout at the end of the lab
dq-checks/
├── requirements.txt, make_feed.py   step 1
├── dbt_project.yml, profiles.yml    step 2
├── models/  sources.yml, models.yml, stg_orders.sql, stg_customers.sql,
│            fct_daily_sales.sql
├── tests/   zero_share_vs_baseline.sql
├── results.py                       step 2: reads dbt's result files
├── ingest.py                        step 4: the ingestion gate
└── show_failures.py                 step 7

02. Step 1: Create a week of history and the new files

make_feed.py plays the role of the past week. It creates raw.orders with seven days of 50 orders each, as if they had been loaded at 06:00 UTC on the following mornings, and raw.customers with 40 customers. It then writes two versions of the file for 3 November into incoming/. The comments show what is wrong with them; predict which check catches each problem.

Python · make_feed.py
"""Create a week of loaded orders and two versions of the next day's partner file."""
import csv
import random
from datetime import date, datetime, timedelta
from pathlib import Path

import duckdb

rng = random.Random(42)
STATUSES = ["placed", "shipped", "shipped", "shipped", "cancelled"]


def day_rows(day, first_id, n):
    start = datetime(day.year, day.month, day.day, 8)
    return [[first_id + i, rng.randint(1, 40), rng.choice(STATUSES),
             round(rng.uniform(5, 120), 2), str(start + timedelta(minutes=13 * i))]
            for i in range(n)]


con = duckdb.connect("warehouse.duckdb")
con.execute("CREATE SCHEMA IF NOT EXISTS raw")
con.execute("CREATE OR REPLACE TABLE raw.customers AS SELECT range + 1 AS customer_id,"
            " 'customer ' || (range + 1) AS name FROM range(40)")
con.execute("""CREATE OR REPLACE TABLE raw.orders (
    order_id INTEGER, customer_id INTEGER, status VARCHAR, amount DECIMAL(9, 2),
    ordered_at TIMESTAMP, _file VARCHAR, _loaded_at TIMESTAMP)""")
next_id = 1000
for offset in range(7):                   # 27 Oct to 2 Nov, each loaded at 06:00 UTC
    day = date(2026, 10, 27) + timedelta(days=offset)
    rows = day_rows(day, next_id, 50)
    next_id += 50
    if offset == 3:
        rows[0][3] = 0.00                 # one free order in the week: a normal share
    loaded = datetime(day.year, day.month, day.day, 6) + timedelta(days=1)
    con.executemany("INSERT INTO raw.orders VALUES (?, ?, ?, ?, ?, ?, ?)",
                    [r + [f"orders_{day}.csv", loaded] for r in rows])

new = day_rows(date(2026, 11, 3), next_id, 60)
for row in new[:3]:
    row[2] = "on_hold"                    # a status the contract does not list
for i, row in enumerate(new[3:7]):
    row[0] = next_id - 4 + i              # four orders of 2 November sent again
for row in new[7:12]:
    row[1] = 999                          # a customer that does not exist
for row in new[12:32]:
    row[3] = 0.00                         # a third of the amounts are zero
Path("incoming").mkdir(exist_ok=True)
header = ["order_id", "customer_id", "status", "amount", "ordered_at"]
for name, cols in [("orders_2026-11-03_v1.csv", header[:3] + ["amount_eur", header[4]]),
                   ("orders_2026-11-03_v2.csv", header)]:
    with open(f"incoming/{name}", "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(cols)
        writer.writerows(new)
files, rows = con.execute(
    "SELECT count(DISTINCT _file), count(*) FROM raw.orders").fetchone()
print(f"raw.orders: {rows} rows from {files} daily files; raw.customers: 40 rows")
print("incoming:", ", ".join(sorted(p.name for p in Path("incoming").iterdir())))
Terminal
python make_feed.py
Expected output
raw.orders: 350 rows from 7 daily files; raw.customers: 40 rows
incoming: orders_2026-11-03_v1.csv, orders_2026-11-03_v2.csv

03. Step 2: Declare the dbt checks and build the history

The dbt project has three models: stg_orders and stg_customers clean the raw tables, and fct_daily_sales sums revenue per day. The staging models are views over the raw tables; the mart is a table. +store_failures: true in dbt_project.yml tells dbt to save the failing rows of every test in a table, so you can read them later.

YAML · dbt_project.yml
name: shop_quality
version: "1.0.0"
profile: shop_quality

models:
  shop_quality:
    +materialized: view
    fct_daily_sales:
      +materialized: table      # the mart keeps its last good build

data_tests:
  shop_quality:
    +store_failures: true      # keep the failing rows of every test in a table
YAML · profiles.yml
shop_quality:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: warehouse.duckdb
      schema: main
      threads: 1
SQL · models/stg_orders.sql
select
    order_id,
    customer_id,
    status,
    amount,
    ordered_at,
    cast(ordered_at as date) as order_date,
    _file as source_file
from {{ source('raw', 'orders') }}
SQL · models/stg_customers.sql
select customer_id, name from {{ source('raw', 'customers') }}
SQL · models/fct_daily_sales.sql
select
    order_date,
    count(*) as orders,
    sum(amount) as revenue
from {{ ref('stg_orders') }}
where status <> 'cancelled'
group by order_date

Tests on a source run on the raw table as it was loaded. Here they check the keys, and the source also declares freshness: how old the newest _loaded_at may be before dbt warns (26 hours) or reports an error (50 hours). freshness moved under config: in dbt 1.9, and loaded_at_field in 1.10.

YAML · models/sources.yml
sources:
  - name: raw
    schema: raw
    tables:
      - name: orders
        config:
          loaded_at_field: _loaded_at
          freshness:
            warn_after: {count: 26, period: hour}
            error_after: {count: 50, period: hour}
        columns:
          - name: order_id
            data_tests: [not_null]
      - name: customers
        columns:
          - name: customer_id
            data_tests: [unique, not_null]

Tests on models check the transformed data. unique and not_null protect the key. relationships checks referential integrity: every customer_id in stg_orders must exist in stg_customers. accepted_values lists the statuses the business has agreed on. Generic tests take their inputs under arguments:, which dbt has supported since 1.10.5 and plans to require in a future version. name: keeps the test names short.

Each test also has a severity. By default a test fails with an error as soon as it returns one row. The status test is set to severity: warn, so an unknown status is reported but does not fail the run. The relationships test uses thresholds instead: warn_if: ">0" and error_if: ">10" mean a few orphan orders give a warning, while more than ten give an error.

YAML · models/models.yml
models:
  - name: stg_orders
    columns:
      - name: order_id
        data_tests: [unique, not_null]
      - name: customer_id
        data_tests:
          - relationships:
              name: stg_orders_customer_exists
              arguments:
                to: ref('stg_customers')
                field: customer_id
              config:
                warn_if: ">0"
                error_if: ">10"
      - name: status
        data_tests:
          - accepted_values:
              name: stg_orders_status_known
              arguments:
                values: [placed, shipped, cancelled]
              config:
                severity: warn
  - name: fct_daily_sales
    columns:
      - name: order_date
        data_tests: [unique]

No generic test compares today with history, so the distribution check is a singular test: a SQL file in tests/ that returns the rows that break the rule. If it returns no rows, it passes.

SQL · tests/zero_share_vs_baseline.sql
-- Distribution check: the share of zero amounts on the newest day must stay within
-- 5 percentage points of its average over the seven days before.
with daily as (
    select order_date, avg(case when amount = 0 then 1.0 else 0.0 end) as zero_share
    from {{ ref('stg_orders') }}
    group by order_date
),
newest as (
    select * from daily order by order_date desc limit 1
),
baseline as (
    select avg(zero_share) as zero_share
    from daily
    where order_date between (select order_date from newest) - 7
                         and (select order_date from newest) - 1
)
select
    newest.order_date,
    round(newest.zero_share, 3) as zero_share,
    round(baseline.zero_share, 3) as baseline_share
from newest, baseline
where newest.zero_share > baseline.zero_share + 0.05

dbt build prints timings that change on every run, so results.py reads dbt's result file instead and prints each node's status, the number of failing rows for tests, and its name.

Python · results.py
"""Print status, failure count and name of each node of a dbt result file."""
import json
import sys

path = sys.argv[1] if len(sys.argv) > 1 else "target/run_results.json"
with open(path) as f:
    run = json.load(f)
for result in run["results"]:
    parts = result["unique_id"].split(".")
    kind = parts[0]
    name = ".".join(parts[2:4]) if kind == "source" else parts[2]
    failures = result.get("failures")
    count = "" if failures is None else str(failures)
    print(f"{result['status']:<7} {kind:<6} {count:>3}  {name}")
Terminal
dbt build --quiet
python results.py
Expected output
pass    test     0  source_not_null_raw_customers_customer_id
pass    test     0  source_not_null_raw_orders_order_id
pass    test     0  source_unique_raw_customers_customer_id
success model       stg_orders
success model       stg_customers
pass    test     0  not_null_stg_orders_order_id
pass    test     0  stg_orders_status_known
pass    test     0  unique_stg_orders_order_id
pass    test     0  zero_share_vs_baseline
pass    test     0  stg_orders_customer_exists
success model       fct_daily_sales
pass    test     0  unique_fct_daily_sales_order_date

Every check passes on the week of history: no duplicates, no orphans, and the one free order on 30 October is within the baseline.

04. Step 3: Check freshness

dbt build does not check freshness; dbt source freshness does, and it writes target/sources.json. Run it now, before anything new has arrived.

Terminal
dbt source freshness --quiet > freshness.log
python results.py target/sources.json
Expected output
error   source      raw.orders

The newest row was loaded at 06:00 UTC on 3 November, more than 50 hours before you ran the command, so freshness is an error. The tests in step 2 all passed on data that was days old: only a freshness check notices that nothing new has come in. dbt's own message, with clock times, is in freshness.log.

05. Step 4: Gate the first file at ingestion

ingest.py validates one file with GX Core. An Expectation is one verifiable assertion, such as "order_id is never null", and an Expectation Suite groups them. A Data Source, Data Asset and Batch Definition tell GX where the data is; here the batch is a whole pandas DataFrame, passed in at run time. A Validation Definition pairs the suite with the batch and runs it. The ephemeral context writes no project folder.

The suite is a contract for the file: a schema check on the exact column list, a volume check of 30 to 80 rows, and row-level checks. Every Expectation has a severity: critical by default, or warning or info. The script loads the file only if no critical Expectation failed.

Python · ingest.py
"""Ingestion gate: validate one partner file with Great Expectations, then load it."""
import sys
from pathlib import Path

import duckdb
import great_expectations as gx
import great_expectations.expectations as gxe
import pandas as pd
from great_expectations.data_context.types.base import ProgressBarsConfig

path = Path(sys.argv[1])
df = pd.read_csv(path)

context = gx.get_context(mode="ephemeral")   # keep nothing on disk for this lab
context.variables.progress_bars = ProgressBarsConfig(globally=False)
batch_def = (context.data_sources.add_pandas("partner")
             .add_dataframe_asset("orders_file")
             .add_batch_definition_whole_dataframe("whole_file"))
suite = context.suites.add(gx.ExpectationSuite(name="orders_file_contract"))
for expectation in [
    gxe.ExpectTableColumnsToMatchOrderedList(
        column_list=["order_id", "customer_id", "status", "amount", "ordered_at"]),
    gxe.ExpectTableRowCountToBeBetween(min_value=30, max_value=80),
    gxe.ExpectColumnValuesToNotBeNull(column="order_id"),
    gxe.ExpectColumnValuesToBeUnique(column="order_id"),
    gxe.ExpectColumnValuesToBeBetween(column="amount", min_value=0, max_value=5000),
    gxe.ExpectColumnValuesToBeInSet(column="status", severity="warning",
                                    value_set=["placed", "shipped", "cancelled"]),
]:
    suite.add_expectation(expectation)
validation = context.validation_definitions.add(
    gx.ValidationDefinition(name="gate", data=batch_def, suite=suite))
result = validation.run(batch_parameters={"dataframe": df})

blocking = 0
for r in sorted(result.results, key=lambda r: r.expectation_config.type):
    cfg = r.expectation_config
    severity = cfg.severity.value           # critical (the default), warning or info
    target = cfg.kwargs.get("column", "table")
    bad = r.result.get("unexpected_count", "")
    status = "pass" if r.success else "FAIL"
    print(f"{status:<4}  {severity:<8}  {cfg.type:<43} {target:<8} {bad}")
    blocking += (not r.success) and severity == "critical"
if blocking:
    print(f"BLOCKED: {path.name} not loaded ({blocking} critical failures)")
    sys.exit(1)
con = duckdb.connect("warehouse.duckdb")
con.execute("INSERT INTO raw.orders"
            " SELECT *, ?, current_timestamp AT TIME ZONE 'UTC' FROM df", [path.name])
print(f"LOADED: {len(df)} rows from {path.name}")
Terminal
python ingest.py incoming/orders_2026-11-03_v1.csv
echo "exit code: $?"
Expected output
FAIL  critical  expect_column_values_to_be_between          amount   
FAIL  warning   expect_column_values_to_be_in_set           status   3
pass  critical  expect_column_values_to_be_unique           order_id 0
pass  critical  expect_column_values_to_not_be_null         order_id 0
FAIL  critical  expect_table_columns_to_match_ordered_list  table    
pass  critical  expect_table_row_count_to_be_between        table    
BLOCKED: orders_2026-11-03_v1.csv not loaded (2 critical failures)
exit code: 1

The partner renamed amount to amount_eur. The schema check fails, and the range check on amount fails as well, because it cannot find its column: GX records an Expectation that could not run as a critical failure, so a check that never ran is not mistaken for a pass. The script exits with code 1 and loads nothing, which is what an orchestrator needs to stop the pipeline. Without this gate, the file would have failed later in stg_orders, with a less helpful error.

06. Step 5: Load the corrected file

The partner resends the file with the right header. Run the gate on it, then check freshness again.

Terminal
python ingest.py incoming/orders_2026-11-03_v2.csv
dbt source freshness --quiet > freshness.log
python results.py target/sources.json
Expected output
pass  critical  expect_column_values_to_be_between          amount   0
FAIL  warning   expect_column_values_to_be_in_set           status   3
pass  critical  expect_column_values_to_be_unique           order_id 0
pass  critical  expect_column_values_to_not_be_null         order_id 0
pass  critical  expect_table_columns_to_match_ordered_list  table    
pass  critical  expect_table_row_count_to_be_between        table    
LOADED: 60 rows from orders_2026-11-03_v2.csv
pass    source      raw.orders

Three rows have the status on_hold, which the contract does not list. That check has severity="warning", so the file loads and the warning goes to the data owner. Freshness passes now, because the new rows carry the current time in _loaded_at. On its own, the file looks fine; the other problems need more context.

07. Step 6: Test after transformation

Terminal
dbt build --quiet --no-use-colors > build.log
echo "exit code: $?"
python results.py
grep -A1 "\[ERROR\]" build.log | cut -c 11-
Expected output
exit code: 1
pass    test     0  source_not_null_raw_customers_customer_id
pass    test     0  source_not_null_raw_orders_order_id
pass    test     0  source_unique_raw_customers_customer_id
success model       stg_orders
success model       stg_customers
pass    test     0  not_null_stg_orders_order_id
warn    test     1  stg_orders_status_known
fail    test     4  unique_stg_orders_order_id
fail    test     1  zero_share_vs_baseline
warn    test     5  stg_orders_customer_exists
skipped model       fct_daily_sales
skipped test        unique_fct_daily_sales_order_date
[ERROR]: in test unique_stg_orders_order_id (models/models.yml)
  Got 4 results, configured to fail if != 0
[ERROR]: in test zero_share_vs_baseline (tests/zero_share_vs_baseline.sql)
  Got 1 result, configured to fail if != 0

Three problems show up that the file alone could not reveal, and step 5's status warning returns:

  • unique_stg_orders_order_id fails with 4 rows. The four ids are unique inside the file, so the GX uniqueness check passed, but they were already loaded on 2 November.
  • stg_orders_customer_exists finds 5 orphan orders. That is above warn_if and below error_if, so it warns.
  • stg_orders_status_known warns with 1 row: an accepted_values test returns one row per unexpected value, and on_hold is one value.
  • zero_share_vs_baseline fails: every amount is a valid number, but a third of them are zero.

Because a test on stg_orders failed, dbt skipped fct_daily_sales and its test, so the mart table kept its last good build. This works because the mart is a table; a view would show the new raw rows at once. A failing test skips a model only if everything the test reads is upstream of that model. unique_stg_orders_order_id and zero_share_vs_baseline read only stg_orders, so they gate the mart; stg_orders_customer_exists also reads stg_customers, so even an error from it would only set the exit code. The errors set the exit code to 1, so a scheduler or CI job stops here; warnings alone leave it at 0 unless you run dbt build --warn-error.

08. Step 7: Read the stored failures

A failing test tells you how many rows fail. With store_failures, dbt also saved which rows, in the schema main_dbt_test__audit (your target schema with the suffix _dbt_test__audit). Join them back to the data to find the cause.

Python · show_failures.py
"""Read the rows that two failing tests stored, thanks to store_failures."""
import duckdb

con = duckdb.connect("warehouse.duckdb", read_only=True)
print(con.sql("""
    SELECT f.unique_field AS order_id, f.n_records,
           list(o.source_file ORDER BY o.source_file) AS files
    FROM main_dbt_test__audit.unique_stg_orders_order_id AS f
    JOIN main.stg_orders AS o ON o.order_id = f.unique_field
    GROUP BY ALL ORDER BY order_id"""))
print(con.sql("SELECT * FROM main_dbt_test__audit.zero_share_vs_baseline"))
Terminal
python show_failures.py
Expected output
┌──────────┬───────────┬───────────────────────────────────────────────────┐
│ order_id │ n_records │                       files                       │
│  int32   │   int64   │                     varchar[]                     │
├──────────┼───────────┼───────────────────────────────────────────────────┤
│     1346 │         2 │ [orders_2026-11-02.csv, orders_2026-11-03_v2.csv] │
│     1347 │         2 │ [orders_2026-11-02.csv, orders_2026-11-03_v2.csv] │
│     1348 │         2 │ [orders_2026-11-02.csv, orders_2026-11-03_v2.csv] │
│     1349 │         2 │ [orders_2026-11-02.csv, orders_2026-11-03_v2.csv] │
└──────────┴───────────┴───────────────────────────────────────────────────┘

┌────────────┬────────────┬────────────────┐
│ order_date │ zero_share │ baseline_share │
│    date    │   double   │     double     │
├────────────┼────────────┼────────────────┤
│ 2026-11-03 │      0.333 │          0.003 │
└────────────┴────────────┴────────────────┘

Each duplicate id is in both yesterday's and today's file, which points at the partner's export. Ask the partner for a file without the resent orders and the zero amounts, and the data owner whether on_hold is a valid new status. Lesson 4 holds such a batch back automatically.

The same checks exist in other tools. Soda Core 4, for example, writes them as a YAML data contract with missing, invalid, duplicate, row_count and freshness checks. The ideas carry over: put each check where its inputs exist, and give it a severity.

09. Check your understanding

Practice check · 3 questions

Where each check belongs

Each question changes one detail of the lab.

Q1. Tomorrow's file contains 12 orders whose `customer_id` is not in `stg_customers`, and nothing else is wrong. What does `dbt build` report for `stg_orders_customer_exists`, and what happens to `fct_daily_sales`?
Q2. Why did the GX uniqueness check on `order_id` pass for `orders_2026-11-03_v2.csv`, while dbt's `unique` test on `stg_orders` failed?
Q3. A team schedules only `dbt build` every hour. The partner stops sending files for three days. What do the tests in this project report?
Practice only: not graded, not saved, not evidence.

10. Apply it

For the skill practice, turn the checks you listed in lesson 1 into code on your own pipeline:

  • Write an ingestion suite for one source with at least a schema, a volume and two row-level Expectations, and give each one a severity.
  • Add dbt tests on the models for uniqueness, a relationship and one distribution check against a baseline, and choose warn_if/error_if values you can justify to the data owner.
  • Schedule dbt source freshness separately from dbt build, and decide who receives its warnings.

11. Review prompt

Without looking back, explain which checks belong at ingestion and which after transformation, and why. Then explain how dbt evaluates severity, warn_if and error_if, what store_failures adds, which failing tests skip downstream models, and why freshness needs its own command.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check