Testing data pipelines: unit tests, data tests and data contracts

TL;DR

Difficulty: Advanced

A pipeline can be wrong in four ways, and each needs its own test.

  • Unit tests (pytest, dbt unit tests) prove the logic on small dirty examples, on every change.
  • Data tests (unique, not_null, accepted_values, relationships and your own) check the real data on every run, with severities and thresholds set in advance.
  • Contracts fix the shape at each boundary: marts, incoming files, events from the shop.
  • Reconciliation tests compare totals with the source and find rows that never arrived.
  • Run it all in CI on a pseudonymised base that deliberately holds every known dirty case, never on a copy of production.

A pipeline rarely crashes when it is wrong. It shows a wrong number with the same confidence as a right one. This chapter shows how to test logic, data, shape and completeness so that mistakes are caught before a report goes out, using the same invented homeware shop in Limerick throughout.

The number that was wrong on Monday morning

On Monday 25 January 2027, Niamh opened the weekly report for Shannonside Home, the online homeware shop in Limerick that this series follows. Gross sales for the week of 18 to 24 January read €40,740. That was a good week, about 5% above the one before. Callum, Shannonside's developer and data engineer, had a nagging feeling, because the Stripe and PayPal payouts for the same week did not look 5% better.

He was right to worry. On the Friday before, he had merged a small change: the orders table now carried the amount each order had been paid, taken from the payments table. Most orders have one payment. But 23 orders that week had been paid partly with a gift card and partly by card, so they had two payments. The join produced two rows for each of those orders, and each row carried the full order value. Twenty three orders at €84 each, counted twice, is €1,932 too much. The true figure was €38,808.

Nothing crashed. No error message appeared. The report simply showed a number that was wrong, with the same confidence as a number that was right. And the test that would have caught it is one line long: "order_id must be unique in the orders table". It would have failed in about 40 seconds, on the Friday, before the change ever reached Niamh.

This chapter answers the question behind that Monday: how do I know my pipeline is right before the numbers reach a report? It walks from the basics (what a test is, for code and for data) to the expert end (contracts between teams, reconciliation against the source, continuous integration on pseudonymised data, severity levels that decide what blocks a release). Every idea comes with a worked example on Shannonside's data, and every piece of code is the kind you can adapt and run.

If you are new to the idea of writing tests at all, test driven development explained is the gentle start, and unit, integration and end to end tests explains the layers for application code. This chapter takes both ideas into the world of data, where one thing changes everything: the input is not under your control.

Four questions, four kinds of test

A pipeline can be wrong in four different ways, and each needs its own kind of test. Mixing them up is why many teams have hundreds of tests and still get surprised.

QuestionKind of testWhat it runs onWhen it runs
Is my logic right?Unit testSmall, hand written input rows with a known answerOn every change, before merging
Is today's data right?Data testThe real data, after each buildOn every production run
Is the shape what everyone agreed?ContractColumn names, types, required fieldsBefore a build, and on every change
Does the result agree with the source?Reconciliation testTotals from the warehouse and from the source systemDaily, after the load

A unit test checks your code. You give it a tiny, made up input and state the exact output you expect. If the output differs, your logic is wrong, whatever the real data looks like today.

A data test checks the data. It runs a query on the real table and counts rows that break a rule: duplicates where there should be none, empty values where there must be one, a status nobody has heard of. Your code can be perfect and a data test can still fail, because the source sent something new.

A contract checks the shape. It is an agreement, written down and enforced by a machine, about which columns exist, what type they are and which may never be empty. It protects the people downstream from changes upstream.

A reconciliation test checks completeness against the outside world. It compares a total in the warehouse with the same total in the system the data came from. It catches the rows that never arrived, which no test on the warehouse alone can see.

Example: the Monday bug through each lens. Take the gift card bug from the opening and ask which test would have caught it.

  • A unit test on the orders model, with one order and two payments as input and one row expected as output, fails immediately. It catches the bug before merging, on a laptop, with four rows of made up data.
  • A data test, unique on order_id, fails on the first production run after the merge. It catches the bug before the report is sent, but after the change is live, so the run stops and the dashboard keeps Thursday's numbers.
  • A contract does not catch it. The columns and types were exactly as agreed. The shape was right, the content was wrong.
  • A reconciliation test comparing gross sales with the sum of Stripe and PayPal settlements fails by €1,932. It catches the bug the next morning, and it would have caught it even if nobody had thought of the unique test.

Three of the four would have caught it, at three different moments. That is the whole idea of layered testing: no single kind of test is enough, and the least expensive moment to catch a bug is the earliest one.

Test first works for data, too

Test driven development (TDD) means writing the test before the code: write a test that fails, write the smallest code that makes it pass, then tidy up. I work this way on every Rails and Solidus shop I build, and every release goes through a test gate and into a release register. The same habit works for data, with one adjustment: in data, the "requirement" is usually a dirty example you have already seen.

So the order becomes: find a dirty row, write it down as a test case with the answer you want, watch the test fail, then write the cleaning rule. The dirty row becomes a permanent guard. If anyone later changes the rule and breaks that case, the test says so.

Example: the country rule, test first. Old addresses at Shannonside store the country as free text: "Ireland", "IRL", "Republic of Ireland", "ROI" and more, plus the UK in its own handful of spellings for customers in Belfast and Derry. Callum's goal is the two letter code from ISO 3166, IE or GB.

  1. He profiles the column (the method is in data profiling) and finds 11 distinct spellings for Ireland and six for the United Kingdom.
  2. He writes a test with five of them, one with doubled spaces, one unknown value ("Narnia", which a customer really typed into a test account), and the empty value.
  3. He runs the test. It fails, because the function does not exist yet. This step matters more than it looks: a test you have never seen fail might not be testing anything.
  4. He writes the mapping. The test passes.
  5. Later, a sixth spelling appears ("U.K."). He adds it to the test first, watches it fail, then adds it to the mapping.

The rest of this chapter shows the code for each of these steps.

Unit tests for cleaning code with pytest

Much cleaning happens in Python before data reaches the warehouse: decoding the 3PL file, parsing its dates, mapping SKUs. Python's standard test tool is pytest. A test is a function whose name starts with test_, and an assert statement inside it states what must be true.

The cleaning functions below handle four of the known problems from this series: emails that differ in case or spaces, country as free text, prices stored as floating point numbers by the old platform, and the 3PL's own SKU prefix. The fifth function handles the 3PL's local time stamps, which have no time zone.

# pipelines/cleaning/rules.py
from datetime import datetime, timezone
from decimal import Decimal, ROUND_HALF_UP
from zoneinfo import ZoneInfo

COUNTRY_ALIASES = {
    "ireland": "IE", "irl": "IE", "ie": "IE", "roi": "IE",
    "republic of ireland": "IE",
    "uk": "GB", "united kingdom": "GB", "gb": "GB",
    "northern ireland": "GB",
}

SKU_PREFIXES = ("TPLIE", "TPL")  # longest first


def normalise_email(raw):
    """Lower case and trim an email. Empty strings become None."""
    if raw is None:
        return None
    cleaned = raw.strip().lower()
    return cleaned or None


def normalise_country(raw):
    """Map free text country names to ISO 3166 alpha 2 codes, or None."""
    if raw is None:
        return None
    return COUNTRY_ALIASES.get(" ".join(raw.split()).lower())


def legacy_price_to_cents(value):
    """Convert a float price from the old platform into whole cent."""
    euros = Decimal(repr(value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    return int(euros * 100)


def shop_sku(threepl_sku):
    """Strip the 3PL's prefix: TPLSH10234 and TPLIESH10234 become SH10234."""
    for prefix in SKU_PREFIXES:
        if threepl_sku.startswith(prefix):
            return threepl_sku[len(prefix):]
    raise ValueError(f"unknown 3PL SKU prefix: {threepl_sku!r}")


def local_to_utc(text, zone="Europe/Dublin"):
    """Parse the 3PL's 'dd/mm/yyyy HH:MM' local time and return (utc, flag).

    flag is 'ok', 'ambiguous' (clocks went back, the time happened twice)
    or 'nonexistent' (clocks went forward, the time never happened).
    """
    naive = datetime.strptime(text, "%d/%m/%Y %H:%M")
    tz = ZoneInfo(zone)
    first = naive.replace(tzinfo=tz, fold=0)
    second = naive.replace(tzinfo=tz, fold=1)
    utc = first.astimezone(timezone.utc)
    if first.utcoffset() != second.utcoffset():
        round_trip = utc.astimezone(tz).replace(tzinfo=None)
        flag = "ambiguous" if round_trip == naive else "nonexistent"
    else:
        flag = "ok"
    return utc, flag

Two design choices in this code are themselves the result of tests. shop_sku raises an error for a prefix it does not know, instead of guessing. The spring 2026 story in cleaning pipelines shows what guessing cost: six weeks of unmatched returns. And local_to_utc returns a flag next to the time, because twice a year a local time is not enough to know the moment.

Parametrised tests: one test, many dirty examples

pytest's parametrize marker runs the same test once for each row of a table of inputs and expected outputs1. That suits cleaning perfectly: the table is your collection of dirty examples, and adding a new one is one line.

# pipelines/tests/test_rules.py
from datetime import datetime, timezone

import pytest

from cleaning.rules import (
    legacy_price_to_cents, local_to_utc, normalise_country,
    normalise_email, shop_sku,
)


@pytest.mark.parametrize("raw, expected", [
    ("niamh@example.com", "niamh@example.com"),
    ("  Niamh@Example.COM ", "niamh@example.com"),
    ("\tniamh@example.com\n", "niamh@example.com"),
    ("   ", None),
    (None, None),
])
def test_normalise_email(raw, expected):
    assert normalise_email(raw) == expected


@pytest.mark.parametrize("raw, expected", [
    ("Ireland", "IE"), ("ROI", "IE"), ("irl", "IE"),
    ("  republic   of ireland ", "IE"), ("Northern Ireland", "GB"),
    ("Narnia", None), (None, None),
])
def test_normalise_country(raw, expected):
    assert normalise_country(raw) == expected


@pytest.mark.parametrize("stored, cents", [
    (19.989999771118164, 1999),  # a float32 value read back as float64
    (84.0, 8400),
    (0.1 + 0.2, 30),             # 0.30000000000000004
    (24.995, 2500),              # half a cent rounds up
])
def test_legacy_price_to_cents(stored, cents):
    assert legacy_price_to_cents(stored) == cents


def test_adding_floats_drifts_but_cents_do_not():
    total = 0.0
    for price in [0.1] * 10:     # ten items at 10 cent, added one by one
        total += price
    assert total != 1.0           # 0.9999999999999999
    assert sum(legacy_price_to_cents(p) for p in [0.1] * 10) == 100


@pytest.mark.parametrize("threepl, shop", [
    ("TPLSH10234", "SH10234"), ("TPLIESH10234", "SH10234"),
])
def test_shop_sku(threepl, shop):
    assert shop_sku(threepl) == shop


def test_unknown_prefix_is_refused_not_guessed():
    with pytest.raises(ValueError):
        shop_sku("XYZSH10234")


@pytest.mark.parametrize("local, utc, flag", [
    ("15/01/2026 14:20", datetime(2026, 1, 15, 14, 20, tzinfo=timezone.utc), "ok"),
    ("15/07/2026 14:20", datetime(2026, 7, 15, 13, 20, tzinfo=timezone.utc), "ok"),
    ("29/03/2026 01:30", datetime(2026, 3, 29, 1, 30, tzinfo=timezone.utc), "nonexistent"),
    ("25/10/2026 01:30", datetime(2026, 10, 25, 0, 30, tzinfo=timezone.utc), "ambiguous"),
])
def test_local_to_utc(local, utc, flag):
    assert local_to_utc(local) == (utc, flag)

Running it gives this:

$ pytest -q pipelines/tests
........................                                    [100%]
24 passed in 0.03s

Twenty four test cases from seven test functions, in three hundredths of a second. That speed is the point of unit tests: they are fast enough to run on every save.

Example: the clock change rows from the 3PL

The last test deserves a closer look, because it is where most pipelines are quietly wrong. Under EU law, summer time starts at 1am UTC on the last Sunday of March and ends at 1am UTC on the last Sunday of October2. In Ireland that means the clocks go forward from 1am to 2am in March and back from 2am to 1am in October. In 2026 those days were 29 March and 25 October.

  • On 29 March 2026, the clock jumped from 00:59 to 02:00. A 3PL row stamped "29/03/2026 01:30" describes a time that never happened on a Limerick clock. The warehouse system wrote it anyway (some systems do, when a scanner's clock lags).
  • On 25 October 2026, the clock went from 01:59 back to 01:00. A row stamped "25/10/2026 01:30" happened twice: once at 00:30 UTC, in Irish Standard Time (the summer time), and once at 01:30 UTC, in Greenwich Mean Time.

Python's zoneinfo resolves both with the fold attribute from PEP 495: with fold=0 it uses the offset from before the transition, with fold=1 the offset after it34. The function tries both. If the two offsets agree, the time is ordinary and the flag is ok. If they differ, it converts with fold=0 and back again. If the round trip lands on the same wall clock time, the time existed twice (ambiguous). If it lands somewhere else, the time never existed (nonexistent).

Worked through for the October row: with fold=0, 01:30 is read as Irish summer time, UTC plus one hour, so the UTC time is 00:30. Converted back to Dublin time, 00:30 UTC is 01:30 summer time, the same wall time. So the flag is ambiguous and the pipeline stores 00:30 UTC with that flag. For a shipment, an hour either way changes nothing. For a return that decides whether it falls inside a 30 day return window, the flag tells a person to look.

Worked through for the March row: with fold=0, 01:30 is read with the offset before the jump, UTC plus zero, so the UTC time is 01:30. Converted back, 01:30 UTC is 02:30 summer time, a different wall time. So the flag is nonexistent. Without the test, nobody would know these rows exist, let alone how many there are. At Shannonside there were three in 2026, all scanner clocks lagging behind the change.

Example: why the float test adds one by one

The test test_adding_floats_drifts_but_cents_do_not looks odd: why add with a loop instead of sum()? Because since Python 3.12, sum() on floats uses a more accurate algorithm5, and sum([0.1] * 10) returns exactly 1.0. Adding one by one, the way a naive script or a database aggregate over a float column does, gives 0.99999999999999996. A test written with sum() would pass on a laptop and say nothing about the pipeline. This is a general lesson: test the operation the pipeline really performs, not a tidier one.

For Shannonside the money at stake is small per order and large in total. The legacy table holds about 61,000 orders imported from the old platform, every price a float. Converting each to whole cent once, in the staging model, and testing that conversion, ends a class of one cent mismatches that otherwise appear in every reconciliation forever.

Property based tests: let the computer find the dirty example

A parametrised test only checks the examples you thought of. A property based test states a rule that must hold for every input, and the library generates hundreds of inputs to try to break it. In Python the standard library for this is Hypothesis7.

Good properties for cleaning functions are easy to name. Normalising twice gives the same result as normalising once (idempotence). Every whole cent survives the round trip through a float. No output country code is longer than two letters.

# pipelines/tests/test_properties.py
from hypothesis import given, strategies as st

from cleaning.rules import legacy_price_to_cents, normalise_email


@given(st.text())
def test_normalising_twice_changes_nothing(raw):
    once = normalise_email(raw)
    assert normalise_email(once) == once


@given(st.integers(min_value=0, max_value=10_000_000))
def test_every_whole_cent_survives_the_float_round_trip(cents):
    assert legacy_price_to_cents(cents / 100) == cents

Example: what the second property proves. It tries amounts from €0.00 to €100,000.00 in whole cent, divides each by 100 to make a float (the way the old platform stored it), and checks that the conversion returns the same number of cent. Hypothesis runs 100 examples by default and deliberately favours edge values such as 0, very large numbers and values just above a boundary. If the rounding mode were wrong, it would find the failing amount and report the smallest one. Both properties pass for these functions. The value is not that they pass today. It is that a later "small improvement" to the rounding cannot slip through.

dbt unit tests: logic checks for SQL models

Most of Shannonside's transformations are SQL models in dbt Core. Since dbt 1.8, dbt has its own unit tests: you give a model fixed input rows for each model or source it reads, state the expected output rows, and dbt runs the model's SQL on exactly those inputs8. No real data is touched.

Here is the orders model as it should have been on that Friday. Payments are summed per order first, then joined, so an order with two payments still gives one row.

-- models/marts/fct_orders.sql  (BigQuery)
with payments as (
    select
        order_id,
        sum(case when state = 'completed' then amount else 0 end) as amount_paid,
        count(*) as payment_count
    from {{ ref('stg_solidus__payments') }}
    group by order_id
)

select
    o.order_id,
    o.order_number,
    o.completed_at_utc,
    o.currency,
    o.total_gross,
    coalesce(p.amount_paid, 0) as amount_paid,
    coalesce(p.payment_count, 0) as payment_count
from {{ ref('int_orders__classified') }} as o
left join payments as p
    on p.order_id = o.order_id
where o.order_class = 'sale'

And here is the unit test that pins the gift card case. It lives in a yml file in the models/ folder, not in tests/, which dbt reserves for data tests8.

# models/marts/_fct_orders__unit_tests.yml
unit_tests:
  - name: one_row_per_order_with_split_payments
    description: "An order paid by gift card and card gives one row, not two."
    model: fct_orders
    given:
      - input: ref('int_orders__classified')
        format: dict
        rows:
          - {order_id: 1, order_number: R100000001, currency: EUR, total_gross: 84.00, order_class: sale}
          - {order_id: 2, order_number: R100000002, currency: EUR, total_gross: 84.00, order_class: sale}
          - {order_id: 3, order_number: R100000003, currency: EUR, total_gross: 40.00, order_class: test}
      - input: ref('stg_solidus__payments')
        format: dict
        rows:
          - {order_id: 1, state: completed, amount: 84.00}
          - {order_id: 2, state: completed, amount: 20.00}
          - {order_id: 2, state: completed, amount: 64.00}
          - {order_id: 2, state: failed, amount: 64.00}
          - {order_id: 3, state: completed, amount: 40.00}
    expect:
      format: dict
      rows:
        - {order_id: 1, total_gross: 84.00, amount_paid: 84.00, payment_count: 1}
        - {order_id: 2, total_gross: 84.00, amount_paid: 84.00, payment_count: 3}

Example: reading the unit test row by row

Each input row is there for a reason, and writing the reason down is part of the test.

  • Order 1 is the ordinary case: one completed payment of €84. Expected: one row, €84 paid.
  • Order 2 is the bug: a €20 gift card, a €64 card payment, and one failed card attempt of €64 before it. Expected: one row, €84 paid (20 plus 64, the failed attempt counts zero), and three payment rows counted. The failed attempt guards a second mistake, summing every payment regardless of state, which would give €148.
  • Order 3 is a test order (the classification comes from the business rules in business rule cleaning). Expected: no row at all.

Run against the Friday version of the model, which joined payments without summing, the test returns four rows for orders 1 and 2 instead of two, and dbt prints the difference between expected and actual. Run against the corrected model, it passes. Only the columns that matter to this test appear in the rows. The rest of the model's columns are not compared, which keeps the test readable.

What dbt unit tests can and cannot do

The documentation is clear about the limits, and they shape how you use them8. These are the ones that matter most.

  • They test SQL models only, in your own project. Python models are tested with pytest, as above.
  • Every ref or source the model reads must appear as an input, or compilation fails.
  • Tables in a join must have aliases (as o and p above).
  • On BigQuery, a STRUCT column needs every field in the fixture.
  • Models using materialised views, recursive SQL or introspective queries are not supported.
  • Upstream models must exist in the warehouse, at least as empty tables. dbt run --select ... --empty builds them without reading data.

Two features make unit tests far more useful for real pipelines. First, overrides can set macros, variables and environment variables for the test9. That lets you test an incremental model in both modes, with is_incremental: true and with false. Note what the incremental version tests: the rows the model would insert or merge, not the final table after the merge8. Whether the merge itself works is a question for the test in incremental loading and change data capture that compares incremental with full.

Second, overriding variables removes the most common cause of flaky tests in data: the current date. A model that filters "the last 30 days" with current_date() gives a different answer every day. Write it with a variable instead, and pin the variable in the test.

# models/marts/_fct_returns__unit_tests.yml
unit_tests:
  - name: return_window_uses_the_reporting_date
    model: fct_returns_in_window
    overrides:
      vars:
        reporting_date: "2027-01-31"
      macros:
        is_incremental: false
    given:
      - input: ref('int_returns__matched')
        format: dict
        rows:
          - {return_id: 1, order_completed_on: "2027-01-01", received_on: "2027-01-30"}
          - {return_id: 2, order_completed_on: "2026-12-30", received_on: "2027-01-31"}
    expect:
      format: dict
      rows:
        - {return_id: 1, days_to_return: 29, inside_window: true}
        - {return_id: 2, days_to_return: 32, inside_window: false}

dbt Labs recommends running unit tests only in development and in continuous integration, because their inputs are fixed and running them again in production costs compute and proves nothing new8. In production, dbt build --exclude-resource-type unit_test leaves them out10.

Data tests: checking the real data on every run

Unit tests prove your logic. They cannot prove that today's file from the 3PL is complete, or that a new payment method has appeared. For that you test the data itself, on every production run.

dbt ships four generic data tests: unique, not_null, accepted_values and relationships11. Each one is a query that returns the rows breaking the rule, and the test fails if any rows come back. You attach them to columns in a yml file.

# models/marts/_fct_orders.yml
version: 2

models:
  - name: fct_orders
    description: "One row per completed sale. Test and staff orders excluded."
    columns:
      - name: order_id
        data_tests:
          - unique
          - not_null
      - name: order_number
        data_tests:
          - unique
          - not_null
      - name: currency
        data_tests:
          - accepted_values:
              arguments:
                values: ["EUR"]
      - name: customer_id
        data_tests:
          - relationships:
              arguments:
                to: ref('dim_customers')
                field: customer_id
              config:
                where: "customer_id is not null"
    data_tests:
      - dbt_utils.expression_is_true:
          arguments:
            expression: "abs(amount_paid - total_gross) <= 0.01"
          config:
            severity: error
            warn_if: ">0"
            error_if: ">5"

Three details in this file are easy to get wrong.

  • Since dbt 1.8 the key is data_tests. The older tests still works as an alias, but not both on the same resource11.
  • From dbt 1.10.5, the inputs of a test (the accepted values, the table a relationship points to) go under arguments, and framework settings such as where or severity go under config11. Older projects put the inputs directly under the test name. Write the new form in new code.
  • The relationships test has a where filter because guest checkouts have no customer account. Without it, every guest order would fail the test. Filters like this are legitimate, but each one is a place where a test can go quietly blind, which a later section comes back to.

The model level test comes from the dbt_utils package, which adds generic tests such as expression_is_true, unique_combination_of_columns, accepted_range and equal_rowcount12. Here it checks that what was paid matches the order total within a cent.

A singular test is a SQL file in the tests/ folder that returns the rows you do not want. If it returns zero rows, it passes11. Use it for rules too specific to be generic.

-- tests/assert_no_order_paid_twice_by_the_same_card.sql  (BigQuery)
select
    order_id,
    response_code,
    count(*) as captures
from {{ ref('stg_solidus__payments') }}
where state = 'completed'
group by order_id, response_code
having count(*) > 1

Severity, thresholds and keeping the failing rows

Not every failing test should stop the pipeline. dbt gives each test a severity of error (the default) or warn, and two thresholds, warn_if and error_if, compared against the number of failing rows. Both default to !=013. With severity: error, dbt checks error_if first, then warn_if.

So the model level test above behaves like this: zero mismatched orders, pass. One to five, a warning: the run continues and the warning is logged. Six or more, an error.

And an error has a consequence in dbt build: tests on a model block everything downstream of it, which is skipped entirely14. That is exactly what you want for money. A broken orders table must not flow into the revenue mart, the customer lifetime value model and the ad platforms' conversion uploads. The dashboards keep yesterday's numbers, which are old but right.

Finally, store_failures: true makes dbt save the failing rows of a test to a table, by default in a schema ending in _dbt_test__audit, replaced on each run15. When a test fails at 6am, the first question is "which rows?", and the answer is already waiting.

Example: the Monday bug, as a data test

Rerun the week of 18 to 24 January with these tests in place. The production build on Friday night builds fct_orders from the faulty model. The unique test on order_id runs straight after and returns 23 rows, one per duplicated order (dbt's unique test groups by the column and returns each value that appears more than once). Severity is error, so dbt marks the test as failed and skips every model downstream: the weekly revenue mart, the customer marts, the export to Google Ads. Callum gets an alert. Niamh's report on Monday shows the week up to Thursday, with a note that Friday's build failed. The wrong €40,740 is never shown to anyone.

That is better than the real Monday, but it is still a production incident. The unit test from the previous section catches the same bug on Friday afternoon, before merging. That difference is the argument for having both.

Thresholds from rates: when is a failure count worth an alarm?

Some rules are broken by a small, steady share of rows, and that is normal. About 2% of Shannonside's orders have a missing or invalid phone number. A test that fails on any invalid phone fails every day and teaches everyone to ignore it. The threshold should sit where an ordinary day almost never crosses it, and a broken checkout always does.

A count of rare, independent events in a fixed period is well described by a Poisson distribution. See Foundations: distributions and Foundations: probability.

P(X≥k)=1−∑j=0k−1e−λ λjj!,λ=p⋅nP(X \ge k) = 1 - \sum_{j=0}^{k-1} \frac{e^{-\lambda}\,\lambda^{j}}{j!}, \qquad \lambda = p \cdot n

where XX is the number of orders with an invalid phone on one day, kk is the threshold being tested, λ\lambda is the expected number per day, pp is the usual share of invalid phones and nn is the number of orders per day.

Example: setting the phone threshold

Shannonside takes 1,980 orders a month, about n=66n = 66 a day. With p=0.02p = 0.02, the expected count is λ=0.02×66=1.32\lambda = 0.02 \times 66 = 1.32. So an ordinary day has between one and two invalid phones. Now the chance that an ordinary day reaches a given count:

Threshold kkP(X≥k)P(X \ge k) on an ordinary dayOrdinary days a year above it
314.8%about 54
44.5%about 16
51.1%about 4
60.24%about 1

Worked through for k=5k = 5: e−1.32=0.267e^{-1.32} = 0.267. The terms for j=0j = 0 to 4 are 0.2670.267, 0.3530.353, 0.2330.233, 0.1020.102 and 0.0340.034, which add up to 0.9890.989. So P(X≥5)=1−0.989=0.011P(X \ge 5) = 1 - 0.989 = 0.011, about 1.1%, or four false alarms a year.

Callum sets warn_if: ">4" (five or more) on yesterday's orders, using a where filter on the order date, and no error threshold, because a missing phone number delays a courier call but does not make a revenue figure wrong. When the checkout change of August 2026 made the phone field optional (the story in data quality dimensions), the share of orders without a usable phone rose from about 2% to about 10%. That moves the expected count to λ=0.10×66=6.6\lambda = 0.10 \times 66 = 6.6 a day, and the chance of five or more on a given day to about 79%. The warning fires on most days of the first week instead of four times a year, which is exactly the change in behaviour a threshold is for.

Every cleaning rule gets a test with a dirty example

A cleaning rule without a test is a rule that will drift. Somebody changes the regular expression, adds a new country alias in the wrong case, or "simplifies" the time zone handling, and the rule quietly stops doing its job. The discipline is simple: every rule in the rule register (the list of cleaning and business rules introduced in business rule cleaning) has at least one unit test built from a real dirty example, and at least one data test that watches how often the rule fires on real data.

The second half is the one teams forget. A unit test proves the rule does what you meant. A data test on the rule's output proves the rule still matters and has not started catching far more, or far fewer, rows than it used to.

Example: Shannonside's known problems, each with its tests. Here are the nine known data problems of the shop, and how each is guarded.

Known problemUnit test (dirty example)Data test on real data
3.1% duplicate customer accountsSame email with capitals and a trailing space, and a guest checkout plus an account, merge into one customerunique on the normalised email in dim_customers, plus the share of merged accounts per month between 2% and 4.5%
About 40 test and staff orders a yearEach rule in the register (test payment method, staff email, internal flag) classifies its example correctlyOrders classified as test or staff below 1% of orders per month
3PL SKU prefixTPLSH10234 and TPLIESH10234 map to SH10234, an unknown prefix is refusedrelationships from mapped SKU to dim_products, failing rows quarantined
Late 3PL returns, up to 5 daysA return received 5 days after shipment joins the right orderReturns arriving more than 7 days late: warn
GA4 about 15% below the shopNot a cleaning rule: the gap is explained, not removedGA4 purchases between 78% and 92% of shop orders per day
Float prices in legacy orders19.989999771118164 becomes 1,999 centSum of line items equals order item total in cent for every legacy order
3PL local time without zoneOrdinary, ambiguous and nonexistent times at both clock changesCount of nonexistent flags above zero: warn
Country as free text11 spellings of Ireland, six of the UK, "Narnia" and emptyNo address with an unmapped country after staging
About 2% missing or invalid phone numbersLeading zero, +353, spaces, letters, emptyFive or more on one day: warn (the threshold above)

Notice the GA4 row. Not every known problem is cleaned. The gap between analytics and the shop is expected, caused by consent and blockers, and when analytics, ads and orders disagree explains why it should be explained, not removed. The test still exists. It checks that the gap stays inside its usual band, because a sudden change in the gap means the tracking broke, not that customers changed.

Contracts: the shape everyone agreed on

Tests check rows. Contracts check the promise about the table itself: which columns exist, what type each one has, which may never be empty. A contract matters most at a boundary, where the person who changes something is not the person who depends on it. Shannonside has three such boundaries: between Callum's models and the reports and tools that read them, between outside suppliers (the 3PL, the supplier feeds) and Callum's pipeline, and between the Rails shop that sends events and the pipeline that receives them.

dbt model contracts: the shape of a mart, enforced

In dbt, setting contract: enforced: true on a model makes the column names and data types part of its definition. Before building, dbt checks that the model's query returns exactly those columns with those types (column order does not matter), and refuses to build if not. It also writes the types and constraints into the table definition16.

# models/marts/_fct_orders.yml (continued)
models:
  - name: fct_orders
    config:
      contract:
        enforced: true
    columns:
      - name: order_id
        data_type: int64
        constraints:
          - type: not_null
          - type: primary_key
            warn_unenforced: false
      - name: order_number
        data_type: string
        constraints:
          - type: not_null
      - name: completed_at_utc
        data_type: timestamp
      - name: currency
        data_type: string
      - name: total_gross
        data_type: numeric
      - name: amount_paid
        data_type: numeric
      - name: payment_count
        data_type: int64

A contract checks shape, not content, and the constraint support depends on the warehouse. This is the part most people get wrong:

ConstraintBigQueryPostgreSQL
not nulldefined and enforceddefined and enforced
primary keydefined, not enforceddefined and enforced
foreign keydefined, not enforceddefined and enforced
uniquenot supporteddefined and enforced
checknot supporteddefined and enforced

Source: dbt's model contracts documentation16 and PostgreSQL's constraints documentation17.

On BigQuery, a primary key in a contract is a hint for the query planner, not a guard. Duplicates still get in. So on BigQuery the contract and the unique data test do different jobs, and you need both. On PostgreSQL, the database itself refuses a duplicate key, which is a stronger guarantee, at the cost of a failed insert rather than a failed test. For a smaller shop that runs its whole warehouse on PostgreSQL, this is one of the honest advantages.

Contracts also guard against breaking changes over time. When dbt compares the project with a previous state, removing a column, changing a column's type or removing a constraint from a contracted model raises an error16. If a change is truly needed, dbt's model versions let you publish fct_orders version 2 next to version 1 and give the people downstream time to move.

Example: the column Callum wanted to rename

In February, Callum wants to rename total_gross to order_total_incl_vat, because new colleagues keep asking whether "gross" includes VAT. In his pull request, the build fails with a contract error: the model no longer returns total_gross, and the yml still promises it. Without the contract, the build would have succeeded and three things would have broken quietly the next morning: Niamh's revenue dashboard, the export of conversion values to Google Ads and the finance spreadsheet that reads the mart through a connector.

He does it properly instead. Version 2 of fct_orders gets the new name. Version 1 stays, built from the same logic, with a deprecation date three months out. The dashboard moves to version 2 in the same week, the ads export a fortnight later, the spreadsheet when finance next touches it. On the deprecation date, version 1 is removed, and by then nothing reads it.

Contracts for incoming files

The most fragile boundary is the one with outside suppliers, because you cannot run their tests and they will not run yours. The 3PL changes its file without notice. A supplier switches from centimetres to millimetres. So the contract sits on your side of the boundary, on the raw table, and checks every delivery before anything is built from it.

Great Expectations, now called GX Core, and Soda are two widely used open source tools for this. GX Core is a Python library in which you define expectations, such as ExpectColumnValuesToBeBetween, group them into suites and run them through checkpoints18. Soda Core in its current version works with data contracts written in YAML: checks per dataset and per column, with thresholds19. Both do the job. dbt's own source tests do it too, if all your checks can be written as SQL. Choose by where your team already writes code.

Here is the 3PL contract for Shannonside in Soda's contract language, checked against the raw table after each load:

# contracts/raw_3pl_movements.yml  (Soda contract)
dataset: shannonside_bq/shannonside_data/raw_3pl/movements

checks:
  - schema:
  - row_count:

columns:
  - name: movement_row_id
    checks:
      - missing:
      - duplicate:
  - name: movement_type
    checks:
      - invalid:
          valid_values: ["SHIP", "RETURN"]
  - name: sku
    checks:
      - missing:
  - name: order_reference
    checks:
      - missing:
          threshold:
            metric: percent
            must_be_less_than: 1
  - name: movement_local_time
    checks:
      - missing:

The schema check fails if columns appear, disappear or change type. row_count fails on an empty table, which is what a failed delivery usually looks like. missing and duplicate with no threshold mean none allowed. On order_reference, a small share of missing values is tolerated (manual stock corrections have none), expressed as a percentage.

Example: the morning the 3PL added a column

On 3 February 2027 the 3PL's file arrives with a twelfth column, carrier_service, inserted in the middle, not at the end. A loader that reads columns by position would now put carrier names into the quantity column. Shannonside's loader reads by header name, so the raw table simply gains a column. The contract's schema check fails at 6.10am: one unexpected column. The build of the returns models does not start. Callum reads the alert, sees a harmless addition, adds the column to the contract and the staging model, and reruns. The returns dashboard is 50 minutes late that morning and right. The alternative, which the cost of dirty data describes in several real cases, is a dashboard that is on time and wrong.

Contracts for events: the shop as producer

The third boundary runs between the Rails shop and the pipeline. When an order completes, Shannonside's shop sends a purchase event from the server (the reasons are in the shop database as the source of truth). The pipeline depends on that event's fields. So the contract should be tested where the event is made, in the shop's own test suite, before a developer can ship a change that breaks it.

The contract is a JSON Schema file kept in the shop's repository:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://shannonsidehome.example/contracts/events/purchase.v1.json",
  "type": "object",
  "required": ["event_name", "event_id", "order_number", "occurred_at", "currency", "value", "tax", "items"],
  "additionalProperties": false,
  "properties": {
    "event_name": { "const": "purchase" },
    "event_id": { "type": "string", "minLength": 1 },
    "order_number": { "type": "string", "pattern": "^R[0-9]{9}$" },
    "occurred_at": { "type": "string", "format": "date-time" },
    "currency": { "enum": ["EUR"] },
    "value": { "type": "number", "minimum": 0 },
    "tax": { "type": "number", "minimum": 0 },
    "items": {
      "type": "array",
      "minItems": 1,
      "items": {
        "type": "object",
        "required": ["sku", "quantity", "price"],
        "properties": {
          "sku": { "type": "string" },
          "quantity": { "type": "integer", "minimum": 1 },
          "price": { "type": "number", "minimum": 0 }
        }
      }
    }
  }
}

And the test in the Rails app uses the json_schemer gem, which validates the current JSON Schema drafts and returns each error with a readable message20. Here is the test:

# test/contracts/purchase_event_contract_test.rb
require "test_helper"

class PurchaseEventContractTest < ActiveSupport::TestCase
  SCHEMA = JSONSchemer.schema(Rails.root.join("contracts/events/purchase.v1.json"))

  test "a completed order's purchase event matches contract v1" do
    order = build_completed_order(number: "R100000002", total: 84.00, tax: 15.71)

    payload = PurchaseEvent.new(order).as_json
    errors = SCHEMA.validate(payload).map { |error| error["error"] }

    assert_empty errors, "purchase event breaks contract v1:\n#{errors.join("\n")}"
  end
end

PurchaseEvent and build_completed_order are the shop's own code (an event builder and a test helper), so this test runs in milliseconds with the rest of the Rails suite. A developer who renames value to revenue sees the test fail, with a message naming the missing property and the unexpected one, before merging.

When events flow through a message broker such as Apache Kafka instead of straight into the warehouse, the same idea is built into the infrastructure as a schema registry. Confluent's Schema Registry checks each new version of a schema against the previous one under a compatibility mode. The default, BACKWARD, allows deleting fields and adding optional fields, and means consumers must be upgraded before producers start sending the new form. FORWARD and FULL and their transitive variants set other rules, and NONE switches the checks off21. A small shop that loads events directly into its warehouse does not need a registry. The JSON Schema test in the shop gives the same protection at a fraction of the moving parts.

Data contracts as agreements between people

The term "data contract" has grown beyond schemas. In a 2026 article on Martin Fowler's site, Simon Harrer and Arif Wider describe data contracts as "a way to describe the contents and guarantees of datasets", whose simplest form is a description of the shape of the data a provider offers22. A full contract adds what the shape cannot say: who owns the data, what each field means, how fresh it will be, which quality checks it passes, and how changes are announced. The Open Data Contract Standard (ODCS), an open specification maintained by the Bitol project under the Linux Foundation, gives that agreement a standard YAML structure23.

For a business the size of Shannonside, the useful part is not the format. It is the conversation. Callum wrote a one page contract for each of the three boundaries: the 3PL file (owner at the 3PL, delivery by 6am, columns, the SKU prefix list, notice period for changes, who to call), the purchase event (owner: Callum as shop developer, consumer: Callum as data engineer, which is a fine thing to write down even when it is one person) and the revenue mart (owner: Callum, consumers: Niamh, the accountant, the ad exports). The machine readable checks above enforce the parts that can be checked. The page records the parts that need a human, such as "the 3PL gives ten working days' notice of any file change", which turns the next surprise column into a breach of an agreement rather than a shrug.

Reconciliation tests: does the warehouse agree with the source?

Every test so far looks at data that arrived. None of them can see data that did not. A pipeline that loses three orders produces a table in which every remaining row is unique, complete, valid and correctly typed. Only a comparison with the source shows the gap.

A reconciliation test counts and sums the same thing in two places and compares. Reporting on cleaned data builds the full revenue bridge from shop to report. Here the goal is narrower: an automated check, after every load, that fails loudly.

The comparison is usually expressed as a relative difference. See Foundations: ratios and rates.

δ=∣W−S∣S\delta = \frac{\lvert W - S \rvert}{S}

where δ\delta is the relative difference, WW is the total in the warehouse and SS is the same total in the source system.

The tolerance depends on what is compared. For orders on a day that is closed (all orders committed, no more can arrive), the tolerance for counts is zero. For money, a cent per order for rounding. For data that is known to differ, such as GA4, a band.

The check must compare like with like. The warehouse's fct_orders excludes test and staff orders, the shop does not. So the check compares the source with the layer before the business rules, or adds the excluded rows back. And the day must have the same boundaries on both sides: an Irish day, midnight to midnight in Limerick, converted to UTC, because the shop stores UTC.

# pipelines/checks/reconcile_orders.py
import datetime as dt
import sys
from zoneinfo import ZoneInfo

import psycopg
from google.cloud import bigquery

DUBLIN = ZoneInfo("Europe/Dublin")

SOURCE_SQL = """
    select count(*), coalesce(sum(total), 0)
    from spree_orders
    where state = 'complete'
      and completed_at >= %(start)s and completed_at < %(end)s
"""

WAREHOUSE_SQL = """
    select count(*), coalesce(sum(total_gross), 0)
    from `shannonside-data.intermediate.int_orders__classified`
    where order_class in ('sale', 'test', 'staff')
      and completed_at_utc >= @start and completed_at_utc < @end
"""


def irish_day_in_utc(day):
    start = dt.datetime.combine(day, dt.time(0), tzinfo=DUBLIN)
    end = dt.datetime.combine(day + dt.timedelta(days=1), dt.time(0), tzinfo=DUBLIN)
    return start.astimezone(dt.timezone.utc), end.astimezone(dt.timezone.utc)


def main(day, source_dsn):
    start, end = irish_day_in_utc(day)

    with psycopg.connect(source_dsn) as conn:
        s_count, s_sum = conn.execute(SOURCE_SQL, {"start": start, "end": end}).fetchone()

    client = bigquery.Client()
    job = client.query(WAREHOUSE_SQL, job_config=bigquery.QueryJobConfig(
        query_parameters=[
            bigquery.ScalarQueryParameter("start", "TIMESTAMP", start),
            bigquery.ScalarQueryParameter("end", "TIMESTAMP", end),
        ]))
    w_count, w_sum = list(job.result())[0].values()

    problems = []
    if w_count != s_count:
        problems.append(f"orders: shop {s_count}, warehouse {w_count}")
    if abs(w_sum - s_sum) > 0.01 * s_count:
        problems.append(f"gross: shop {s_sum:.2f}, warehouse {w_sum:.2f}")

    if problems:
        print(f"{day}: reconciliation FAILED: " + "; ".join(problems))
        return 1
    print(f"{day}: {s_count} orders, €{s_sum:.2f}, shop and warehouse agree")
    return 0


if __name__ == "__main__":
    sys.exit(main(dt.date.fromisoformat(sys.argv[1]), sys.argv[2]))

The source query runs against a read replica of the shop database, never the live primary, so a slow check cannot slow down the checkout. The script exits with a non zero status when the totals disagree, which is what an orchestrator (the subject of orchestration) needs to mark the task as failed and raise the alert.

Example: three orders missing on 26 January

On the morning of 27 January the check for 26 January prints:

2027-01-26: reconciliation FAILED: orders: shop 66, warehouse 63; gross: shop 5544.00, warehouse 5292.00

Worked through: the warehouse is missing 66−63=366 - 63 = 3 orders and €5,544.00−€5,292.00=€252.00€5{,}544.00 - €5{,}292.00 = €252.00, which is exactly three orders at the average of €84. The relative difference on revenue is δ=∣5,292−5,544∣/5,544=252/5,544=0.045\delta = \lvert 5{,}292 - 5{,}544 \rvert / 5{,}544 = 252 / 5{,}544 = 0.045, so 4.5%, on a measure whose tolerance is effectively zero. Every data test on fct_orders had passed: the 63 rows were perfect. Callum lists the three missing order numbers by comparing order numbers instead of totals, and finds that all three completed between 23:59:58 and 00:00:01 while a slow stock import held a database transaction open. Their rows committed after the incremental load had moved its high watermark past them, the first trap in incremental loading and change data capture. The fix there is a lookback window. The lesson here is that only a reconciliation test could see it.

Continuous integration: every change tested before it merges

Continuous integration (CI) means that every proposed change to the code is built and tested automatically, before it is merged into the main version. For application code this is standard practice. For data pipelines it is less common, and the reason is practical: the tests need a warehouse and data to run against, and the real data is large, costly to query and full of personal information.

The answer has three parts: build only what changed, build it in a separate place that cleans itself up, and build it on data that is safe to use.

Build only what changed. dbt can compare the current project with the saved state of a previous run (its manifest.json file) and select only new or modified models, plus everything downstream of them, with state:modified+. Unmodified parents are not rebuilt. With --defer, references to them resolve to the tables of that previous run instead2425. dbt's own best practice guide calls this "slim CI"24.

Build in a separate, short lived place. Each pull request gets its own BigQuery dataset, created with a default table expiration so that it deletes its tables by itself. In bq, --default_table_expiration takes seconds, so 86,400 is one day26.

Build on safe data. This is where many setups go wrong, and the next section explains how to get it right. The short version: defer to a pseudonymised CI base, not to production.

# .github/workflows/dbt-ci.yml
name: dbt ci
on:
  pull_request:
    paths: ["dbt/**", "pipelines/**"]

jobs:
  test:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write
    env:
      CI_DATASET: ci_pr_${{ github.event.number }}
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt

      - name: Python unit tests
        run: pytest -q pipelines/tests

      - uses: google-github-actions/auth@v3
        with:
          workload_identity_provider: ${{ vars.GCP_WIF_PROVIDER }}
          service_account: ${{ vars.GCP_CI_SERVICE_ACCOUNT }}
      - uses: google-github-actions/setup-gcloud@v3

      - name: Dataset for this pull request, deletes its tables after one day
        run: bq --location=EU mk --force -d --default_table_expiration 86400 "shannonside-ci:${CI_DATASET}"

      - name: State of the nightly CI base build
        run: gcloud storage cp gs://shannonside-dbt-artifacts/ci-base/manifest.json ci-base-state/manifest.json

      - name: Build and test what changed, on pseudonymised data
        working-directory: dbt
        run: |
          dbt deps
          dbt build --target ci --select "state:modified+" --defer --state ../ci-base-state

The job authenticates to Google Cloud with workload identity federation through Google's auth action27, so no long lived key sits in the repository. The ci target in dbt's profile writes to the dataset named in CI_DATASET, and its service account can read only the CI datasets, never production.

Example: Callum's pull request on 2 February. Callum changes int_orders__classified to add a new staff email rule. On push, the workflow starts:

  1. 128 Python unit tests: 4 seconds.
  2. dbt selects state:modified+: the changed model and the 11 models downstream of it. Everything else is deferred to the CI base.
  3. dbt builds those 12 models on the CI data and runs their 9 unit tests and 74 data tests in lineage order: unit tests first, then the model, then its data tests8.
  4. One data test fails: the share of orders classified as staff jumped from 0.2% to 3.4% in the CI data. The new rule matched every email at shannonsidehome.example, including customers who had used the shop's own newsletter alias for gift orders. The pull request is marked red.
  5. Callum narrows the rule to the staff list, pushes again, and the run passes in 3 minutes 40 seconds.

The bug never reached the main branch. Nobody had to remember to check.

Sampling for CI: will the bug be in the sample?

CI data is usually a sample, because the full history is too large to rebuild on every change. A random sample has a catch: rare problems may not be in it. If a problem affects a share pp of rows and the sample has nn rows drawn at random, the chance that at least one affected row is in the sample is:

P(at least one)=1−(1−p)nP(\text{at least one}) = 1 - (1 - p)^{n}

where pp is the share of rows with the problem and nn is the number of rows in the sample. Solved for nn, the sample size that finds at least one affected row with probability cc is n=ln⁡(1−c)/ln⁡(1−p)n = \ln(1 - c) / \ln(1 - p). See Foundations: probability and Foundations: sampling.

Example: test orders in a random sample

Shannonside has about 40 test and staff orders in 23,760 orders a year, so p=40/23,760=0.00168p = 40 / 23{,}760 = 0.00168.

  • A sample of n=500n = 500 orders: 1−(1−0.00168)500=1−0.431=0.5691 - (1 - 0.00168)^{500} = 1 - 0.431 = 0.569. A 57% chance of containing even one test order.
  • A sample of n=2,000n = 2{,}000: 1−0.034=0.9661 - 0.034 = 0.966, about 97%.
  • For a 95% chance: n=ln⁡(0.05)/ln⁡(1−0.00168)=−2.996/−0.00168=1,778n = \ln(0.05) / \ln(1 - 0.00168) = -2.996 / -0.00168 = 1{,}778 orders.

Compare duplicate customers, at p=0.031p = 0.031: a random sample of only 100 accounts contains at least one duplicate with probability 1−0.969100=0.9571 - 0.969^{100} = 0.957, about 96%.

So a random sample finds common problems easily and rare ones by luck. The conclusion is not "use a bigger sample". It is: build the CI dataset from a random sample plus every known dirty case, deliberately. Shannonside's CI base holds 2,000 random orders from the last year, plus all test and staff orders, all orders with split payments, all legacy float priced orders from one month, every 3PL row flagged ambiguous or nonexistent, and the accounts involved in a sample of 200 duplicate pairs. Rare cases are put in on purpose, because the tests that need them must not depend on luck.

Test data and privacy: never copy production as it is

The easiest way to get realistic CI data is to copy production. It is also the way that most often goes wrong. A copy of production in a test environment is still personal data: names, emails, addresses, phone numbers, order histories. Copying it is processing under data protection law, and test environments are usually less protected than production: more people have access, logs keep more, and copies multiply.

In Ireland, the GDPR applies directly, alongside the Data Protection Act 2018, and its principles apply to every copy: purpose limitation, data minimisation, and integrity and confidentiality (Article 5)28. Article 25 requires data protection by design and by default, and Article 32 names pseudonymisation and encryption among the appropriate security measures2930. The Data Protection Commission (DPC) is clear that data which can still be linked back to a person with additional information is pseudonymised rather than anonymised, and is still personal data31. This is general information, not legal advice. For a specific setup, ask a data protection specialist.

Three options, from safest to most realistic:

OptionWhat it isPersonal data?Good for
Synthetic dataMade up rows that follow the schema and the known patternsNo, if generated from scratchLocal development, unit test fixtures, demos
Pseudonymised sampleReal rows with identifiers replaced by keyed hashes or fake valuesYes, for whoever holds the keyCI on realistic distributions
Production copyReal rows as they areYes, fullyAlmost never, and only with a documented reason and the same protection as production

For synthetic data, the Python library Faker generates realistic names, addresses and emails for many locales, and can be seeded so that the same seed gives the same data on every run32. Its safe_email() method produces addresses at example domains that can never reach a real inbox.

For a pseudonymised sample, the trick is to keep the patterns the tests need while removing the identities. Shannonside's duplicates are emails that differ only in case and spaces. A naive replacement (a random fake email per row) destroys exactly that pattern, and the duplicate tests then test nothing. A keyed hash of the normalised email keeps it: the same person gets the same pseudonym, and the case and spacing of the original can be reproduced on top.

-- Builds the CI base's customer table from production (BigQuery)
-- Run by a separate service account that can read production and write ci_base only.
create or replace table `shannonside-ci.ci_base.spree_users`
options (expiration_timestamp = timestamp_add(current_timestamp(), interval 8 day))
as
with hashed as (
    select
        u.id,
        u.created_at,
        u.email as original_email,
        to_hex(sha256(concat(@pseudonym_key, lower(trim(u.email))))) as h
    from `shannonside-data.raw_solidus.spree_users` as u
    where u.id in (select user_id from `shannonside-ci.ci_base.sample_user_ids`)
)
select
    id,
    created_at,
    concat(
        if(original_email != trim(original_email), ' ', ''),
        if(trim(original_email) != lower(trim(original_email)), 'User', 'user'),
        substr(h, 1, 12),
        '@example.com'
    ) as email
from hashed

The key, @pseudonym_key, is a secret kept outside the CI project. Without it, nobody in CI can turn a pseudonym back into an email by hashing guesses. Names, street addresses and phone numbers are replaced with Faker values in the same build, phones keeping their pattern of validity (an invalid phone stays invalid, in a different invalid way) so that the phone tests still have something to find.

Example: what the CI base contains, and what it does not

Shannonside's CI base is rebuilt every night from the sample described in the previous section. It contains 2,000 sampled orders plus the deliberately added dirty cases, about 2,900 orders in all, with their line items, payments, refunds and the matching 3PL rows. Emails are keyed hashes in the shape User3fa9c0d1e2b4@example.com, with a leading space where the original had one. Names and addresses are Faker values. Order amounts, dates, SKUs and states are real, because the tests need them and they identify nobody once the customer is pseudonymised.

It does not contain any free text field from customer service tickets or order notes, because free text is where people write things like "please leave with Margaret at number 12", which no hash removes. It lives in the EU region like production, only the CI service account and Callum can read it, and every table expires after eight days, so a forgotten copy cannot linger. And it is still treated as personal data, because Callum holds the key.

The test pyramid for data

For application code, the test pyramid is the classic picture: many fast unit tests at the bottom, fewer integration tests in the middle, a handful of slow end to end tests at the top. Martin Fowler traces the idea to Mike Cohn's 2009 book "Succeeding with Agile", and the reasoning is cost: tests near the bottom are fast, precise and inexpensive to keep, tests near the top are slow and brittle33.

Data pipelines need the same balance for code tests, and one more layer that application code does not have: tests on the production data itself, every run. These do not fit the pyramid, because they are not about how much of your code is covered. They are about the data changing under you.

Bar chart of the number of tests by kind in the invented Shannonside Home pipeline: 128 Python unit tests, 52 dbt unit tests, 14 contracts, 307 data tests, 6 reconciliation checks and 2 end to end checks. Data tests on real data are the largest group, unlike the classic test pyramid for application code. Tap or click to open full screen and move around

Example: Shannonside's test inventory, layer by layer.

LayerCountRuntimeRuns whereCatches
Python unit tests (pytest)1284 secondsLaptop, CIWrong logic in extractors and cleaning functions
dbt unit tests52about 90 secondsLaptop, CIWrong logic in SQL models
Contracts (11 marts, 3 sources)14checked during the buildCI, productionBroken shape, at boundaries
Data tests (286 generic, 21 singular)307about 6 minutesCI, production every runBad data, broken rules, surprises from sources
Reconciliation checks6about 1 minuteProduction dailyMissing or extra data compared with the source
End to end checks225 minutesWeeklyA full rebuild on the CI base equals the incremental build, and the monthly bridge closes

Read the counts as two pyramids side by side. The code pyramid (unit tests, then contracts, then end to end) has the classic shape: 180 unit tests, 14 contracts, 2 end to end checks. The data tests form their own wide layer, because every important column of every important table gets a few quick checks, and they run against reality every night.

Where the bugs were caught in the last 12 months tells the same story in another way.

Bar chart for the invented Shannonside Home pipeline showing where 31 data bugs in one year were first caught: 17 by tests in continuous integration before merging, 9 by data tests in production, 3 by reconciliation checks and 2 by a person reading a report. Tap or click to open full screen and move around

The 17 caught in CI cost minutes each. The 9 caught by production data tests cost a late dashboard. The 3 caught by reconciliation were invisible to every other test. The 2 that reached a person are the ones to study: each led to a new test, so the same bug cannot reach a person twice.

Severity: what blocks a release, what warns, what quarantines

A test that fails needs a consequence decided in advance, not at 6am by whoever is awake. Three consequences cover almost everything.

  • Block. The change cannot merge (in CI), or the downstream models do not build (in production). Reports keep the last good data. For anything that touches money, legal duties or a decision made from the data today.
  • Quarantine. The rows that break the rule are set aside with a reason, the rest flows on, and the report carries a note. The quarantine pattern is in cleaning pipelines. For problems confined to identifiable rows, such as an unknown SKU in the 3PL file.
  • Warn. The run continues, the warning is counted and reviewed on a fixed day. For quality signals that do not make a number wrong, such as missing phone numbers.
Tap or click to open full screen and move around

How strict to be depends on what the data feeds. Quality tiers for business critical software sets out the reasoning for software, and it carries over: the revenue mart that feeds the accounts and the ad platforms sits in a higher tier than the table behind an internal product popularity chart. Write the tier into the model's metadata, and let it decide the default severity of its tests.

A release of pipeline code is a release like any other. It goes through the test gate, and an entry in the release register records what changed, which tests ran and who approved it. Evidencing compliance shows what such a register holds. For a data pipeline, the useful extras are the list of models rebuilt and any test whose threshold changed, because a loosened threshold is a decision, not a technicality.

Example: one Tuesday's failures, sorted. The production build on Tuesday 9 February reports three failures.

  1. relationships from mapped 3PL SKU to products: 4 rows. The 3PL shipped a new product before it was set up in the shop. The rows can be isolated and the reason is clear: quarantine. The returns dashboard publishes with a note, "4 shipment lines of 9 February awaiting product setup".
  2. Phone validity on yesterday's orders: 5 invalid, against a threshold of five or more. Warn. It goes on Monday's review list. Per the threshold table, this happens about four times a year by chance.
  3. unique on order_id in fct_orders: 0 rows, but expression_is_true on amount paid against order total: 7 rows, above error_if: ">5". That touches revenue and cannot be isolated with confidence, so it blocks. The revenue mart and the ad exports do not build. Callum finds that a PayPal settlement arrived with a changed currency field. Fixed and rebuilt by 9.40am.

Tests that lie: flaky, hollow and blind

A test suite can be green and wrong. Three failure modes cause most of it, and each has a simple countermeasure.

Flaky tests pass and fail on the same code. In data, the causes are nearly always the current date (the window moves), row order (a query without order by returns rows in any order, and a test that takes "the first row" gets a different one) and timing (a test runs before the late data it checks has arrived). Pin the date with a variable, compare sets instead of ordered lists, and schedule checks after the data's known arrival time. A test that is flaky is worse than no test, because it teaches people to rerun until green.

Hollow tests cannot fail. The classic: a where filter that excludes every row, so the test checks nothing and passes forever. Or a threshold set so high that no realistic failure crosses it. The countermeasure is the step from the test first section: see every test fail at least once. For data tests, the CI base's deliberately dirty rows are what make that possible: each important test should have at least one row in the CI base that it is supposed to catch.

Blind spots are what no test looks at: the source that stops sending, the column nobody declared, the table that is complete but a day old. Some are covered by reconciliation, some by contracts. The rest is the territory of monitoring, which a later chapter in this series covers: tests check what you know can go wrong, monitoring notices what you did not think of.

Example: the test that passed for six months. Shannonside had a data test that no order in fct_orders was completed in the future, filtered with where: "completed_at_utc > current_timestamp()". Callum adds the "see it fail" step to his review checklist and inserts a test row into the CI base with a completion date in 2030. The test still passes. The reason: a staging model drops rows with completion dates more than a day ahead, so no such row ever reached fct_orders. The test was guarding a door that was already bricked up. He moves it to the staging model, where future dates actually arrive, and it fails on the planted row, as it should. In production it then finds 11 legacy orders with a completion date in 2036, a typo in the old platform's import ten years ago, which had been silently dropped from every report since the migration.

A testing plan for a shop of this size

Everything above can sound like a lot. Here is the order in which I would introduce it for a shop like Shannonside, each step useful on its own.

  1. Week 1: generic data tests on the marts. unique and not_null on every primary key, relationships on every foreign key, accepted_values on every status column. An afternoon's work, and it would have caught the Monday bug.
  2. Week 1: one reconciliation check. Orders and gross revenue per Irish day, warehouse against the shop's read replica. The script above, scheduled after the load.
  3. Week 2: severity and thresholds. Every test gets an explicit severity. Money blocks, rows that can be isolated are quarantined, quality signals warn with thresholds derived from their usual rate.
  4. Week 2: unit tests for every cleaning rule. One pytest or dbt unit test per rule in the register, each built from a real dirty example, each seen to fail first.
  5. Week 3: contracts at the boundaries. Model contracts on the marts that tools read, a contract check on the 3PL file and supplier feeds, the JSON Schema test for the purchase event in the shop.
  6. Week 4: CI on a pseudonymised base. The nightly CI base with its deliberate dirty cases, slim CI on every pull request, the production manifest never used for deferral.
  7. Ongoing: every bug becomes a test. When something reaches a person, the fix is not complete until a test would have caught it.

Conclusion

A pipeline is right when four things are true: the logic does what you meant, today's data obeys the rules, the shape is what everyone agreed, and the result agrees with the source. Each needs its own test. Unit tests, in pytest and in dbt, prove the logic on small dirty examples, fast enough to run on every change. Data tests check the real data on every run, with severities and thresholds that decide in advance what blocks, what quarantines and what only warns. Contracts protect the boundaries between the shop, the suppliers and the people who read the marts. Reconciliation tests see the rows that never arrived, which nothing else can.

Run all of it in continuous integration on a pseudonymised base that deliberately contains every known dirty case, never on a copy of production. Make every test fail once before you trust it. And turn every bug that reaches a person into a test, so that the next Monday morning starts with the right number.

If your reports have ever been wrong without any error to warn you, book the free workshop: we map the four kinds of test your pipeline needs and where they belong, and the first two weeks of work are on me.

Sources

  1. 1.

    pytest, How to parametrize fixtures and test functions, pytest documentation, https://docs.pytest.org/en/stable/how-to/parametrize.html

  2. 2.

    European Parliament and Council, Directive 2000/84/EC on summer time arrangements, Official Journal of the European Union, 2001, https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32000L0084

  3. 3.

    Python Software Foundation, zoneinfo: IANA time zone support (ambiguous and imaginary times, the fold attribute), Python documentation, https://docs.python.org/3/library/zoneinfo.html

  4. 4.

    Alexander Belopolsky and Tim Peters, PEP 495: Local Time Disambiguation, Python Enhancement Proposals, 2015, https://peps.python.org/pep-0495/

  5. 5.

    Python Software Foundation, Built in functions: sum (changed in version 3.12, summation of floats switched to a more accurate algorithm), Python documentation, https://docs.python.org/3/library/functions.html

  6. 6.

    Python Software Foundation, Floating point arithmetic: issues and limitations, Python tutorial, https://docs.python.org/3/tutorial/floatingpoint.html

  7. 7.

    Hypothesis, Quickstart, Hypothesis documentation, https://hypothesis.readthedocs.io/en/latest/quickstart.html

  8. 8.

    dbt Labs, Unit tests, dbt Developer Hub, https://docs.getdbt.com/docs/build/unit-tests

  9. 9.

    dbt Labs, Unit testing properties (given, expect, overrides), dbt Developer Hub, https://docs.getdbt.com/reference/resource-properties/unit-tests

  10. 10.

    dbt Labs, Resource type (exclude all unit tests), dbt Developer Hub, https://docs.getdbt.com/reference/global-configs/resource-type

  11. 11.

    dbt Labs, Add data tests to your DAG, dbt Developer Hub, https://docs.getdbt.com/docs/build/data-tests

  12. 12.

    dbt Labs, dbt utils package (generic tests: expression_is_true, unique_combination_of_columns, accepted_range, equal_rowcount), GitHub, https://github.com/dbt-labs/dbt-utils

  13. 13.

    dbt Labs, severity, error_if and warn_if, dbt Developer Hub, https://docs.getdbt.com/reference/resource-configs/severity

  14. 14.

    dbt Labs, About dbt build command, dbt Developer Hub, https://docs.getdbt.com/reference/commands/build

  15. 15.

    dbt Labs, store_failures, dbt Developer Hub, https://docs.getdbt.com/reference/resource-configs/store_failures

  16. 16.

    dbt Labs, Model contracts, dbt Developer Hub, https://docs.getdbt.com/docs/mesh/govern/model-contracts

  17. 17.

    PostgreSQL Global Development Group, Constraints, PostgreSQL documentation (current version), https://www.postgresql.org/docs/current/ddl-constraints.html

  18. 18.

    Great Expectations, Try GX Core, GX Core documentation, https://docs.greatexpectations.io/docs/core/introduction/try_gx

  19. 19.

    Soda, Contract language reference, Soda documentation, https://docs.soda.io/reference/contract-language-reference

  20. 20.

    David Harsha, json_schemer, README, GitHub, https://github.com/davishmcclurg/json_schemer

  21. 21.

    Confluent, Schema evolution and compatibility for Schema Registry, Confluent documentation, https://docs.confluent.io/platform/current/schema-registry/fundamentals/schema-evolution.html

  22. 22.

    Simon Harrer and Arif Wider, Data Contracts, martinfowler.com, 18 November 2026, https://martinfowler.com/articles/data-contracts.html

  23. 23.

    Bitol, Open Data Contract Standard (ODCS), GitHub, https://github.com/bitol-io/open-data-contract-standard

  24. 24.

    dbt Labs, Best practices for workflows (run only modified models to test changes, slim CI), dbt Developer Hub, https://docs.getdbt.com/best-practices/best-practice-workflows

  25. 25.

    dbt Labs, Defer, dbt Developer Hub, https://docs.getdbt.com/reference/node-selection/defer

  26. 26.

    Google Cloud, Create datasets (default table expiration), BigQuery documentation, https://docs.cloud.google.com/bigquery/docs/datasets

  27. 27.

    Google, Authenticate to Google Cloud from GitHub Actions (google-github-actions/auth), GitHub, https://github.com/google-github-actions/auth

  28. 28.

    European Parliament and Council, Regulation (EU) 2016/679 (General Data Protection Regulation), Article 5, Official Journal of the European Union, 2016, https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679

  29. 29.

    European Parliament and Council, Regulation (EU) 2016/679 (General Data Protection Regulation), Article 25 (Data protection by design and by default), Official Journal of the European Union, 2016, https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679

  30. 30.

    European Parliament and Council, Regulation (EU) 2016/679 (General Data Protection Regulation), Article 32 (Security of processing), Official Journal of the European Union, 2016, https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679

  31. 31.

    Data Protection Commission, Anonymisation and pseudonymisation, DPC guidance, https://www.dataprotection.ie/dpc-guidance/anonymisation-pseudonymisation

  32. 32.

    Faker, Welcome to Faker's documentation (locales and seeding), Faker documentation, https://faker.readthedocs.io/en/master/

  33. 33.

    Martin Fowler, Test Pyramid, martinfowler.com, 1 May 2012, https://martinfowler.com/bliki/TestPyramid.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.