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
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.
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.
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 caught
Three questions. No score is saved anywhere — this is just you against the material.
Data quality grows in four levels: reading a validation report, writing contracts and checks, versioning and quarantining, and running contracts across an organisation.
At the basic level you can read what the checks found and say whether the data is fit to train on.
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.
At the intermediate level you write the contract with the producer and turn it into checks.
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.
At the advanced level every dataset a model sees is a version with its checks attached.
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.
At the master level data contracts are how teams depend on each other.
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.
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.
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.
amount in cents. The field is still a number; their tests pass.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.
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.
Type each one, read what it prints, and compare it with the note above it.
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
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.dvcChange 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 diffGo 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())"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())"data_contract.pyThis 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)
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
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
diff, mkdir, cat, cd, If...Else.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.
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?
Say 60 datasets, hourly partitions of about 100,000 rows, nightly retraining for 30 models, and two serious data incidents last quarter.
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.
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.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Dollars become cents | Hop 6: Distribution | Breaks | There 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 arrives | Hop 5: Freshness and volume | Breaks | The 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 arrives | Hop 8: Training read | Degrades | The run read dt=2026-11-27 directly, so its input is whatever was there at 10:20. |
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.