Worked Example: Validation Checks That Fail Loudly
Write schema, range, null-rate and distribution (PSI) checks for a nightly batch, calibrate the null-rate and PSI limits from 30 days of normal history instead of guessing them, and watch four broken batches (a type change, fees in cents, a broken join and a price rise) stop the pipeline before training with one clear report each.
Contentsand lesson path
On this page
- The problem
- Step 1: History and today’s batches
- Step 2: The checks
- Step 3: What PSI measures
- Step 4: Calibrate the limits from history
- Step 5: Run the pipeline on tonight’s batches
- Check your understanding
- Apply it
- Review prompt
Lessons of ML Pipelines & Continuous Training
- From Notebook to Pipeline: Steps, Artifacts and DAGs Concept · 20 min
- Lab: Orchestrate an End-to-End Training Pipeline Lab · 30 min
- Worked Example: Validation Checks That Fail Loudly Worked example · 20 min
- Champion vs Challenger: Automated Promotion Gates Concept · 20 min
- Lab: Testing ML Code in CI and Choosing Retraining Triggers Lab · 25 min
- Check: Pipeline Design Review Knowledge check · 8 questions
What you will learn
- Add data validation checks (schema, ranges, null rates, distributions) that stop the pipeline before bad data reaches training.
01. The problem
A churn model is retrained every night on a fresh batch of 1,000 customer records. Training code rarely crashes on bad data. It converts, fills and fits whatever it receives, and the damage shows up weeks later as a worse model. The validate step of the orchestration lab only checked that columns exist. Your task is to replace it with checks that stop the run, with a message a person can act on, whenever a batch breaks one of four kinds of rule:
- schema: every expected column is present with the expected type;
- ranges: values are physically possible and categories are known;
- null rates: missing values stay within what normal days show;
- distributions: the shape of each numeric feature stays close to the training data.
You will also decide how strict each check should be. The first two come from a data contract, the rules agreed with the team that produces the data. The last two are statistical, and their limits come from measuring normal days. You need Python 3.12 with NumPy and pandas.
mkdir validation-demo && cd validation-demo
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "numpy==2.5.5" "pandas==3.1.1"02. Step 1: History and today’s batches
batches.py generates the data. history() returns 30 normal nights. On a normal night 0.5% to 2% of support_calls values are missing, a level the team has always lived with. batch(30, kind) returns tonight in five versions: a normal one and four realistic breaks. In type_change, a new upstream release sends tenure as text such as "12 months". In cents, fees arrive in cents instead of euros. In nulls, a broken join loses 15% of support data. In price_rise, the basic plan really did go up from 45 to 55 euros.
"""Nightly customer batches: 30 normal days of history, plus today in five variants."""
import numpy as np
import pandas as pd
def batch(day: int, kind: str = "good", n: int = 1000) -> pd.DataFrame:
rng = np.random.default_rng(1000 + day)
plan = rng.choice(["basic", "standard", "premium"], n, p=[0.5, 0.3, 0.2])
base_fee = np.select([plan == "standard", plan == "premium"], [65.0, 90.0], 45.0)
df = pd.DataFrame({
"customer_id": [f"c{day:02d}{i:04d}" for i in range(n)],
"tenure_months": rng.integers(1, 73, n),
"monthly_fee": (base_fee + rng.normal(0, 8, n)).round(2),
"support_calls": rng.poisson(1.2, n).astype(float),
"plan": plan,
})
missing = rng.random(n) < rng.uniform(0.005, 0.02) # 0.5-2% nulls on a normal day
df.loc[missing, "support_calls"] = np.nan
if kind == "type_change": # upstream now sends text such as "12 months"
df["tenure_months"] = df["tenure_months"].astype(str) + " months"
elif kind == "cents": # fees arrive in cents instead of euros
df["monthly_fee"] = (df["monthly_fee"] * 100).round()
elif kind == "nulls": # a broken join drops the support system's data
df.loc[rng.random(n) < 0.15, "support_calls"] = np.nan
elif kind == "price_rise": # basic plan moved from 45 to 55 euros
df.loc[df["plan"] == "basic", "monthly_fee"] += 10
return df
def history():
return [batch(day) for day in range(30)]03. Step 2: The checks
checks.py keeps the contract at the top as plain data: the expected type of each column, the allowed range of each number and the allowed categories. The range limits are wide on purpose. A tenure of 600 months is unusual but possible; a negative tenure or a fee of 4,500 euros is not. Ranges catch impossible values, not unusual ones.
find_problems runs the four families in order and collects every problem as a sentence that names the column, the measured value and the limit. Range, null and distribution checks only run on columns that passed the schema check: comparing the text "12 months" with a number would crash with a TypeError and hide the real cause. check_or_raise raises one DataValidationError listing everything, so a single failed run tells the data owner all that is wrong.
import numpy as np
import pandas as pd
from pandas.api import types
# The data contract agreed with the upstream team: hard rules, not statistics.
SCHEMA = {"customer_id": "string", "tenure_months": "integer",
"monthly_fee": "number", "support_calls": "number", "plan": "string"}
RANGES = {"tenure_months": (0, 600), "monthly_fee": (0.0, 500.0),
"support_calls": (0, 50)}
ALLOWED = {"plan": {"basic", "standard", "premium"}}
IS_TYPE = {"string": types.is_string_dtype, "integer": types.is_integer_dtype,
"number": types.is_numeric_dtype}
class DataValidationError(Exception):
pass
def psi(reference, current, bins=10):
"""Population stability index over the reference deciles."""
ref = pd.Series(reference).dropna().to_numpy()
cur = pd.Series(current).dropna().to_numpy()
edges = np.unique(np.quantile(ref, np.linspace(0, 1, bins + 1)))
edges[0], edges[-1] = -np.inf, np.inf
e = np.histogram(ref, edges)[0] / len(ref)
a = np.histogram(cur, edges)[0] / len(cur)
e, a = np.clip(e, 1e-4, None), np.clip(a, 1e-4, None)
return float(np.sum((a - e) * np.log(a / e)))
def find_problems(df, reference, limits):
problems = []
for col, kind in SCHEMA.items(): # 1. schema
if col not in df.columns:
problems.append(f"schema: column {col!r} is missing")
elif not IS_TYPE[kind](df[col]):
problems.append(f"schema: {col!r} should be {kind}, got {df[col].dtype}")
typed_ok = [c for c in SCHEMA if c in df.columns and IS_TYPE[SCHEMA[c]](df[c])]
for col, (lo, hi) in RANGES.items(): # 2. ranges
if col in typed_ok:
bad = int(((df[col] < lo) | (df[col] > hi)).sum())
if bad:
problems.append(f"range: {bad} values of {col!r} outside [{lo}, {hi}]")
for col, allowed in ALLOWED.items():
if col in typed_ok and not set(df[col].dropna()) <= allowed:
extra = sorted(set(df[col].dropna()) - allowed)
problems.append(f"range: unexpected {col!r} values {extra}")
for col in typed_ok: # 3. null rates
rate, limit = df[col].isna().mean(), limits["null_rate"][col]
if rate > limit:
problems.append(f"nulls: {col!r} null rate {rate:.3f} > limit {limit:.3f}")
for col, limit in limits["psi"].items(): # 4. distributions
if col in typed_ok:
value = psi(reference[col], df[col])
if value > limit:
problems.append(f"drift: {col!r} PSI {value:.3f} > limit {limit:.3f}")
return problems
def check_or_raise(df, reference, limits):
problems = find_problems(df, reference, limits)
if problems: # report all, then stop
raise DataValidationError(f"{len(problems)} check(s) failed:\n "
+ "\n ".join(problems))04. Step 3: What PSI measures
The population stability index (PSI) compares two distributions of one feature. psi cuts the reference data into ten bins at its deciles, so each bin holds 10% of the reference rows, and measures what share of today’s rows fall into each bin. Each bin adds (today − reference) × ln(today / reference), so bins that gained or lost many rows add the most. The values are clipped away from zero so that an empty bin does not divide by zero. A PSI of 0 means identical shares. The script below moves the mean of a fee-like feature by a few euros.
import numpy as np
from checks import psi
rng = np.random.default_rng(0)
reference = rng.normal(60, 19, 15000) # like monthly_fee in the reference
for shift in [0, 2, 5, 10]:
today = rng.normal(60 + shift, 19, 1000) # a batch of 1,000 rows
print(f"mean moved by {shift:>2} euros: PSI {psi(reference, today):.3f}")python psi_demo.pymean moved by 0 euros: PSI 0.014
mean moved by 2 euros: PSI 0.024
mean moved by 5 euros: PSI 0.077
mean moved by 10 euros: PSI 0.321Even with no shift at all, PSI is 0.014, because 1,000 random rows never land in the bins in exactly the reference proportions. A shift of 2 euros is hard to tell from that noise; a shift of 10 euros, about half a standard deviation, gives 0.321. So the limit cannot be chosen from a formula alone. It depends on the batch size, the feature and how much a normal night varies, and the next step measures that.
05. Step 4: Calibrate the limits from history
calibrate.py uses nights 0 to 14 as the reference, the snapshot the model is trained on, and nights 15 to 29 to measure normal variation. Keeping the two apart matters: a night that is part of the reference is partly compared with itself, so its PSI is lower than a new night would show. For each numeric feature the PSI limit is 1.5 times the highest normal value, with a floor of 0.05 so that a very stable feature does not get a hair-trigger limit. The null-rate limit is the mean plus four standard deviations of the 30 normal nights, with a floor of 0.5%. Both rules are choices you should write down and revisit, not laws.
import json
import numpy as np
import pandas as pd
from batches import history
from checks import SCHEMA, psi
days = history()
reference = pd.concat(days[:15]) # days 0-14: the training snapshot
holdout = days[15:] # days 15-29: normal days not in it
reference.to_csv("reference.csv", index=False)
limits = {"null_rate": {}, "psi": {}}
for col in SCHEMA:
rates = np.array([d[col].isna().mean() for d in days])
limits["null_rate"][col] = round(max(rates.mean() + 4 * rates.std(), 0.005), 4)
for col in ["tenure_months", "monthly_fee", "support_calls"]:
values = np.array([psi(reference[col], d[col]) for d in holdout])
limits["psi"][col] = round(max(values.max() * 1.5, 0.05), 3)
print(f"{col:<14} normal-day PSI {values.min():.3f} to {values.max():.3f}"
f" -> limit {limits['psi'][col]}")
fee = [psi(reference["monthly_fee"], d["monthly_fee"]) for d in holdout]
print("a guessed fee limit of 0.01 would fail", sum(v > 0.01 for v in fee),
"of", len(fee), "normal days")
inside = [psi(reference["monthly_fee"], d["monthly_fee"]) for d in days[:15]]
print(f"fee PSI of nights inside the reference: up to {max(inside):.3f}")
rates = [d["support_calls"].isna().mean() for d in days]
print(f"support_calls normal-day null rate {min(rates):.3f} to {max(rates):.3f}"
f" -> limit {limits['null_rate']['support_calls']}")
json.dump(limits, open("limits.json", "w"), indent=1)
print("saved limits.json and reference.csv,", len(reference), "reference rows")python calibrate.pytenure_months normal-day PSI 0.005 to 0.021 -> limit 0.05
monthly_fee normal-day PSI 0.002 to 0.028 -> limit 0.05
support_calls normal-day PSI 0.000 to 0.003 -> limit 0.05
a guessed fee limit of 0.01 would fail 3 of 15 normal days
fee PSI of nights inside the reference: up to 0.016
support_calls normal-day null rate 0.003 to 0.022 -> limit 0.0338
saved limits.json and reference.csv, 15000 reference rowsNormal nights reach a fee PSI of 0.028, while nights inside the reference reach only 0.016. Calibrated on those, the rule would give 0.024 instead of 0.042 before the floor: a limit almost half as high, set by an optimistic view of normal. A limit of 0.01, which looks reasonable if you guess, would have failed 3 of the 15 normal nights, a false alarm about every five days, and people stop reading alerts that cry wolf. The null-rate limit for support_calls is 3.4%, above the worst normal night (2.2%) but far below a real breakage. In production you rerun this calibration on a schedule and review the limits when they move.
06. Step 5: Run the pipeline on tonight’s batches
pipeline.py is the validation step of the nightly run. It loads the reference and the limits, runs the checks, and exits with code 1 on any failure. An orchestrator treats a non-zero exit, or the raised exception inside a task, as a failed step, so the training step after it never starts.
import json
import sys
import pandas as pd
from batches import batch
from checks import DataValidationError, check_or_raise
kind = sys.argv[1] if len(sys.argv) > 1 else "good"
today = batch(30, kind)
reference = pd.read_csv("reference.csv")
limits = json.load(open("limits.json"))
try:
check_or_raise(today, reference, limits)
except DataValidationError as err:
print(f"validate: FAILED, pipeline stopped before training\n{err}")
sys.exit(1) # a non-zero exit fails the task and the run
print(f"validate: passed, training can start on {len(today)} rows")for kind in good type_change cents nulls price_rise; do
echo "== $kind"; python pipeline.py $kind; echo "exit code $?"
done== good
validate: passed, training can start on 1000 rows
exit code 0
== type_change
validate: FAILED, pipeline stopped before training
1 check(s) failed:
schema: 'tenure_months' should be integer, got str
exit code 1
== cents
validate: FAILED, pipeline stopped before training
2 check(s) failed:
range: 1000 values of 'monthly_fee' outside [0.0, 500.0]
drift: 'monthly_fee' PSI 8.283 > limit 0.050
exit code 1
== nulls
validate: FAILED, pipeline stopped before training
1 check(s) failed:
nulls: 'support_calls' null rate 0.155 > limit 0.034
exit code 1
== price_rise
validate: FAILED, pipeline stopped before training
1 check(s) failed:
drift: 'monthly_fee' PSI 0.531 > limit 0.050
exit code 1Each break is caught by the check designed for it, and the message names the column. The type change stops at the schema check, so nothing tries to compare text with numbers. Fees in cents break the range rule and, as a side effect, the distribution rule. The broken join shows up as a 15.5% null rate against a limit of 3.4%. The price rise is different: every value is valid, and only the shape changed.
That last case is not a bug, and the pipeline should still stop. A person decides whether the change is real and permanent; if it is, they rebuild the reference from recent data, recalibrate and rerun. Many teams give each check two levels: warn for small changes that someone reviews the next day, and fail for changes large enough to stop training. Libraries such as TensorFlow Data Validation, pandera and Great Expectations package the same ideas with schemas you store in the repository.
07. Check your understanding
08. Apply it
In the practice project, the pipeline must reject an injected schema change. Build that on your own data.
- Write the contract for your training table (types, ranges, categories) as data at the top of a
checks.py, and agree it with whoever produces the data. - Calibrate null-rate and PSI limits from at least 30 historical batches that are not part of your reference, and save them to a file the pipeline reads.
- Put the checks in the validate task of your pipeline, inject one schema break and one distribution shift of your own, and confirm the run stops before training with a message that names the column.
09. Review prompt
Without looking back, name the four families of checks and say which ones come from a contract and which from history; explain how PSI is computed and why its value is above zero even when nothing changed; describe how the limits were calibrated and why the calibration nights are kept out of the reference; and explain what the pipeline should do, and who decides, when a distribution shift turns out to be real.
References
- TensorFlow Data Validation guide (schema, skew and drift checks)
- Breck et al.: Data Validation for Machine Learning (MLSys 2019)
- Google Cloud: MLOps — Continuous Delivery and Automation Pipelines in Machine Learning
- pandas API: pandas.api.types.is_string_dtype
- pandera documentation (dataframe schemas and checks)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.