Sub topic 4
Catching broken inputs: schema, missing values and ranges
This chapter assumes you can write basic Python with pandas, and that you have deployed a model as a batch job or an API. Data quality checks are the cheapest monitoring layer. They catch pipeline bugs before you spend time on drift statistics.
Why check inputs before testing for drift
A drift test asks whether the distribution of a feature has changed. A data quality check asks whether the feature is valid at all. These are different questions. A unit change from dollars to cents looks like drift, but the cause is a bug and the fix is in the pipeline, not a retrain.
Broken inputs often produce no error. The model still returns a prediction, and it is wrong. Quality checks run before the model and give you a clear failure instead of a quiet one.
The three checks
| Check | Question | Typical cause of failure |
|---|---|---|
| Schema | Are the expected columns present with the expected types? | Upstream rename, type change, dropped column |
| Missing values | Is the share of nulls within normal bounds? | Broken join, failed sensor, new default |
| Ranges | Are numeric values and categories within allowed limits? | Unit change, sentinel values, new category |
Schema
Compare each incoming frame to an expected column list and dtypes. Missing columns and wrong types are hard failures. Extra columns are usually only a warning.
Missing values
Track the null rate per feature and compare it to the rate in your reference data. A feature that is 1% null in training and 40% null today is a strong sign of a broken source. Be careful with imputation. If the pipeline fills nulls with a default, the null rate drops to zero and hides the problem. Check nulls before imputing, or monitor how often the default is used.
Ranges
For numeric features, set minimum and maximum bounds from domain knowledge, such as age between 0 and 120. Training data can suggest limits, but widen them a little so rare valid values do not trigger alerts. For categorical features, check values against the known set and count unseen categories.
A reusable validator
The function below returns a list of problems for one batch. It is plain pandas, so it runs anywhere.
import numpy as np
import pandas as pd
EXPECTED = {"age": "int64", "income": "float64", "plan": "object"}
MAX_NULL_RATE = {"age": 0.01, "income": 0.05, "plan": 0.0}
RANGES = {"age": (0, 120), "income": (0.0, 1_000_000.0)}
CATEGORIES = {"plan": {"free", "basic", "pro"}}
def validate(df: pd.DataFrame) -> list[str]:
problems = []
for col, dtype in EXPECTED.items():
if col not in df.columns:
problems.append(f"missing column: {col}")
continue
if str(df[col].dtype) != dtype:
problems.append(f"{col}: dtype {df[col].dtype}, expected {dtype}")
null_rate = df[col].isna().mean()
if null_rate > MAX_NULL_RATE[col]:
problems.append(f"{col}: null rate {null_rate:.2%}")
for col, (lo, hi) in RANGES.items():
if col in df.columns:
bad = ((df[col] < lo) | (df[col] > hi)).mean()
if bad > 0:
problems.append(f"{col}: {bad:.2%} outside [{lo}, {hi}]")
for col, allowed in CATEGORIES.items():
if col in df.columns:
unseen = set(df[col].dropna().unique()) - allowed
if unseen:
problems.append(f"{col}: unseen categories {sorted(unseen)}")
return problems
batch = pd.DataFrame(
{
"age": [34, 51, -1, 29],
"income": [52000.0, np.nan, 61000.0, 48000.0],
"plan": ["free", "pro", "gold", "basic"],
}
)
for problem in validate(batch):
print(problem)On this batch the function reports a 25% null rate for income, one out-of-range age, and the unseen category gold.
Common mistakes
- Checking only the schema. A column can have the right type and still hold all zeros.
- Using hard failures for everything. Reject a batch for a missing column, but only warn on a small rise in null rate.
- Setting bounds from the training maximum. Valid future values then raise alerts.
- Dropping bad rows silently. Log them, or quarantine them, so you can see what the pipeline is producing.
Exercise
A feature income is 2% null in the reference data. After a deployment, the pipeline fills nulls with 0 before the model runs, and the null rate your monitor sees is 0%. Why is this a problem, and where should the null check run?
Show answer
Filling nulls with 0 hides a possible upstream failure, and it creates a spike of fake zero values that the model treats as real incomes. The null check should run before imputation, or you should monitor how often the default value is applied, so a rise in missing data still triggers an alert.