Project 4: Dataset Quality Analyzer
A delivery company retrains its delivery-time model every night on the previous day's orders, which arrive as a CSV file from a partner's system. Twice last year a bad file went straight into training: once a column was renamed, once distances suddenly arrived in metres. Both times the model got worse and nobody noticed for a week. The job: a quality gate that runs before training, checks each new batch against a written data contract and against a reference profile of known-good data, writes a JSON report, and returns an exit code (pass, warn or fail) that the pipeline obeys. The level is beginner; the main skills are data validation and cleaning turned into an automatic, repeatable step.
You built a dataset quality analyzer before, in the data course's mini project: a one-off investigation of a single messy table, ending in a report for a person to read. This project is the production version of the same idea, and it answers a different question: not "what is wrong with this dataset?" but "may this batch enter the pipeline, yes or no?", every day, with nobody looking unless it says no. It applies the two lessons of the deployment course, data validation and data drift, to that decision.
Goal and success criteria
| Criterion | |
|---|---|
| Decision | every batch gets pass (exit code 0), warn (1: train, but alert a person) or fail (2: do not train, keep yesterday's model) |
| Contract | written down before the first run: columns, types, ranges, allowed values, key, nulls, row count; reviewed with the partner |
| Distribution | PSI per column against the reference profile: below 0.1 pass, 0.1 to 0.25 warn, 0.25 or more fail (PSI) |
| Detection | on the three test batches built for this project (clean, drifted, broken): pass, warn, fail, each with the reason named in the report |
| No false alarms | 20 further clean batches from the reference process: all pass |
| Output | a JSON report per batch, quarantined rows in a separate file, the exit code |
The data
Real batches would come from the partner's export, under a data-sharing agreement that says which fields are sent, how often, and what happens when the format changes. Delivery records hold addresses and times, which are personal data; the batch here keeps only the city, and the gate never needs more (privacy, consent and licensing).
A generator writes daily batches of orders: order id, creation time, city, distance, number of items, payment method, the courier's rating (sometimes empty) and the delivery time in minutes. The reference is ten clean days in May. Then three test batches for June, built to fail in known ways:
- 3 June, clean: the same process as the reference.
- 4 June, drifted: distances are about 35 % longer (a new, larger delivery zone) and 3 % of payments use a new method,
wallet. Nothing is broken; the world changed. - 5 June, broken: the partner's new export renamed
courier_ratingtorating, sends a fifth of the distances in metres, and repeats 30 order ids.
Step 1: the contract and the reference profile
A contract has two parts. The rules come from people: the partner's documentation and the domain (a delivery is between 0.1 and 60 km; an order has 1 to 50 items). The profile comes from the reference data: the quantile bins for PSI and the category shares. Both are saved as JSON next to the pipeline, under version control, so that a change to the rules is a reviewed change.
import json
import numpy as np
import pandas as pd
CITIES = ["lyon", "lille", "nantes", "nice", "rennes"]
def make_batch(day, n=1000, seed=0, longer=0.0, wallet=0.0):
rng = np.random.default_rng(seed)
dist = np.round(rng.gamma(2.2, 1.6, n) * (1 + longer), 2)
items = rng.integers(1, 12, n)
pay = rng.choice(["card", "cash", "voucher"], n, p=[0.7, 0.2, 0.1])
pay = np.where(rng.random(n) < wallet, "wallet", pay)
return pd.DataFrame({
"order_id": [f"{day.replace('-', '')}-{i:05d}" for i in range(n)],
"created_at": (pd.Timestamp(day) + pd.to_timedelta(rng.integers(0, 86400, n), unit="s")).strftime("%Y-%m-%d %H:%M:%S"),
"city": rng.choice(CITIES, n, p=[0.3, 0.2, 0.2, 0.15, 0.15]),
"distance_km": dist, "items": items, "payment": pay,
"courier_rating": np.where(rng.random(n) < 0.04, np.nan, np.round(rng.uniform(3, 5, n), 1)),
"delivery_min": np.clip(np.round(12 + 4.5 * dist + 0.8 * items + rng.normal(0, 5, n)), 5, 180),
})
reference = pd.concat([make_batch(f"2024-05-{d:02d}", seed=d) for d in range(1, 11)], ignore_index=True)
contract = {
"version": "1.0", "key": "order_id", "rows": [500, 5000], "timestamp": "created_at",
"columns": {
"order_id": {"type": "str"},
"created_at": {"type": "datetime", "format": "%Y-%m-%d %H:%M:%S"},
"city": {"type": "category", "allowed": CITIES},
"distance_km": {"type": "float", "min": 0.1, "max": 60},
"items": {"type": "int", "min": 1, "max": 50},
"payment": {"type": "category", "allowed": ["card", "cash", "voucher"], "unknown": "warn"},
"courier_rating": {"type": "float", "min": 1, "max": 5, "max_null_share": 0.10},
"delivery_min": {"type": "float", "min": 5, "max": 180},
},
"row_violation_fail_share": 0.01,
"psi": {"warn": 0.1, "fail": 0.25},
}
def build_profile(ref, contract):
prof = {}
for col, rule in contract["columns"].items():
if rule["type"] in ("float", "int"):
edges = np.unique(np.quantile(ref[col].dropna(), np.linspace(0, 1, 11))[1:-1])
prof[col] = {"edges": [round(float(e), 4) for e in edges], "null_share": round(float(ref[col].isna().mean()), 4)}
elif rule["type"] == "category":
prof[col] = {"shares": {k: round(float(v), 4) for k, v in ref[col].value_counts(normalize=True).items()}}
return prof
profile = build_profile(reference, contract)
json.dump(contract, open("contract.json", "w"), indent=2)
json.dump(profile, open("profile.json", "w"), indent=2)
print(f"reference: {len(reference)} rows from {reference.created_at.str[:10].nunique()} days")
print("distance_km decile edges:", profile["distance_km"]["edges"])
print("payment shares:", profile["payment"]["shares"])
print("courier_rating null share:", profile["courier_rating"]["null_share"])
print("saved contract.json (", len(json.dumps(contract)), "bytes ) and profile.json (", len(json.dumps(profile)), "bytes )")reference: 10000 rows from 10 days
distance_km decile edges: [1.02, 1.53, 2.01, 2.47, 2.98, 3.534, 4.27, 5.19, 6.64]
payment shares: {'card': 0.6991, 'cash': 0.2031, 'voucher': 0.0978}
courier_rating null share: 0.0369
saved contract.json ( 685 bytes ) and profile.json ( 572 bytes )
The reference holds 10,000 orders from ten days. Its profile is small (572 bytes): nine decile edges per numeric column (for distance from 1.02 to 6.64 km), category shares (70 % card, 20 % cash, 10 % voucher) and null shares (3.7 % of courier ratings are empty; the contract allows up to 10 %). Two design choices are worth copying. The contract has a version, which every report repeats, so that a report can always be traced to the rules that produced it. And payment is marked "unknown": "warn": a new payment method is a business change the model can live with (its one-hot encoder ignores unknown values), while an unknown city means orders from a place the company does not serve, which is an error.
Step 2: schema and row checks
Each check returns a small record: what was checked, the measured value and a status. Schema problems (a missing column, a column that cannot be parsed) fail at once: the batch cannot be trusted at all. Row problems (a value out of range, an unknown category, a duplicate key, a bad timestamp) are counted: if they affect at most 1 % of the rows, those rows are quarantined and the batch warns; above 1 %, it fails. An extra column only warns: it may be a harmless addition, or the renamed version of a column that is now missing.
import numpy as np
import pandas as pd
CITIES = ["lyon", "lille", "nantes", "nice", "rennes"]
def make_batch(day, n=1000, seed=0, longer=0.0, wallet=0.0):
rng = np.random.default_rng(seed)
dist = np.round(rng.gamma(2.2, 1.6, n) * (1 + longer), 2)
items = rng.integers(1, 12, n)
pay = rng.choice(["card", "cash", "voucher"], n, p=[0.7, 0.2, 0.1])
pay = np.where(rng.random(n) < wallet, "wallet", pay)
return pd.DataFrame({
"order_id": [f"{day.replace('-', '')}-{i:05d}" for i in range(n)],
"created_at": (pd.Timestamp(day) + pd.to_timedelta(rng.integers(0, 86400, n), unit="s")).strftime("%Y-%m-%d %H:%M:%S"),
"city": rng.choice(CITIES, n, p=[0.3, 0.2, 0.2, 0.15, 0.15]),
"distance_km": dist, "items": items, "payment": pay,
"courier_rating": np.where(rng.random(n) < 0.04, np.nan, np.round(rng.uniform(3, 5, n), 1)),
"delivery_min": np.clip(np.round(12 + 4.5 * dist + 0.8 * items + rng.normal(0, 5, n)), 5, 180),
})
def broken_batch():
b = make_batch("2024-06-05", seed=5).rename(columns={"courier_rating": "rating"})
rng = np.random.default_rng(55)
metres = rng.random(len(b)) < 0.2
b.loc[metres, "distance_km"] = (b.loc[metres, "distance_km"] * 1000).round(0)
b.loc[rng.choice(len(b), 30, replace=False), "order_id"] = b.order_id.iloc[:30].to_numpy()
return b
CONTRACT = {"key": "order_id", "rows": [500, 5000], "row_violation_fail_share": 0.01, "columns": {
"order_id": {"type": "str"}, "created_at": {"type": "datetime", "format": "%Y-%m-%d %H:%M:%S"},
"city": {"type": "category", "allowed": CITIES}, "distance_km": {"type": "float", "min": 0.1, "max": 60},
"items": {"type": "int", "min": 1, "max": 50}, "payment": {"type": "category", "allowed": ["card", "cash", "voucher"], "unknown": "warn"},
"courier_rating": {"type": "float", "min": 1, "max": 5, "max_null_share": 0.10},
"delivery_min": {"type": "float", "min": 5, "max": 180}}}
def row_checks(df, contract, day):
"""Returns (results, bad_row_mask). Each result: (check, column, value, status)."""
out, bad = [], pd.Series(False, index=df.index)
lo, hi = contract["rows"]
out.append(("row count", "", len(df), "pass" if lo <= len(df) <= hi else "fail"))
cols = contract["columns"]
for col in cols:
if col not in df:
out.append(("column present", col, "missing", "fail"))
for col in df.columns.difference(list(cols)):
out.append(("unexpected column", col, "extra", "warn"))
for col, rule in cols.items():
if col not in df:
continue
s = df[col]
if rule["type"] in ("float", "int"):
num = pd.to_numeric(s, errors="coerce")
unparsable = num.isna() & s.notna()
if unparsable.mean() > 0.5:
out.append(("parses as number", col, f"{unparsable.mean():.1%} not numeric", "fail"))
continue
viol = unparsable | (num < rule["min"]) | (num > rule["max"])
bad |= viol
out.append((f"range {rule['min']}-{rule['max']}", col, int(viol.sum()), "pass" if viol.sum() == 0 else "rows"))
if rule["type"] == "category":
viol = s.notna() & ~s.isin(rule["allowed"])
if rule.get("unknown") == "warn": # a new value is news, not an error: keep the rows
new = sorted(s[viol].unique())
out.append(("new values", col, f"{new} in {int(viol.sum())} rows" if new else 0, "warn" if new else "pass"))
else:
bad |= viol
out.append(("allowed values", col, int(viol.sum()), "pass" if viol.sum() == 0 else "rows"))
if rule["type"] == "datetime":
t = pd.to_datetime(s, format=rule["format"], errors="coerce")
viol = t.isna() | (t.dt.strftime("%Y-%m-%d") != day)
bad |= viol
out.append(("timestamp on batch day", col, int(viol.sum()), "pass" if viol.sum() == 0 else "rows"))
null_share = s.isna().mean()
limit = rule.get("max_null_share", 0.0)
out.append(("null share", col, round(float(null_share), 3), "pass" if null_share <= limit else "fail"))
dup = df[contract["key"]].duplicated(keep=False)
bad |= dup
out.append(("unique key", contract["key"], int(dup.sum()), "pass" if dup.sum() == 0 else "rows"))
share = bad.mean() # row problems: quarantine or fail, decided on the total
row_status = "pass" if share == 0 else ("warn" if share <= contract["row_violation_fail_share"] else "fail")
out = [(c, col, v, row_status if st == "rows" else st) for c, col, v, st in out]
return out, bad
batches = {"2024-06-03": make_batch("2024-06-03", seed=3),
"2024-06-04": make_batch("2024-06-04", seed=4, longer=0.35, wallet=0.03),
"2024-06-05": broken_batch()}
for day, df in batches.items():
results, bad = row_checks(df, CONTRACT, day)
flagged = [r for r in results if r[3] != "pass"]
worst = max((r[3] for r in results), key=["pass", "warn", "fail"].index)
print(f"{day}: {len(df)} rows, {int(bad.sum())} bad rows ({bad.mean():.1%}) -> {worst}")
for check, col, value, status in flagged:
print(f" {status:4} {check:24} {col:15} {value}")2024-06-03: 1000 rows, 0 bad rows (0.0%) -> pass
2024-06-04: 1000 rows, 3 bad rows (0.3%) -> warn
warn range 0.1-60 distance_km 3
warn new values payment ['wallet'] in 38 rows
2024-06-05: 1000 rows, 266 bad rows (26.6%) -> fail
fail column present courier_rating missing
warn unexpected column rating extra
fail range 0.1-60 distance_km 218
fail unique key order_id 58
- 3 June passes every rule.
- 4 June has 3 orders over 60 km (the new zone's tail), 0.3 % of the rows: they are quarantined and the batch warns. The new payment value
wallet(38 rows) is reported as news, not removed. - 5 June fails for three independent reasons, each of which alone would stop it:
courier_ratingis missing (andrating, an unexpected column, is very probably its new name, but the gate does not guess); 218 distances are far above 60 "km" (the metres); and 58 rows share an order id with another row. Together 26.6 % of the rows break a rule.
The gate does not repair anything. Renaming rating back or dividing by 1,000 might be right, but it is a decision for the people who own the contract and the partner's export; the gate's job is to stop the batch and say exactly why.
Step 3: distribution checks against the reference
A batch can pass every rule and still be unlike the data the model learned from. PSI compares the share of rows in each reference decile (numbers) or each category (categories, with any new value as its own bin) between the reference and the batch. It is computed for every column that passed its schema check; KS D, the largest gap between the two cumulative distributions, is printed alongside for numbers. With 1,000 rows per batch, a KS test would call tiny shifts significant, so the decision uses PSI with fixed thresholds and KS is information only (big samples make everything significant).
import numpy as np
import pandas as pd
from scipy.stats import ks_2samp
CITIES = ["lyon", "lille", "nantes", "nice", "rennes"]
def make_batch(day, n=1000, seed=0, longer=0.0, wallet=0.0):
rng = np.random.default_rng(seed)
dist = np.round(rng.gamma(2.2, 1.6, n) * (1 + longer), 2)
items = rng.integers(1, 12, n)
pay = rng.choice(["card", "cash", "voucher"], n, p=[0.7, 0.2, 0.1])
pay = np.where(rng.random(n) < wallet, "wallet", pay)
return pd.DataFrame({
"order_id": [f"{day.replace('-', '')}-{i:05d}" for i in range(n)],
"created_at": (pd.Timestamp(day) + pd.to_timedelta(rng.integers(0, 86400, n), unit="s")).strftime("%Y-%m-%d %H:%M:%S"),
"city": rng.choice(CITIES, n, p=[0.3, 0.2, 0.2, 0.15, 0.15]),
"distance_km": dist, "items": items, "payment": pay,
"courier_rating": np.where(rng.random(n) < 0.04, np.nan, np.round(rng.uniform(3, 5, n), 1)),
"delivery_min": np.clip(np.round(12 + 4.5 * dist + 0.8 * items + rng.normal(0, 5, n)), 5, 180),
})
NUMERIC, CATEGORICAL = ["distance_km", "items", "courier_rating", "delivery_min"], ["city", "payment"]
def psi(ref_share, new_share, eps=1e-4):
r, n = np.maximum(ref_share, eps), np.maximum(new_share, eps)
return float(np.sum((n - r) * np.log(n / r)))
def numeric_psi(ref, new):
edges = np.unique(np.quantile(ref, np.linspace(0, 1, 11))[1:-1])
share = lambda x: np.bincount(np.searchsorted(edges, x, side="right"), minlength=len(edges) + 1) / len(x)
return psi(share(ref), share(new))
def category_psi(ref, new):
cats = sorted(set(ref) | set(new))
share = lambda x: pd.Series(x).value_counts(normalize=True).reindex(cats, fill_value=0).to_numpy()
return psi(share(ref), share(new))
def status(v):
return "pass" if v < 0.1 else ("warn" if v < 0.25 else "fail")
reference = pd.concat([make_batch(f"2024-05-{d:02d}", seed=d) for d in range(1, 11)], ignore_index=True)
batches = {"2024-06-03 clean": make_batch("2024-06-03", seed=3),
"2024-06-04 drifted": make_batch("2024-06-04", seed=4, longer=0.35, wallet=0.03)}
for name, b in batches.items():
print(name)
for col in NUMERIC:
v = numeric_psi(reference[col].dropna(), b[col].dropna())
d = ks_2samp(reference[col].dropna(), b[col].dropna()).statistic
print(f" {col:15} PSI {v:6.3f} KS D {d:.3f} {status(v)}")
for col in CATEGORICAL:
v = category_psi(reference[col], b[col])
new_values = sorted(set(b[col]) - set(reference[col]))
print(f" {col:15} PSI {v:6.3f} {'new: ' + str(new_values) if new_values else '':16} {status(v)}")
print("\n20 more clean days: largest PSI of any column on each day")
worst = [max([numeric_psi(reference[c].dropna(), b[c].dropna()) for c in NUMERIC] +
[category_psi(reference[c], b[c]) for c in CATEGORICAL])
for b in (make_batch(f"2024-06-{d:02d}", seed=100 + d) for d in range(6, 26))]
print(" max", round(max(worst), 3), "| mean", round(float(np.mean(worst)), 3), "| days not pass:", sum(w >= 0.1 for w in worst))2024-06-03 clean
distance_km PSI 0.013 KS D 0.051 pass
items PSI 0.021 KS D 0.027 pass
courier_rating PSI 0.004 KS D 0.014 pass
delivery_min PSI 0.011 KS D 0.033 pass
city PSI 0.001 pass
payment PSI 0.004 pass
2024-06-04 drifted
distance_km PSI 0.171 KS D 0.155 warn
items PSI 0.007 KS D 0.026 pass
courier_rating PSI 0.005 KS D 0.025 pass
delivery_min PSI 0.157 KS D 0.156 warn
city PSI 0.002 pass
payment PSI 0.228 new: ['wallet'] warn
20 more clean days: largest PSI of any column on each day
max 0.035 | mean 0.015 | days not pass: 0
The clean batch stays far below 0.1 everywhere (largest PSI 0.021). The drifted batch warns on three columns: distance (0.171), delivery time (0.157) and payment (0.228, mostly from the new wallet bin). Delivery time is the model's target: it moved because distances did, which is exactly the situation where retraining on the new data is right, but a person should know that the model is about to learn a new zone. Its KS D values (0.155 and 0.156) say the same, but on 1,000 against 10,000 rows a KS test would also flag the clean batch's 0.051 as significant at the 5 % level, which is why KS is not used for the decision. Over 20 more clean days, the largest PSI of any column on any day is 0.035: no day comes near the warn threshold, so the PSI part of the "no false alarms" criterion holds.
How large should a batch be for PSI to be trusted? The drift monitor from the deployment course answers it visually: a shift of half a standard deviation from day 31, PSI with an alarm threshold of 0.2. Set the drift to "none" and shrink the daily window to 50 rows: with nothing changing at all, PSI crosses the threshold on 33 of the 60 days, because ten bins of five rows each are mostly noise. That is why the contract has a minimum of 500 rows per batch.
Step 4: the gate as a program
The pieces become one command that a scheduler runs before training: python gate.py --batch orders-2024-06-05.csv. It reads the contract and profile, runs the three stages, writes reports/<day>.json and, when the batch is usable, quarantine/<day>.csv with the rejected rows and clean/<day>.csv with the rest. The exit code is the overall status. The pipeline step after it is plain shell: python gate.py --batch "$F" || [ $? -eq 1 ] continues on 0 and 1 and stops on 2.
In the browser there is no shell, so main(argv) returns the code instead of calling sys.exit, and the example calls it for the three June files.
import argparse, json, os
import numpy as np
import pandas as pd
CITIES = ["lyon", "lille", "nantes", "nice", "rennes"]
def make_batch(day, n=1000, seed=0, longer=0.0, wallet=0.0):
rng = np.random.default_rng(seed)
dist = np.round(rng.gamma(2.2, 1.6, n) * (1 + longer), 2)
items = rng.integers(1, 12, n)
pay = rng.choice(["card", "cash", "voucher"], n, p=[0.7, 0.2, 0.1])
pay = np.where(rng.random(n) < wallet, "wallet", pay)
return pd.DataFrame({
"order_id": [f"{day.replace('-', '')}-{i:05d}" for i in range(n)],
"created_at": (pd.Timestamp(day) + pd.to_timedelta(rng.integers(0, 86400, n), unit="s")).strftime("%Y-%m-%d %H:%M:%S"),
"city": rng.choice(CITIES, n, p=[0.3, 0.2, 0.2, 0.15, 0.15]),
"distance_km": dist, "items": items, "payment": pay,
"courier_rating": np.where(rng.random(n) < 0.04, np.nan, np.round(rng.uniform(3, 5, n), 1)),
"delivery_min": np.clip(np.round(12 + 4.5 * dist + 0.8 * items + rng.normal(0, 5, n)), 5, 180),
})
# ---- setup: the files the gate expects (in production they already exist) ----
reference = pd.concat([make_batch(f"2024-05-{d:02d}", seed=d) for d in range(1, 11)], ignore_index=True)
CONTRACT = {"version": "1.0", "key": "order_id", "rows": [500, 5000], "row_violation_fail_share": 0.01,
"psi": {"warn": 0.1, "fail": 0.25}, "columns": {
"order_id": {"type": "str"}, "created_at": {"type": "datetime", "format": "%Y-%m-%d %H:%M:%S"},
"city": {"type": "category", "allowed": CITIES}, "distance_km": {"type": "float", "min": 0.1, "max": 60},
"items": {"type": "int", "min": 1, "max": 50}, "payment": {"type": "category", "allowed": ["card", "cash", "voucher"], "unknown": "warn"},
"courier_rating": {"type": "float", "min": 1, "max": 5, "max_null_share": 0.10},
"delivery_min": {"type": "float", "min": 5, "max": 180}}}
json.dump(CONTRACT, open("contract.json", "w"))
reference.to_csv("reference.csv", index=False)
make_batch("2024-06-03", seed=3).to_csv("orders-2024-06-03.csv", index=False)
make_batch("2024-06-04", seed=4, longer=0.35, wallet=0.03).to_csv("orders-2024-06-04.csv", index=False)
b = make_batch("2024-06-05", seed=5).rename(columns={"courier_rating": "rating"})
rng = np.random.default_rng(55)
metres = rng.random(len(b)) < 0.2
b.loc[metres, "distance_km"] = (b.loc[metres, "distance_km"] * 1000).round(0)
b.loc[rng.choice(len(b), 30, replace=False), "order_id"] = b.order_id.iloc[:30].to_numpy()
b.to_csv("orders-2024-06-05.csv", index=False)
# ---- gate.py ----
LEVEL = {"pass": 0, "warn": 1, "fail": 2}
def psi(r, n, eps=1e-4):
r, n = np.maximum(r, eps), np.maximum(n, eps)
return float(np.sum((n - r) * np.log(n / r)))
def shares(x, bins):
return np.bincount(np.searchsorted(bins, x, side="right"), minlength=len(bins) + 1) / len(x)
def check(df, ref, contract, day):
res, bad = [], pd.Series(False, index=df.index)
add = lambda check, col, value, st: res.append({"check": check, "column": col, "value": value, "status": st})
lo, hi = contract["rows"]
add("row count", None, len(df), "pass" if lo <= len(df) <= hi else "fail")
cols = contract["columns"]
for col in df.columns.difference(list(cols)):
add("unexpected column", col, "extra", "warn")
usable = []
for col, rule in cols.items():
if col not in df:
add("column present", col, "missing", "fail")
continue
s, viol = df[col], pd.Series(False, index=df.index)
if rule["type"] in ("float", "int"):
num = pd.to_numeric(s, errors="coerce")
viol = (num.isna() & s.notna()) | (num < rule["min"]) | (num > rule["max"])
elif rule["type"] == "category":
viol = s.notna() & ~s.isin(rule["allowed"])
if rule.get("unknown") == "warn" and viol.any():
add("new values", col, sorted(s[viol].unique()), "warn")
viol = pd.Series(False, index=df.index)
elif rule["type"] == "datetime":
t = pd.to_datetime(s, format=rule["format"], errors="coerce")
viol = t.isna() | (t.dt.strftime("%Y-%m-%d") != day)
if viol.any():
add("row rule", col, int(viol.sum()), "rows")
bad |= viol
if s.isna().mean() > rule.get("max_null_share", 0.0):
add("null share", col, round(float(s.isna().mean()), 3), "fail")
usable.append(col)
dup = df[contract["key"]].duplicated(keep=False)
if dup.any():
add("unique key", contract["key"], int(dup.sum()), "rows")
bad |= dup
row_st = "warn" if bad.mean() <= contract["row_violation_fail_share"] else "fail"
for r in res:
r["status"] = row_st if r["status"] == "rows" else r["status"]
good = df[~bad] # distribution checks on the rows that passed
for col in usable:
rule = cols[col]
if rule["type"] in ("float", "int"):
ref_x = ref[col].dropna()
bins = np.unique(np.quantile(ref_x, np.linspace(0, 1, 11))[1:-1])
v = psi(shares(ref_x, bins), shares(pd.to_numeric(good[col]).dropna(), bins))
elif rule["type"] == "category":
cats = sorted(set(ref[col]) | set(good[col]))
sh = lambda x: x.value_counts(normalize=True).reindex(cats, fill_value=0).to_numpy()
v = psi(sh(ref[col]), sh(good[col]))
else:
continue
p = contract["psi"]
st = "pass" if v < p["warn"] else ("warn" if v < p["fail"] else "fail")
if st != "pass":
add("PSI", col, round(v, 3), st)
return res, bad
def main(argv):
ap = argparse.ArgumentParser(prog="gate.py")
ap.add_argument("--batch", required=True)
ap.add_argument("--contract", default="contract.json")
ap.add_argument("--reference", default="reference.csv")
args = ap.parse_args(argv)
contract, ref = json.load(open(args.contract)), pd.read_csv(args.reference)
df = pd.read_csv(args.batch)
day = os.path.basename(args.batch)[len("orders-"):-len(".csv")]
results, bad = check(df, ref, contract, day)
status = max((r["status"] for r in results), key=LEVEL.get, default="pass")
report = {"batch": args.batch, "contract_version": contract["version"], "rows": len(df),
"rows_quarantined": int(bad.sum()) if status != "fail" else 0, "status": status,
"problems": [r for r in results if r["status"] != "pass"]}
os.makedirs("reports", exist_ok=True)
json.dump(report, open(f"reports/{day}.json", "w"), indent=2)
if status != "fail":
os.makedirs("quarantine", exist_ok=True)
os.makedirs("clean", exist_ok=True)
df[bad].to_csv(f"quarantine/{day}.csv", index=False)
df[~bad].to_csv(f"clean/{day}.csv", index=False)
return LEVEL[status]
# ---- the scheduler calls it once per file ----
for f in ["orders-2024-06-03.csv", "orders-2024-06-04.csv", "orders-2024-06-05.csv"]:
code = main(["--batch", f])
day = f[7:17]
rep = json.load(open(f"reports/{day}.json"))
print(f"{f}: exit {code} ({rep['status']}), quarantined {rep['rows_quarantined']}, "
f"{'training runs' if code < 2 else 'pipeline stopped, yesterday model kept'}")
for p in rep["problems"]:
print(f" {p['status']:4} {p['check']:18} {str(p['column']):15} {p['value']}")
print("\nreports/2024-06-04.json:")
print(open("reports/2024-06-04.json").read())orders-2024-06-03.csv: exit 0 (pass), quarantined 0, training runs
orders-2024-06-04.csv: exit 1 (warn), quarantined 3, training runs
warn row rule distance_km 3
warn new values payment ['wallet']
warn PSI distance_km 0.176
warn PSI payment 0.222
warn PSI delivery_min 0.159
orders-2024-06-05.csv: exit 2 (fail), quarantined 0, pipeline stopped, yesterday model kept
warn unexpected column rating extra
fail row rule distance_km 218
fail column present courier_rating missing
fail unique key order_id 58
reports/2024-06-04.json:
{
"batch": "orders-2024-06-04.csv",
"contract_version": "1.0",
"rows": 1000,
"rows_quarantined": 3,
"status": "warn",
"problems": [
{
"check": "row rule",
"column": "distance_km",
"value": 3,
"status": "warn"
},
{
"check": "new values",
"column": "payment",
"value": [
"wallet"
],
"status": "warn"
},
{
"check": "PSI",
"column": "distance_km",
"value": 0.176,
"status": "warn"
},
{
"check": "PSI",
"column": "payment",
"value": 0.222,
"status": "warn"
},
{
"check": "PSI",
"column": "delivery_min",
"value": 0.159,
"status": "warn"
}
]
}
The three files get the three intended decisions, each with its reasons in the report: exit 0 for 3 June; exit 1 for 4 June, with 3 rows quarantined and five warnings for the person on call; exit 2 for 5 June, where the training step never starts and yesterday's model keeps serving. The PSI values in the gate (0.176 for distance) differ slightly from Step 3 (0.171) because the gate computes them on the rows that survived the row checks, so that broken rows cannot pass as drift. The report is plain JSON with the contract version, so a dashboard or an alerting rule can read it as easily as a person.
What the gate cannot see belongs in the write-up: labels that are wrong but plausible, values that are wrong but in range (a distance of 3.0 km that should be 30), and drift too slow to cross a threshold on any single day.
Extensions
- Add cross-column rules (a delivery of 1 km that takes 150 minutes; more items than a courier can carry) and decide whether they quarantine rows or only warn.
- Make the reference rolling (the last 30 accepted days) instead of fixed, and think about the risk: a slow drift is accepted a little each day (retraining strategies).
- Track the gate's own history: PSI per column per day as a time series, with the drift monitor's logic for alarms over several days.
- Express the same contract in a validation library (pandera, Great Expectations) and compare what you gain and lose (data validation, "Tools").
- Run the gate in CI on a sample of each new export format before the partner switches over (CI/CD for ML).
Write-up template
Gate: <pipeline>, contract version <x>, reference <period, rows>
Rules (from people): <columns, types, ranges, allowed values, key, nulls, row count>, reviewed by <who>
Profile (from data): <bins, shares>, rebuilt when <...>
Decision rules: row violations <x %> quarantine / fail; PSI warn <x>, fail <x>; minimum batch size <n>
Tested on: clean <result>, drifted <result>, broken <result>, <n> extra clean batches <false alarms>
Actions: pass -> <...>; warn -> <who is alerted, by when>; fail -> <fallback, who fixes, how to re-run>
Known gaps: <what the gate cannot see: label quality, slow drift, correct-looking wrong values>Practice
- The partner says the renamed column on 5 June was intended, and from now on it will be
rating. What do you change, and in what order?
Answer
The contract, not the gate's code: rename the column in a new contract version (1.1), have the change reviewed, and keep the profile (the values did not change, only the name). Then re-run the gate on the 5 June file: it still fails on the metres and the duplicate ids, which are separate problems for the partner. Reports from before the change keep pointing at version 1.0.
- Why does the gate compute PSI only on rows that passed the row checks?
Answer
Otherwise one problem is counted twice and, worse, can change category: 218 distances in metres would also give a huge PSI for distance_km, so a row problem would appear as drift. Separating them keeps the report's reasons accurate. When a batch fails on rows, the distribution checks are not the reason to look at.
- A colleague wants to lower the PSI fail threshold to 0.1 "to be safe". What would happen on 4 June, and what is the cost?
Answer
4 June would fail (three columns above 0.1) and the pipeline would keep yesterday's model, which knows nothing about the new delivery zone, so predictions there stay poor until a person intervenes. The cost of a too-strict gate is a stale model and alert fatigue; the cost of a too-loose one is training on bad data. The warn level exists for exactly this middle ground: train, and make sure a person looks.
Test yourself
The 4 June batch has 3 orders above the 60 km limit (0.3 % of rows). What does the gate do?
- Fails the batch
- Quarantines the 3 rows and warns, because the share is below the 1 % limit
- Clips the distances to 60 km
- Ignores them
Why is a new payment method a warning while an unknown city would make rows invalid?
- Cities are more important than payments
- The contract says so per column: a new payment method is a business change the model tolerates, an unknown city means orders the company does not serve
- PSI cannot be computed for cities
- Payments are numeric
Why does the gate decide with PSI thresholds rather than a KS test's p-value?
- KS cannot compare numeric columns
- With 1,000 and 10,000 rows, a KS test calls even the clean batch's tiny differences significant
- PSI is always more accurate
- KS needs labels
What should the training pipeline do when the gate exits with code 2?
- Train anyway and alert
- Not train, keep the current model serving, and alert the owners with the report
- Delete the batch
- Lower the thresholds and re-run the gate