TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Data Validation: Schemas and Expectations

Data Validation: Schemas and Expectations

Most models in production do not fail with an exception. They fail quietly, because the data changed: an upstream team renamed a category from "South" to "south", a form started sending ages as text, a currency conversion was applied twice, a join started producing nulls. The model accepts all of it and returns numbers, and the numbers are wrong. Data validation checks data against explicit expectations before it is used, for training and for prediction, so that bad data stops the pipeline or the request instead of silently degrading the model.

What to check

raw batch batch validationschema + profile training fail: stop, alert request request schemaPydantic model model fail: 422 error logged inputs vs training profile: skew

Expectations come in two kinds:

  • Schema checks, row by row: the expected columns and no others, types (a number, an integer, a date), ranges (age 18 to 100, a ratio between 0 and 1.5), allowed categories, nullability, uniqueness of keys. They have a clear right answer, and a violation is a bug somewhere.
  • Distribution checks, on a whole batch against a reference profile computed on the training data: medians and quantiles, share of nulls, category proportions, correlations. A violation is a signal, not a proof: data may legitimately change. These checks overlap with drift detection, which adds statistical tests (PSI, KS) and monitoring over time.

From scratch: a schema validator in pandas

A schema is a dictionary of rules per column. The validator reports every problem at once with the offending values, which is what an engineer needs to fix the source. The batch of 8 loan applications contains the usual suspects.

python · try it yourself
import numpy as np
import pandas as pd

SCHEMA = {
    "income":     {"dtype": "float", "min": 0, "max": 100_000, "nullable": False},
    "debt_ratio": {"dtype": "float", "min": 0.0, "max": 1.5, "nullable": False},
    "age":        {"dtype": "int", "min": 18, "max": 100, "nullable": False},
    "region":     {"dtype": "category", "allowed": {"north", "south", "east", "west"}, "nullable": False},
    "employment": {"dtype": "category", "allowed": {"employed", "self", "unemployed", "retired"}, "nullable": True},
}

def validate(df, schema, max_null_share=0.05):
    issues = []
    missing = set(schema) - set(df.columns)
    extra = set(df.columns) - set(schema)
    if missing: issues.append(("table", "missing columns", sorted(missing)))
    if extra: issues.append(("table", "unexpected columns", sorted(extra)))
    for col, rule in schema.items():
        if col not in df:
            continue
        s = df[col]
        if rule["dtype"] in ("float", "int"):
            num = pd.to_numeric(s, errors="coerce")
            bad_type = s.notna() & num.isna()
            if bad_type.any(): issues.append((col, "not numeric", s[bad_type].tolist()))
            if rule["dtype"] == "int":
                frac = num.notna() & (num % 1 != 0)
                if frac.any(): issues.append((col, "not an integer", num[frac].tolist()))
            out = num.notna() & ((num < rule["min"]) | (num > rule["max"]))
            if out.any(): issues.append((col, f"outside [{rule['min']}, {rule['max']}]", num[out].tolist()))
        else:
            unknown = s.notna() & ~s.isin(rule["allowed"])
            if unknown.any(): issues.append((col, "unknown category", sorted(set(s[unknown]))))
        nulls = s.isna().mean()
        if not rule["nullable"] and nulls > 0:
            issues.append((col, "nulls not allowed", f"{s.isna().sum()} rows"))
        elif nulls > max_null_share:
            issues.append((col, f"null share > {max_null_share:.0%}", f"{nulls:.0%}"))
    return issues

batch = pd.DataFrame({
    "income":     [4200.0, 3100.0, -50.0, 5600.0, None, 2900.0, 3800.0, 7100.0],
    "debt_ratio": [0.31, 0.22, 0.40, 31.0, 0.18, 0.27, 0.35, 0.12],
    "age":        [34, 51, 29, 44, 38, "unknown", 17, 62],
    "region":     ["north", "south", "South", "east", "west", "north", "west", "mars"],
    "employment": ["employed", None, "self", "employed", None, "retired", "employed", "employed"],
    "ssn":        ["x"] * 8,
})
print(f"batch of {len(batch)} rows")
for col, problem, detail in validate(batch, SCHEMA):
    print(f"  {col:11} {problem:24} {detail}")
batch of 8 rows
  table       unexpected columns       ['ssn']
  income      outside [0, 100000]      [-50.0]
  income      nulls not allowed        1 rows
  debt_ratio  outside [0.0, 1.5]       [31.0]
  age         not numeric              ['unknown']
  age         outside [18, 100]        [17.0]
  region      unknown category         ['South', 'mars']
  employment  null share > 5%          25%

Eight rows, eight findings: an unexpected column ssn (a social security number that should never reach the model, and a privacy problem), a negative income and a missing one, a debt ratio of 31.0 (probably sent in percent), an age written as 'unknown' and an underage applicant of 17, the categories 'South' (wrong case) and 'mars', and a quarter of the employment values missing while the schema allows at most 5 %. Note the order of checks for age: the type check converts with errors="coerce" and reports what cannot be converted, then the range check works on the numbers.

What to do with a failure depends on the stage. In a training pipeline, stop: a model trained on a batch with 31.0 debt ratios is worse than no new model. In batch scoring, quarantine the bad rows, score the rest, and alert. For online requests, reject the request with a clear error (see Pydantic below). Never "fix" silently (clipping, lowercasing) inside the validator; fixes belong in the documented preprocessing, so that training and serving apply them identically.

Distribution checks and training/serving skew

Training/serving skew is a difference between the data the model was trained on and the data it receives in production that comes from the system, not from the world: the serving code computes a feature differently (another unit, another time window, a different default for missing values), a lookup table is stale, or preprocessing was reimplemented in another language. It is one of the most common bug classes in deployed ML, and schema checks often miss it because the wrong values can still be in range.

The defence is a profile: summary statistics of every feature on the training data, stored with the model, and compared with each serving batch. The example profiles 5,000 training applicants (median and 99th percentile of income, mean and maximum debt ratio, region shares) and compares three batches of 500: a normal day, a day on which the serving code sends the debt ratio in percent, and a day on which incomes are 30 % higher.

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
def applicants(n, rng, debt_in_percent=False, income_shift=0.0):
    df = pd.DataFrame({"income": rng.lognormal(8.2 + income_shift, 0.4, n).round(0),
                       "debt_ratio": rng.beta(2, 5, n).round(3),
                       "region": rng.choice(["north", "south", "east", "west"], n, p=[0.4, 0.3, 0.2, 0.1])})
    if debt_in_percent:
        df["debt_ratio"] = (df["debt_ratio"] * 100).round(1)     # the serving code's unit bug
    return df

def profile(df):
    return {"income_median": df["income"].median(), "income_p99": df["income"].quantile(0.99),
            "debt_ratio_mean": df["debt_ratio"].mean(), "debt_ratio_max": df["debt_ratio"].max(),
            "region_shares": df["region"].value_counts(normalize=True).sort_index().round(3).to_dict()}

def compare(ref, new, rel_tol=0.25, share_tol=0.10):
    alerts = []
    for key in ("income_median", "income_p99", "debt_ratio_mean", "debt_ratio_max"):
        change = (new[key] - ref[key]) / abs(ref[key])
        if abs(change) > rel_tol:
            alerts.append(f"{key}: {ref[key]:.3g} -> {new[key]:.3g} ({change:+.0%})")
    for cat in set(ref["region_shares"]) | set(new["region_shares"]):
        a, b = ref["region_shares"].get(cat, 0), new["region_shares"].get(cat, 0)
        if abs(a - b) > share_tol:
            alerts.append(f"region={cat}: share {a:.2f} -> {b:.2f}")
    return alerts or ["no alerts"]

reference = profile(applicants(5000, rng))                     # computed once on the training data
print("reference:", {k: (v if isinstance(v, dict) else round(float(v), 3)) for k, v in reference.items()})
cases = {"normal day": applicants(500, rng),
         "serving sends debt in percent": applicants(500, rng, debt_in_percent=True),
         "incomes 30% higher": applicants(500, rng, income_shift=np.log(1.3))}
for name, batch in cases.items():
    print(f"{name}:")
    for a in compare(reference, profile(batch)):
        print("   ", a)
reference: {'income_median': 3601.0, 'income_p99': 9083.79, 'debt_ratio_mean': 0.287, 'debt_ratio_max': 0.882, 'region_shares': {'east': 0.199, 'north': 0.402, 'south': 0.299, 'west': 0.099}}
normal day:
    no alerts
serving sends debt in percent:
    debt_ratio_mean: 0.287 -> 27.8 (+9567%)
    debt_ratio_max: 0.882 -> 82 (+9197%)
incomes 30% higher:
    income_median: 3.6e+03 -> 4.53e+03 (+26%)

The normal day raises no alert. The unit bug is unmistakable: the mean debt ratio jumps from 0.287 to 27.8. Here the percent values (up to 82) would also break the schema's maximum of 1.5, but a subtler skew (a 30-day average where training used 90 days, say) stays inside every range and only a profile comparison shows it. The income shift moves the median by +26 %, just over the 25 % tolerance. That one may be real (inflation, a new customer segment) rather than a bug: a distribution alert asks a human to look, and the answer may be retraining rather than a fix.

The strongest protection against skew is structural: use one implementation of the feature code for training and serving (the model's scikit-learn Pipeline, a shared feature library, or a feature store), and log serving inputs so that they can be profiled.

Validating single requests with Pydantic

An online prediction service receives one JSON object per request. Pydantic, which FastAPI uses for request bodies, turns the schema into a class: types, constraints with Field(ge=..., le=...), allowed values with Literal, optional fields, and cross-field rules with a validator.

python · try it yourself
from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator

class LoanRequest(BaseModel):
    model_config = ConfigDict(extra="forbid")          # unknown fields are an error, not silently dropped
    income: float = Field(ge=0, le=100_000, description="monthly income")
    debt: float = Field(ge=0)
    age: int = Field(ge=18, le=100)
    region: Literal["north", "south", "east", "west"]
    employment: Optional[Literal["employed", "self", "unemployed", "retired"]] = None

    @model_validator(mode="after")
    def debt_not_absurd(self):
        if self.income > 0 and self.debt / self.income > 1.5:
            raise ValueError("debt is more than 1.5 times income")
        return self

ok = LoanRequest(income=4200, debt=1300, age="34", region="north")
print("valid:", ok.model_dump())

bad = {"income": -50, "debt": 900, "age": 17.5, "region": "mars", "extra_field": 1}
try:
    LoanRequest(**bad)
except ValidationError as e:
    for err in e.errors():
        print(f"  {'.'.join(map(str, err['loc'])):12} {err['type']:22} {err['msg']}")

try:
    LoanRequest(income=1000, debt=2000, age=40, region="west")
except ValidationError as e:
    print("  cross-field:", e.errors()[0]["msg"])
valid: {'income': 4200.0, 'debt': 1300.0, 'age': 34, 'region': 'north', 'employment': None}
  income       greater_than_equal     Input should be greater than or equal to 0
  age          int_from_float         Input should be a valid integer, got a number with a fractional part
  region       literal_error          Input should be 'north', 'south', 'east' or 'west'
  extra_field  extra_forbidden        Extra inputs are not permitted
  cross-field: Value error, debt is more than 1.5 times income

The valid request shows that Pydantic also coerces: the age "34" arrived as a string and became the integer 34 (Pydantic's default "lax" mode; strict=True would reject it). The invalid request gets one error per problem, each with a location, a machine-readable type and a message: income below 0, an age of 17.5 that is not an integer (17.5 is rejected before the range check), an unknown region, and the field extra_field, rejected because the model forbids extra fields (by default Pydantic would silently drop it). The last request has valid fields but violates the cross-field rule. In FastAPI, the same errors come back to the client as an HTTP 422 response with a detail list, before any model code runs.

Tools

Writing validators by hand teaches the ideas; libraries add a vocabulary of checks, reports and integrations. From memory (APIs change; check the docs):

  • pandera: schemas for pandas (and Polars, PySpark) data frames in Python: DataFrameSchema({"age": Column(int, Check.in_range(18, 100))}) or class-based models, schema.validate(df, lazy=True) to collect all failures. The closest to this lesson's from-scratch validator.
  • Great Expectations (GX): expectations such as expect_column_values_to_be_between grouped into suites, run against batches, with HTML data docs as reports; integrates with orchestrators and data warehouses.
  • TensorFlow Data Validation (TFDV): computes statistics of a dataset, infers a schema from them, and checks new data and serving data against it, including training/serving skew and drift comparators; part of TFX.
  • Others: Deequ (Spark, from AWS), Soda, dbt tests on warehouse tables, Evidently (reports and tests for data and model drift), and Pydantic or JSON Schema for single records.

Pitfalls

  • Validating only at training time. Serving data needs the same schema, and its batches need the profile comparison; that is where skew appears.
  • A schema inferred and never reviewed. Inferring ranges from today's data encodes today's bugs. Review inferred schemas, and widen them deliberately.
  • Alerts that cry wolf. Tight distribution tolerances on small batches fire every day and get ignored; base tolerances on the normal day-to-day variation, and on batch size.
  • Silent coercion. pd.to_numeric(errors="coerce") and Pydantic's lax mode turn bad values into NaN or convert them; count and report what was coerced.
  • Checking columns, not semantics. A debt ratio in percent passes a type check. Add ranges and profile checks that encode units.
  • Personal data in validation reports. Reports that print offending values can leak them; mask identifiers.

Practice

  1. Add a check to the from-scratch validator that a key column (say application_id) is unique, and say what a duplicate key usually means upstream.
  2. The training pipeline computes income as the average of the last 3 monthly salaries; the serving code uses the latest salary only. Which check could detect this, and why might the schema check not?
  3. Why should LoanRequest forbid extra fields instead of ignoring them?
Answers
  1. dup = df["application_id"].duplicated(keep=False); if dup.any(): issues.append(("application_id", "duplicate keys", sorted(set(df.loc[dup, "application_id"])))). Duplicates usually mean a join fanned out (one row matched several rows in another table) or a batch was loaded twice.
  2. A profile comparison: the latest salary has a larger spread than a 3-month average, so quantiles (the 99th percentile, the standard deviation) of serving inputs differ from the training profile, while every single value is still a plausible income inside the schema's range.
  3. An extra field is often a sign that the client and the service disagree about the contract (a renamed field, a new version of the client). Ignoring it hides the mismatch; with renamed fields, the old field may then be missing or defaulted. Rejecting it surfaces the problem at once.

Test yourself

What is training/serving skew?

  1. Any change in the world after training
  2. A difference between training and serving data caused by the system, for example a feature computed differently in serving
  3. A slow model server
  4. An imbalanced training set

Which check catches a category spelled 'South' when the schema allows 'south'?

  1. A range check
  2. An allowed-values (category) check
  3. A null check
  4. A uniqueness check

Pydantic received "age": "34" for an int field. What happened by default?

  1. A validation error
  2. It was coerced to the integer 34 (lax mode)
  3. It was dropped
  4. It became 0

A distribution check flags that the income median rose by 26 %. What is the right reaction?

  1. Always block the data
  2. Investigate: it may be a bug or a real change; a real change may call for retraining
  3. Ignore it, the schema passed
  4. Clip incomes to the old range