Data Validation: Contracts, Stats, and Monitoring
Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe
Prerequisites
- !Working with pandas DataFrames
- !How training pipelines consume data
- !Basics of statistical distributions
What You'll Learn
- 1Classify data failures by the test that catches each one
- 2Express expectations as a versioned, reviewable suite
- 3Implement statistical rules with tolerances and evidence
- 4Choose between blocking, warning, and quarantining bad batches
The failures that validation prevents
Most ML incidents attributed to "the model" begin upstream. A nullable column stops being nullable and the ingestion job starts writing nulls as the string None, which passes a naive check and becomes a legitimate category. A currency column changes from one decimal place to three, shifting a feature by an order of magnitude without ever leaving its expected range. A join key silently changes type and the enrichment step starts matching almost nothing, so a feature that looked populated becomes a constant. None of these require a statistician to catch; they require a check that runs before training and fails loudly rather than a chart reviewed after the fact.
Validation is also the cheapest stage in the entire pipeline to make valuable. It runs in seconds, it needs no GPU, and it prevents an expensive model from being trained on garbage that then has to be traced, retrained, and redeployed. Teams that invest here first consistently report that their later monitoring alerts drop, because the class of problem that used to reach production is being stopped at the boundary where it entered.
Three layers of checking
Each layer catches what the others cannot. Schema checks are deterministic and cheap: names, types, presence, and basic invariants such as primary keys being unique. Statistical checks add tolerance: value ranges, null ratios, category frequency, and distribution distance against a reference. Distribution checks over time are the only ones that catch slow drift â a null ratio creeping from 1% to 9% looks fine in isolation at every point but is clearly wrong as a trend.
| Layer | Example check | Catches | Cost | Blocking by default |
|---|---|---|---|---|
| Schema | Column customer_id is int64 and unique | Renames, type changes, duplicate keys | Milliseconds | Yes |
| Statistical | lifetime_value between 0 and 1M, nulls below 5% | Corruption, sentinel values, unit errors | Seconds | Usually |
| Distribution | PSI below 0.2 versus training reference | Slow shifts and seasonal change | Seconds to minutes | Warn first |
| Volume | Row count within expected band for the window | Truncated extracts, stuck upstream jobs | Milliseconds | Yes |
The last column is the design decision that most affects adoption. Blocking too eagerly trains teams to override the check; blocking too rarely means the check exists but nothing stops. A reasonable default is to block on schema, volume, and hard range violations, and to warn on distribution movement until a threshold and an owner have been agreed.
Expectations as a versioned suite
Great Expectations frames each check as an expectation â a named, parameterized assertion with a documented rationale â which turns validation into something reviewable in a pull request rather than a script somebody edited at 2 a.m. The suite below covers a customer feature table, encodes business rules alongside physical ones, and emits a structured result that downstream stages can act on programmatically.
# expectations_suite.py
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List
import pandas as pd
@dataclass
class Expectation:
column: str
check: Callable[[pd.Series], bool]
description: str
severity: str = "block"
@dataclass
class SuiteResult:
suite: str
passed: bool
failures: List[Dict[str, str]] = field(default_factory=list)
observed: Dict[str, Any] = field(default_factory=dict)
def fail(self, column: str, message: str) -> None:
self.passed = False
self.failures.append({"column": column, "message": message})
class ExpectationSuite:
def __init__(self, name: str):
self.name = name
self.expectations: List[Expectation] = []
def add(self, column: str, check: Callable[[pd.Series], bool],
description: str, severity: str = "block") -> "ExpectationSuite":
self.expectations.append(Expectation(column, check, description, severity))
return self
def validate(self, df: pd.DataFrame) -> SuiteResult:
result = SuiteResult(suite=self.name, passed=True)
for exp in self.expectations:
if exp.column not in df.columns:
if exp.severity == "block":
result.fail(exp.column, "column missing")
continue
series = df[exp.column]
try:
ok = exp.check(series)
except Exception as exc:
result.fail(exp.column, f"check errored: {exc}")
continue
if not ok:
if exp.severity == "block":
result.fail(exp.column, exp.description)
else:
result.fail(exp.column, f"warn: {exp.description}")
result.observed[exp.column] = {
"nulls": float(series.isnull().mean()),
"unique": int(series.nunique()),
}
return result
def build_suite() -> ExpectationSuite:
suite = ExpectationSuite("customer_features_v3")
suite.add("customer_id", lambda s: s.is_unique, "customer_id must be unique")
suite.add("customer_id", lambda s: s.dtype.kind == "i", "customer_id must be integer")
suite.add("lifetime_value", lambda s: s.isnull().mean() < 0.05, "nulls below 5%")
suite.add("lifetime_value", lambda s: bool(((s >= 0) & (s <= 1_000_000)).all()),
"values within business range")
suite.add("total_purchases", lambda s: bool((s >= 0).all()), "non-negative purchases")
suite.add("segment", lambda s: s.isin(["bronze", "silver", "gold", "platinum"]).all(),
"segment in known set")
suite.add("days_since_last_order", lambda s: s.isnull().mean() < 0.02,
"nulls below 2%", severity="warn")
return suite
df = pd.DataFrame({
"customer_id": [1, 2, 3, 4],
"lifetime_value": [120.0, 45.5, 980.0, -3.0],
"total_purchases": [2, 1, 6, 3],
"segment": ["gold", "bronze", "silver", "gold"],
"days_since_last_order": [2, 14, 30, 7],
})
print(build_suite().validate(df))
Keep suites in the repository next to the pipeline code, one per dataset and version. When a definition legitimately changes, the change goes through review with the migration plan attached, and the old suite becomes part of the audit trail explaining why a historical model was trained under different rules.
Statistical rules you can unit test
Beyond expectations, a small rules engine handles the checks that depend on thresholds relative to a baseline: mean drift within tolerance, categorical distribution stability, and row counts within a band. The important property is that these are ordinary functions with inputs and outputs, which means you can test the validation logic itself â an underrated practice, since a checker that silently passes everything is worse than no checker at all.
# statistical_rules.py
from dataclasses import dataclass, field
from typing import Dict, List, Optional
import numpy as np
import pandas as pd
@dataclass
class RuleResult:
rule: str
passed: bool
observed: float
limit: float
message: str = ""
@dataclass
class RuleReport:
results: List[RuleResult] = field(default_factory=list)
@property
def passed(self) -> bool:
return all(r.passed for r in self.results)
@property
def blocking_failures(self) -> List[RuleResult]:
return [r for r in self.results if not r.passed]
def summary(self) -> str:
return "\n".join(
f"[{'PASS' if r.passed else 'FAIL'}] {r.rule}: "
f"observed={r.observed:.4f} limit={r.limit:.4f} {r.message}"
for r in self.results
)
class StatisticalRules:
def __init__(self, reference: pd.DataFrame):
self.reference = reference
self.report = RuleReport()
def row_count_band(self, current: pd.DataFrame, low: float, high: float) -> "StatisticalRules":
n = len(current)
ok = low <= n <= high
self.report.results.append(RuleResult(
"row_count", ok, float(n), high,
"" if ok else f"rows {n} outside band [{low}, {high}]",
))
return self
def mean_within(self, column: str, current: pd.DataFrame, tolerance_sd: float = 3.0) -> "StatisticalRules":
ref_mean = self.reference[column].mean()
ref_sd = self.reference[column].std()
observed = abs(current[column].mean() - ref_mean) / max(ref_sd, 1e-9)
self.report.results.append(RuleResult(
f"mean_shift:{column}", observed <= tolerance_sd, observed, tolerance_sd,
"" if observed <= tolerance_sd else "mean shifted beyond tolerance",
))
return self
def null_ratio(self, column: str, current: pd.DataFrame, max_ratio: float) -> "StatisticalRules":
ratio = float(current[column].isnull().mean())
self.report.results.append(RuleResult(
f"null_ratio:{column}", ratio <= max_ratio, ratio, max_ratio,
))
return self
def category_share(self, column: str, current: pd.DataFrame,
min_share: float = 0.01) -> "StatisticalRules":
shares = current[column].value_counts(normalize=True)
rare = shares[shares < min_share]
self.report.results.append(RuleResult(
f"category_share:{column}", len(rare) == 0, float(shares.min()), min_share,
f"rare categories: {list(rare.index)}" if len(rare) else "",
))
return self
def distribution_stable(self, column: str, current: pd.DataFrame,
max_psi: float = 0.2, bins: int = 10) -> "StatisticalRules":
ref = self.reference[column].dropna().to_numpy()
cur = current[column].dropna().to_numpy()
edges = np.quantile(ref, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf
ref_p = np.clip(np.histogram(ref, bins=edges)[0] / max(len(ref), 1), 1e-4, None)
cur_p = np.clip(np.histogram(cur, bins=edges)[0] / max(len(cur), 1), 1e-4, None)
psi = float(np.sum((cur_p - ref_p) * np.log(cur_p / ref_p)))
self.report.results.append(RuleResult(
f"psi:{column}", psi <= max_psi, psi, max_psi,
))
return self
reference = pd.DataFrame({"amount": np.random.lognormal(3.0, 0.5, 4000)})
current = pd.DataFrame({"amount": np.random.lognormal(3.3, 0.6, 3800)})
rules = StatisticalRules(reference)
rules.row_count_band(current, 3000, 5000) \
.null_ratio("amount", current, 0.05) \
.mean_within("amount", current) \
.distribution_stable("amount", current)
print(rules.report.summary())
print("blocking failures:", len(rules.report.blocking_failures))
Run this rules engine in your own test suite against synthetic bad data â a DataFrame with a null flood, a shifted mean, a missing column â and assert that each case produces a failure. A validation layer whose failure paths are untested will pass everything on the day it matters most.
Where validation belongs
Validation has three natural checkpoints, and skipping any one of them leaves a gap. On ingestion, check the raw extract against the schema before anything downstream consumes it â catching problems at the cheapest possible moment. Before training, re-run the statistical and distribution rules on the exact DataFrame the model will see, because transformations can introduce their own defects. In production monitoring, run the same suite on serving inputs continuously, so the boundary you enforced at training time is enforced identically at inference time.
Reusing one rule definition across all three checkpoints is the point. When the training check and the serving check are the same code, a discrepancy between them becomes impossible by construction, and a rule change is a single edit reviewed once rather than three edits that must be remembered and synchronized. This is the same parity principle that governs feature stores, applied to validation.
Block, warn, or quarantine
Not every failure deserves a hard stop, and not every one deserves a log line. Blocking is correct when proceeding would produce a model or a decision you cannot trust â missing keys, type changes, empty extracts. Warning is correct when the data is usable but notable, such as a distribution shift within an acknowledged seasonal pattern. Quarantine is the third option and the most underused: write the offending rows or partition aside with a reason attached, continue processing the remainder, and schedule review. Quarantine preserves both throughput and evidence, which matters when a partial upstream outage would otherwise cost you a full day of training.
Whichever path is chosen, the decision must be recorded with the run. If a run proceeded despite warnings, note which warnings and who accepted them. Six months later, when someone asks why a particular model behaves oddly for one segment, that record converts an investigation into a lookup â and it is the difference between a validation system the team trusts and one they route around.
đĄTest your validators like production code
Common Mistakes
Validating only at ingestion and never before training
Fix: Re-run the same rules on the exact training frame â transformations introduce their own defects.
Hard-blocking on every distribution shift
Fix: Warn on distribution movement by default and escalate to blocking only with an agreed threshold and owner.
Rules spread across notebooks and pipeline code
Fix: Keep one versioned rule module imported by ingestion, training, and serving monitors.
Discarding failing data without a trace
Fix: Quarantine bad rows with a reason and retain them, so the failure remains investigable.
Best Practices
- Version suites in the repository and change them through review
- Record observed statistics alongside pass or fail for later tuning
- Alert on trends, not only thresholds, to catch slow degradation
- Reuse one rule implementation across training and serving checkpoints
- Measure how often each rule fires â a rule that never fires is either perfect or dead
Interview Questions
Q1: Schema validation versus statistical validation â when do you need both?
Schema checks catch structural breaks immediately and cheaply; statistical checks catch values that fit the structure but violate the business or distributional assumptions.
Q2: What should happen when validation fails?
Block for structural and hard range failures, warn for notable-but-usable conditions, and quarantine suspect rows with a recorded reason.
Q3: How do you avoid validation becoming a bottleneck?
Run cheap checks on every ingest, heavy distribution checks on a sample, and keep suites fast enough that nobody is tempted to bypass them.
Q4: Why put validation suites in version control?
They are contracts. Versioning makes changes reviewable and creates an audit trail of what rules a given dataset satisfied.
Key Takeaways
- Validation is the cheapest stage to run and the most expensive to skip
- Three layers â schema, statistics, distribution â catch different failure classes
- Versioned expectations turn checks into reviewable contracts
- Block, warn, and quarantine are distinct responses, not a single on-off switch
- Reuse one rule module across ingestion, training, and serving for real parity