Data Quality Validation with Great Expectations
Models do not fail loudly when their inputs rot â they degrade quietly. A vendor renames a column, a sensor starts reporting zeros, a timezone bug shifts timestamps by one day, and training accuracy slips a fraction of a point at a time until the postmortem. Data quality validation is the discipline of encoding your assumptions about data as executable checks that run before downstream consumers see the data at all.
This lesson covers the five quality dimensions that matter for machine learning, two complementary validation frameworks (Great Expectations for expectation suites and reporting, Pandera for typed in-pipeline schemas), the data contract pattern for producer-consumer agreements, and a monitoring loop that catches the drift validation alone cannot.
What You'll Learn
- 1Classify quality failures across completeness, validity, consistency, uniqueness, and timeliness
- 2Write and run Great Expectations suites against tabular datasets
- 3Enforce typed schemas in pipeline code with Pandera
- 4Implement a data contract with severity levels and freshness checks
Prerequisites
- !pandas fluency
- !Basic understanding of CI/CD pipelines
- !Familiarity with training data provenance
The five dimensions that catch real failures
Quality frameworks enumerate many properties; five cover the failures that actually take models down in production.
Completeness asks whether required values are present â null rates per column, required keys never missing. A jump in customer_id nulls from 0.01% to 3% usually means a broken join upstream, not a behavior change. Validity asks whether values conform to expectations â emails match a pattern, amounts are non-negative, categories fall inside an enum. Consistency catches contradictions across sources â the same order has different totals in two tables, or a state abbreviations list disagrees between systems. Uniqueness detects duplicate primary keys, the classic symptom of a replayed batch or a broken incremental watermark. Timeliness asks whether data arrived when promised â a table whose max timestamp is six hours old is stale regardless of how clean its values are.
| Dimension | Example check | Typical severity | When it fires |
|---|---|---|---|
| Completeness | Null rate of customer_id below 0.1% | Critical | Broken upstream join, truncated extract |
| Validity | email matches regex pattern | Warning | Vendor format change |
| Consistency | Order totals agree across tables | Critical | Divergent ETL logic |
| Uniqueness | order_id is unique | Critical | Replay, watermark bug |
| Timeliness | Max event_time within 15 minutes | Critical | Downed producer, stuck stream |
Assign severities deliberately. Critical violations should fail the pipeline and page someone; warnings should annotate the data catalog and open a ticket. A validation suite where everything is critical trains responders to ignore alerts.
Great Expectations: executable expectations
Great Expectations (GX) turns these checks into a versionable suite with structured validation results, data docs for human review, and hooks for orchestration tools.
import great_expectations as gx
import pandas as pd
context = gx.get_context()
# Synthetic customer extract
df = pd.DataFrame({
"customer_id": range(1, 501),
"email": [f"user{i}@example.com" for i in range(1, 501)],
"age": [18 + (i * 7) % 60 for i in range(1, 501)],
"status": ["active", "inactive", "pending"] * 166 + ["active", "active"],
"lifetime_value": [round(50 + (i * 13) % 900, 2) for i in range(1, 501)],
})
df.loc[df.index[42], "email"] = "not-an-email" # deliberate violation
df.loc[df.index[77], "age"] = 250 # out-of-range violation
df.loc[df.index[100], "customer_id"] = 1 # duplicate key
validator = context.sources.pandas_default.read_dataframe(df)
validator.expect_column_values_to_not_be_null("customer_id")
validator.expect_column_values_to_be_unique("customer_id")
validator.expect_column_values_to_be_between("age", min_value=0, max_value=120)
validator.expect_column_values_to_match_regex(
"email", r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$", mostly=0.99
)
validator.expect_column_values_to_be_in_set(
"status", ["active", "inactive", "pending", "churned"]
)
validator.expect_column_values_to_be_between(
"lifetime_value", min_value=0, max_value=100000
)
results = validator.validate()
print(f"Success: {results.success}")
for r in results.results:
if not r.success:
print(f"FAILED: {r.expectation_config.type} on "
f"{r.expectation_config.kwargs.get('column')} -> "
f"{r.result}")
The mostly parameter is underused and valuable: it encodes "99% of emails must match", acknowledging real-world messiness without letting a systemic format change pass. Run suites in three places â a pre-merge check on pipeline code against fixture data, a scheduled job on freshly landed production data, and a lightweight check at the top of training jobs so no model trains on data the platform has already condemned.
Pandera: typed schemas inside the pipeline
Great Expectations excels at suites and reporting. Pandera complements it with schemas that live in Python code, validate on assignment, and integrate with type hints so a function cannot receive non-conforming data without raising immediately.
import pandera as pa
from pandera import Check, Column, DataFrameSchema
import pandas as pd
events = pd.DataFrame({
"event_id": ["e1", "e2", "e3", "e3"],
"user_id": ["u1", "u2", "u3", "u3"],
"event_type": ["click", "view", "purchase", "purchase"],
"amount": [None, None, 49.99, 49.99],
"timestamp": pd.to_datetime([
"2026-01-01T10:00:00", "2026-01-01T10:01:00",
"2026-01-01T10:02:00", "2026-01-01T10:02:00",
]),
})
EventSchema = DataFrameSchema({
"event_id": Column(str, Check.str_length(min_value=1), unique=True,
nullable=False),
"user_id": Column(str, nullable=False),
"event_type": Column(str, Check.isin(["click", "view", "purchase",
"add_to_cart", "signup"])),
"amount": Column(float, Check.greater_than_or_equal_to(0), nullable=True),
"timestamp": Column(pa.DateTime, nullable=False,
checks=Check.less_than(pd.Timestamp("2030-01-01"))),
}, checks=[
Check(lambda df: df.loc[df["event_type"] == "purchase", "amount"]
.notna().all(), "purchases must carry an amount"),
])
try:
EventSchema.validate(events, lazy=True)
except pa.errors.SchemaErrors as err:
print("Schema violations:")
print(err.failure_cases[["column", "check", "failure_case"]])
lazy=True collects all violations rather than stopping at the first â essential when a schema drift breaks six columns and you want all six in one ticket. The cross-column check (purchases must have amounts) is where Pandera shines relative to column-wise tools: business rules that no single column can express.
Data contracts: agreeing with your producers
Validation without an agreement is unilateral policing; producers will change schemas and blame consumers for not keeping up. A data contract formalizes the producer's promise â schema, semantics, freshness SLA, quality rules â and version-controls it next to the code that generates the data.
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from typing import Callable, Dict, List
import pandas as pd
class Severity(Enum):
CRITICAL = "critical" # fail the pipeline, page on-call
WARNING = "warning" # annotate and ticket
INFO = "info" # log only
@dataclass
class DataContract:
name: str
owner: str
freshness_minutes: int
columns: Dict[str, dict]
rules: List[dict] = field(default_factory=list)
def validate(self, df: pd.DataFrame) -> List[dict]:
violations = []
for col, spec in self.columns.items():
if spec.get("required", True) and col not in df.columns:
violations.append({"rule": f"missing:{col}",
"severity": Severity.CRITICAL.value})
continue
if col in df.columns and not spec.get("nullable", True):
nulls = int(df[col].isna().sum())
if nulls:
violations.append({"rule": f"nulls:{col}", "count": nulls,
"severity": Severity.CRITICAL.value})
for rule in self.rules:
ok, detail = rule["check"](df)
if not ok:
violations.append({"rule": rule["name"], "detail": detail,
"severity": rule["severity"].value})
return violations
contract = DataContract(
name="customer_events",
owner="[email protected]",
freshness_minutes=15,
columns={
"event_id": {"type": "string", "required": True, "nullable": False},
"user_id": {"type": "string", "required": True, "nullable": False},
"event_type": {"type": "string", "required": True, "nullable": False},
"timestamp": {"type": "datetime", "required": True, "nullable": False},
"amount": {"type": "float", "required": False, "nullable": True},
},
rules=[
{"name": "freshness",
"severity": Severity.CRITICAL.value,
"check": lambda df: (
(datetime.now() - df["timestamp"].max()) < timedelta(minutes=15),
f"lag={(datetime.now() - df['timestamp'].max())}"
)},
{"name": "unique_events",
"severity": Severity.CRITICAL.value,
"check": lambda df: (df["event_id"].is_unique, "duplicate event_ids")},
{"name": "purchase_amounts_present",
"severity": Severity.WARNING.value,
"check": lambda df: (
df.loc[df["event_type"] == "purchase", "amount"].notna().all(),
"purchases missing amount"
)},
],
)
print(contract.validate(events))
Publishing the contract in a machine-readable format (YAML or JSON in the producer's repository) enables a CI check: the producer's pipeline cannot merge a schema change that violates the current contract version without a coordinated consumer upgrade. That negotiation, not the validation code, is the part that prevents most outages.
Continuous monitoring and alerting
Point-in-time validation catches acute breaks; monitoring catches slow decay â null rates creeping up, volumes declining on weekends when they never used to, distributions shifting as a new cohort of users arrives.
import logging
from dataclasses import dataclass
from typing import Callable, Dict, List
import numpy as np
import pandas as pd
@dataclass
class Monitor:
name: str
metric_fn: Callable[[pd.DataFrame], float]
threshold: float
comparison: str = "gte" # gte: metric >= threshold is healthy
def evaluate(self, df: pd.DataFrame) -> dict:
value = float(self.metric_fn(df))
healthy = value >= self.threshold if self.comparison == "gte" \
else value <= self.threshold
return {"check": self.name, "value": value,
"threshold": self.threshold, "healthy": healthy}
class QualityMonitor:
def __init__(self):
self.monitors: List[Monitor] = []
self.history: List[dict] = []
self.log = logging.getLogger("dq")
def add(self, monitor: Monitor):
self.monitors.append(monitor)
def run(self, df: pd.DataFrame) -> List[dict]:
results = [m.evaluate(df) for m in self.monitors]
for r in results:
if not r["healthy"]:
self.log.warning("ALERT %s=%.4f (threshold %.4f)",
r["check"], r["value"], r["threshold"])
self.history.append({"ts": pd.Timestamp.now(), "results": results})
return results
monitor = QualityMonitor()
monitor.add(Monitor("null_free_rate",
lambda d: 1 - d.isna().mean().mean(), 0.98))
monitor.add(Monitor("freshness_minutes",
lambda d: (pd.Timestamp.now() - d["timestamp"].max())
.total_seconds() / 60, 30, comparison="lte"))
monitor.add(Monitor("unique_event_ratio",
lambda d: d["event_id"].nunique() / len(d), 0.999))
print(monitor.run(events))
Wire monitor output into the same observability stack as application metrics â dashboards showing null-free rate and freshness over 30 days make gradual decay visible long before a model metric moves. Pair it with a weekly review of the data catalog: every dataset that feeds a production model needs a named owner, an expected-freshness SLA, and the contract version it currently satisfies.
Where validation stops
Validation proves data conforms to what you already expected. It cannot tell you the expectation is right, that a new upstream partner is semantically different despite identical schemas, or that a distribution shift is seasonal rather than pathological. Those require the other half of the loop: drift detection against training distributions, sampling-based manual review of edge cases, and feedback from downstream model performance back into the expectation suite. Treat the suite as living documentation â every postmortem that traces to bad data should leave behind at least one new expectation.
A practical operating rhythm helps the suite stay alive rather than decaying into a ignored green checkmark. Run the full suite in CI against synthetic fixtures on every pipeline pull request, then run a lighter smoke suite on freshly landed production data on a schedule aligned with your ingestion cadence â hourly for streaming tables, daily for batch. Review the data docs weekly for the handful of datasets that feed production models, and treat any new warning-level violation as a conversation with the producer, not just a ticket. When a critical rule fires in production, the pipeline should fail closed and page the on-call owner named in the data contract; fail-open validation trains teams to ignore the gate entirely. Finally, budget time each quarter to retire stale expectations: a rule that has not fired in a year either reflects a stable process (keep it, it is cheap insurance) or a rule nobody understands anymore (delete it with a review note).
Common Mistakes
Marking every rule critical so on-call ignores the alert stream
Fix: Tier severities: critical fails the pipeline, warning annotates, info logs. Review alert volume monthly and demote rules that never page.
Validating only after the training job starts
Fix: Validate at ingestion and again before training; the earlier check short-circuits wasted compute and keeps poisoned rows out of the warehouse entirely.
Checking column types but not cross-column business rules
Fix: Add Pandera DataFrame-level checks (purchases carry amounts, end_date after start_date) that single-column validators cannot express.
Treating a green validation suite as proof the data is correct
Fix: Validation confirms conformance to existing expectations; combine with drift monitoring, sampled manual review, and downstream model metrics to catch wrong-but-valid data.
Best Practices
- Define expectations from real postmortems and incident reviews â every outage should leave a new check behind
- Run suites at three points: CI against fixtures, ingestion against fresh data, and pre-training against the final matrix
- Use Pandera lazy validation in pipeline code so all schema violations surface in one failure
- Version data contracts with the producer repository and block breaking changes without consumer sign-off
- Monitor aggregate quality metrics (null-free rate, freshness, uniqueness) on dashboards, not just pass/fail logs
Interview Questions
Q1: How do Great Expectations and Pandera differ in role?
Great Expectations manages suites, validation results, and data docs across a platform â best for scheduled checks and reporting. Pandera is a lightweight typed schema library embedded in pipeline code â best for failing fast inside ETL functions with cross-column rules.
Q2: What is a data contract and why does it matter operationally?
A versioned agreement between producer and consumer covering schema, semantics, freshness SLA, and quality rules. It turns unilateral validation into a negotiated interface, so schema changes are coordinated rather than discovered in production.
Q3: Name a quality problem point-in-time validation cannot catch.
Slow distribution drift: a column remains schema-valid while its value distribution shifts toward a new population. That requires statistical drift monitoring (PSI, KS tests) against a reference window, not just conformance checks.
Key Takeaways
- Quality failures cluster into completeness, validity, consistency, uniqueness, and timeliness â map every check to one of these and assign a severity
- Great Expectations suits platform-level suites and data docs; Pandera suits typed, in-code pipeline validation with cross-column rules
- Data contracts convert validation from policing into a producer-consumer agreement with SLAs
- Continuous monitors for null rates, freshness, and uniqueness catch decay that point checks miss
- Every data incident should produce a new expectation â the suite is living documentation, not a one-time deliverable