Platform Engineering · Lesson 321

MLOps Data Quality and Data Contracts

A model is only as good as the rows it learned from, and most model incidents start upstream, in data nobody on the ML team owns. A data contract is a written, versioned agreement between the team that produces a dataset and the teams that consume it: the schema, the meaning and unit of every field, how fresh and complete it will be, and who to call. Data quality checks enforce it in the pipeline: schema, nulls, ranges, freshness, volume, and the distribution of values. This lesson follows one day of events from the producer to a training run, and shows the two failures that checks on types alone never catch: a field that changes its unit, and a day that arrives half-full.

Difficulty: Advanced · Know this first: Lesson 311, Lesson 198

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from the producer's change to a training run on checked data. It is a worked example, not a measurement. The freshness, volume, and distribution hops are where wrong data either stops or gets through.

Try it: which check catches the bad data?

Pick what went wrong upstream and which checks the pipeline runs. A check catches a problem only if it looks at the right thing and is allowed to block.

not caughtcaught by
trained on bad datatraining

Not caught

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Data quality grows in four levels: reading a validation report, writing contracts and checks, versioning and quarantining, and running contracts across an organisation.

Basic — Read a validation report

At the basic level you can read what the checks found and say whether the data is fit to train on.

  • Row counts against the expected band; null rates per field; quarantined rows by reason.
  • Freshness: when the partition landed against when it was promised.
  • Which checks passed, which warned, which blocked.

Where it breaks: reading "all checks passed" without asking which checks exist.

Try it: Basic

Every check is green, but the model got worse after retraining. What do you ask first?

Now do it: List your pipeline's checks and mark which look at values, not just types.

Intermediate — Write the contract and the checks

At the intermediate level you write the contract with the producer and turn it into checks.

  • A contract file with type, unit, nullability, allowed values, volume band, freshness, owner, and the compatibility rule.
  • Row checks (schema, ranges, uniqueness) with a quarantine table; dataset checks (volume, freshness) that block.
  • Thresholds from history: the same hour last week, not a number someone guessed.

Try it: Intermediate

Where should the contract check for a breaking schema change run first?

Now do it: Add a contract test to one producer's pipeline.

Advanced — Version, quarantine, and trace

At the advanced level every dataset a model sees is a version with its checks attached.

  • Immutable versions (Delta, Iceberg, Hudi, lakeFS, or DVC); training logs the version with the run.
  • Distribution checks (PSI, KS) on the fields that matter most to the model.
  • Lineage events (OpenLineage) from every job, so "what did this model learn from" is a query.

Try it: Advanced

A model misbehaves. How do you find the upstream change fastest?

Now do it: Emit lineage from one training job and follow it back.

Master — Contracts across the organisation

At the master level data contracts are how teams depend on each other.

  • Every dataset a model depends on has a contract, an owner, an SLO (freshness, completeness), and an on-call.
  • Breaking changes go through versions and deprecation windows, like APIs.
  • Quality incidents get postmortems; the fix includes the check that would have caught it.

Trade-off: contracts slow producers down a little and stop the worst class of silent model failures.

Try it: Master

A producer must rename a field many models use. What is the contract-first way?

Now do it: Write the deprecation plan for one field.

Go deeper

A data contract does not need special tools to start: a reviewed file in the producer's repository is enough. This one is in a neutral format; the Open Data Contract Standard (ODCS) and tools such as datacontract-cli define similar fields, so check their current specification before you adopt one.

# contracts/checkout_events.yaml — owned by the checkout team
name: checkout_events
version: 3.0.0                 # major: breaking change, minor: compatible addition
owner: team-checkout           # who answers when it breaks
on_call: checkout-primary
delivery:
  partition: hourly            # dt=YYYY-MM-DD/hour=HH
  freshness_minutes: 20        # partition complete within 20 minutes of the hour
  rows_per_partition: {min: 90000, max: 140000}
compatibility: backward        # adding optional fields is allowed; nothing else is
fields:
  - {name: order_id,    type: string,  required: true, unique: true}
  - {name: amount,      type: decimal, required: true, unit: USD dollars, min: 0, max: 50000}
  - {name: currency,    type: string,  required: true, allowed: [USD]}
  - {name: country,     type: string,  required: true, null_rate_max: 0.0}
  - {name: coupon_code, type: string,  required: false, since: 3.0.0}
quality:
  - {check: psi, field: amount, reference_days: 28, block_over: 0.25}
  - {check: share, field: country, reference_days: 28, block_over: 0.10}

The checks that matter, and what each one catches:

Where they run: row and dataset checks in the pipeline (Great Expectations, Soda, dbt tests, Deequ, or your own SQL), contract checks in the producer's CI, and lineage events from every job. The tool matters less than two rules: the important checks block, and every dataset version carries its results.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A unit changed, and every check said the data was fine.

Timeline

  • Day 0, 14:00The checkout team refactors its event code and starts sending amount in cents. The field is still a number; their tests pass.
  • Day 0, 23:00The nightly fraud model retrains on the day's data. Schema, null, and range checks pass: 4,599 is a valid amount.
  • Day 1, 08:00The new model is promoted. Manual-review rate rises from 0.4% to 9% of orders.
  • Day 2, 10:00The review team escalates. Lineage leads from the model to the dataset to the producer's refactor within minutes of someone looking.
  • Day 2, 12:30The model is rolled back to the previous version; the two days of data are re-cut with a conversion.

What changed after

The contract now names the unit of every numeric field, the producer's CI compares a sample of real output with the contract, a PSI check on the five fields the model depends on most blocks training, and model promotion waits for a business metric (review rate) to stay inside its band on a canary.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A virtual environment for Python packages: python3 -m venv ~/mlops && . ~/mlops/bin/activate. Then pip install dvc pandas pyarrow for the versioning steps, and Git.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Make a project with Git and DVC, the way a training repository starts.

    mkdir -p ~/labs/contracts && cd ~/labs/contracts
    git init -q && dvc init -q
    git status --short

    Options: -q keeps both quiet; dvc init adds a .dvc/ folder that Git tracks.

    Expect: A short list of new files under .dvc/, ready to commit.

    Clean up: rm -rf ~/labs/contracts removes the whole lab.

  2. Write a small day of events and track it as a dataset version.

    python3 -c "import pandas as pd; pd.DataFrame({'order_id':['a1','a2','a3'],'amount':[45.99,12.50,230.00]}).to_parquet('events.parquet')"
    dvc add events.parquet
    git add events.parquet.dvc .gitignore && git commit -qm "dataset v1"
    cat events.parquet.dvc

    Options: dvc add hashes the file, moves it into the DVC cache, and writes a small .dvc pointer that Git versions instead of the data.

    Expect: The pointer shows an md5 and the size: that hash is the dataset version.

    Clean up: Nothing to undo; the cache is inside the lab folder.

  3. Change the data the way the incident did (dollars to cents) and see DVC notice.

    python3 -c "import pandas as pd; d=pd.read_parquet('events.parquet'); d['amount']=d['amount']*100; d.to_parquet('events.parquet')"
    dvc status
    dvc diff

    Expect: dvc status says the file changed. DVC sees a new version; only a quality check can say whether the new values are wrong.

  4. Go back to the version the model was trained on.

    git checkout -q HEAD -- events.parquet.dvc && dvc checkout -q
    python3 -c "import pandas as pd; print(pd.read_parquet('events.parquet')['amount'].tolist())"

    Expect: [45.99, 12.5, 230.0]: the pinned version, restored exactly.

  5. Run the contract checks in the next part on your own data: count rows and nulls per column with SQLite, a quick check needing no packages.

    python3 -c "import sqlite3; c=sqlite3.connect(':memory:'); c.execute('create table e(order_id, amount)'); c.executemany('insert into e values(?,?)', [('a1',45.99),('a2',None),('a3',230)]); print(c.execute('select count(*), sum(amount is null) from e').fetchone())"

    Expect: (3, 1): three rows, one null amount.

2. Python: data_contract.py

This program checks three hourly batches against a data contract: schema and types, nulls and ranges (bad rows go to quarantine), volume against the promised band, and the distribution of amount against a reference window using the population stability index. It shows which check catches each kind of bad data, and that the cents bug passes every check except the distribution one. Save it as data_contract.py, then run it.

# data_contract.py
import math
import random

CONTRACT = {
    "fields": {"order_id": str, "amount": float, "country": str},
    "amount_range": (0.0, 50000.0),
    "quarantine_rate_max": 0.01,
    "rows": (90_000, 140_000),
    "psi_block": 0.25,
}
EDGES = [0, 10, 25, 50, 100, 250, 1000, 5000, 1e12]  # amount buckets for PSI

def batch(seed, rows, scale=1.0):
    rnd = random.Random(seed)
    out = []
    for i in range(rows):
        amount = round(math.exp(rnd.gauss(3.7, 0.9)) * scale, 2)
        out.append({"order_id": f"o{seed}-{i}", "amount": amount, "country": rnd.choice(["DE", "FR", "US", "IN"])})
    return out

def shares(values):
    counts = [0] * (len(EDGES) - 1)
    for v in values:
        for b in range(len(EDGES) - 1):
            if EDGES[b] <= v < EDGES[b + 1]:
                counts[b] += 1
                break
    return [max(c / len(values), 1e-6) for c in counts]

def psi(reference, current):
    e, a = shares(reference), shares(current)
    return sum((ai - ei) * math.log(ai / ei) for ei, ai in zip(e, a))

def check(name, rows, reference):
    lo, hi = CONTRACT["amount_range"]
    quarantine, nulls, good = 0, 0, []
    for r in rows:
        ok = all(isinstance(r.get(f), t) for f, t in CONTRACT["fields"].items())
        if r.get("amount") is None:
            nulls += 1
        if not ok or not (lo <= r["amount"] <= hi):
            quarantine += 1
        else:
            good.append(r["amount"])
    results = [
        ("schema+ranges", quarantine / len(rows) <= CONTRACT["quarantine_rate_max"], f"{quarantine} rows quarantined ({quarantine / len(rows):.2%}, limit 1%)"),
        ("volume", CONTRACT["rows"][0] <= len(rows) <= CONTRACT["rows"][1], f"{len(rows):,} rows (band {CONTRACT['rows'][0]:,}-{CONTRACT['rows'][1]:,})"),
    ]
    p = psi(reference, good)
    results.append(("distribution", p <= CONTRACT["psi_block"], f"PSI of amount = {p:.3f} (block over {CONTRACT['psi_block']})"))
    verdict = "PUBLISH" if all(ok for _, ok, _ in results) else "BLOCK"
    print(f"{name:<22} {verdict}")
    for check_name, ok, detail in results:
        print(f"    {'pass' if ok else 'FAIL'}  {check_name:<13} {detail}")

reference = [r["amount"] for r in batch(1, 100_000)]
check("hour 10, normal", batch(2, 118_400), reference)
check("hour 11, cents bug", batch(3, 121_900, scale=100), reference)
check("hour 12, half a day", batch(4, 55_300), reference)

Run it, and you should see this output:

$ python3 data_contract.py
hour 10, normal        PUBLISH
    pass  schema+ranges 0 rows quarantined (0.00%, limit 1%)
    pass  volume        118,400 rows (band 90,000-140,000)
    pass  distribution  PSI of amount = 0.000 (block over 0.25)
hour 11, cents bug     BLOCK
    pass  schema+ranges 330 rows quarantined (0.27%, limit 1%)
    pass  volume        121,900 rows (band 90,000-140,000)
    FAIL  distribution  PSI of amount = 20.001 (block over 0.25)
hour 12, half a day    BLOCK
    pass  schema+ranges 0 rows quarantined (0.00%, limit 1%)
    FAIL  volume        55,300 rows (band 90,000-140,000)
    pass  distribution  PSI of amount = 0.000 (block over 0.25)

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/mlops-data-quality-and-contracts && cd ~/labs/mlops-data-quality-and-contracts) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "MLOps Data Quality and Data Contracts", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Make a project with Git and DVC, the way a training repository starts.'
  'Write a small day of events and track it as a dataset version.'
  'Change the data the way the incident did (dollars to cents) and see DVC notice.'
  'Go back to the version the model was trained on.'
  'Run the contract checks in the next part on your own data: count rows and nulls per column with SQLite, a quick check needing no packages.'
)

step_1() {
mkdir -p ~/labs/contracts && cd ~/labs/contracts
git init -q && dvc init -q
git status --short
}

step_2() {
python3 -c "import pandas as pd; pd.DataFrame({'order_id':['a1','a2','a3'],'amount':[45.99,12.50,230.00]}).to_parquet('events.parquet')"
dvc add events.parquet
git add events.parquet.dvc .gitignore && git commit -qm "dataset v1"
cat events.parquet.dvc
}

step_3() {
python3 -c "import pandas as pd; d=pd.read_parquet('events.parquet'); d['amount']=d['amount']*100; d.to_parquet('events.parquet')"
dvc status
dvc diff
}

step_4() {
git checkout -q HEAD -- events.parquet.dvc && dvc checkout -q
python3 -c "import pandas as pd; print(pd.read_parquet('events.parquet')['amount'].tolist())"
}

step_5() {
python3 -c "import sqlite3; c=sqlite3.connect(':memory:'); c.execute('create table e(order_id, amount)'); c.executemany('insert into e values(?,?)', [('a1',45.99),('a2',None),('a3',230)]); print(c.execute('select count(*), sum(amount is null) from e').fetchone())"
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your company has 30 models that depend on 60 datasets owned by 12 teams. Design the data contract and quality system that stops bad data before it reaches a model.

Clarifying questions to ask

Which datasets get contracts first? What does a contract contain, and where does it live? Which checks run where, and which block? How are breaking changes handled? How does a model run record its data, and how do you trace an incident to a producer commit?

Rough sizing

Say 60 datasets, hourly partitions of about 100,000 rows, nightly retraining for 30 models, and two serious data incidents last quarter.

Shape of the answer

Contracts as files in producer repositories (fields, units, volume, freshness, owner), checked in producer CI; pipeline checks in two tiers (row checks with quarantine, dataset checks that block); PSI on each model's top features; immutable dataset versions with check results attached; training pinned to versions and logged in the tracker; OpenLineage from every job into the catalog; a data SLO per contract with an on-call; breaking changes through major versions and a deprecation window.

Trade-offs to name

Blocking checks delay training when data is late, and stop bad models; tight distribution thresholds catch more and page more, so start with the fields the model depends on most; contracts add work for producers, who get fewer surprise escalations in return.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Dollars become centsHop 6: DistributionBreaksThere is no distribution check on amount. The median order is now 4,599 instead of 45.99, and nothing compares it with yesterday.
Half a day arrivesHop 5: Freshness and volumeBreaksThe volume check fires: 55,300 rows, 48% of normal. It was configured as a warning, so the pipeline continues. A training run starts on the half day, the new model looks worse offline, and it takes six hours of the team's time to find the cause.
Half a day arrivesHop 8: Training readDegradesThe run read dt=2026-11-27 directly, so its input is whatever was there at 10:20.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: The contract → Contract check in CI → Ingestion → Schema and nulls → Freshness and volume → Distribution → Dataset version → Training read → Lineage. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 322
Feature Stores, Online/Offline Consistency, and Lineage

A feature is a value a model reads: "orders this customer placed in the last 7 days". A feature store computes it once and serves it twice: from an offline store (a warehouse or lake) for training, with correct values for every…

Go to Lesson 322 →

Or browse the full course from the Lessons index.