Sub topic 4
Catching broken inputs: schema, missing values and ranges
This chapter assumes you can write Python with pandas and NumPy, and that you have deployed a model as a batch job or an API. It covers the first data-level layer of monitoring: checks that find inputs that are broken, which is different from inputs that have drifted.
Broken versus drifted
Drift means the real world changed. Customers get older, a new market opens, prices rise. The data is still valid, but it looks different from what the model saw in training.
A broken input is a pipeline fault. An upstream team renames a column, a join starts returning nulls, or a field switches from dollars to cents. Nothing about the world changed, but the model now receives garbage.
The two need different responses, and broken inputs are usually easier to catch. You can often detect them with a single row or a small batch, with no statistical test and no reference window. Drift tests such as KS and chi-square also fire on broken inputs. They report "distribution changed" and hide the cause. Running data quality checks first lets you tell the two cases apart.
The three families of checks
| Check | What it catches | Example failure |
|---|---|---|
| Schema | Wrong columns or types | `age` arrives as the string `"34"`, or a column is dropped |
| Missing values | Nulls above the normal rate | A join breaks and `income` is null for 40% of rows |
| Ranges and allowed values | Impossible or unseen values | `age` is 250, or `country` is `"UK"` when training only had `US`, `DE`, `FR` |
Schema checks
A schema check compares the incoming data to a contract: column names, data types, and sometimes column order. Check these items:
- Every required column is present.
- No unexpected columns appear. Extra columns are often harmless, but they signal that someone changed the upstream pipeline.
- Each column has the expected type. Numeric data parsed as text is the most common failure.
Many models fail loudly on a missing column, but a type problem can pass silently. For example, a pipeline may coerce unparseable strings to NaN, and then an imputer fills them with the training median. The model returns a confident score for every row, and every row is wrong.
Missing-value checks
Track the fraction of nulls per feature per window. The useful comparison is against the rate seen in training or in a healthy period. A feature that was 1% null in training and is now 30% null is a failure even if the model still runs.
Watch for nulls disguised as other values:
- Empty strings,
"N/A","null"and"unknown"in text columns. - Sentinel numbers such as
-999,0or9999that mean "not available". - A feature that is suddenly constant, which can be the result of silent imputation upstream.
Range and allowed-value checks
For numeric features, define a plausible minimum and maximum. For categorical features, define the set of allowed values. Count the fraction of values outside these limits instead of failing on one bad value, because real data always has a few outliers.
Take limits from two sources. Domain rules give hard limits, such as age cannot be negative. Training data gives soft limits, such as the 0.1st and 99.9th percentiles. A value beyond a soft limit is unusual but possible. A value beyond a hard limit is a bug.
Where the checks run
Place validation between the input source and the model, and decide in advance what happens when a check fails.
A batch validator
The function below checks a pandas DataFrame against a specification. It returns a list of human-readable issues, so the same function works in a batch job, a test, or an API handler.
import pandas as pd
SPEC = {
"age": {"kind": "numeric", "min": 18, "max": 100, "max_missing": 0.02},
"income": {"kind": "numeric", "min": 0, "max": 1_000_000, "max_missing": 0.05},
"country": {"kind": "categorical", "allowed": {"US", "DE", "FR"}, "max_missing": 0.0},
}
def validate_batch(df, spec, max_bad_fraction=0.01):
issues = []
for col, rule in spec.items():
if col not in df.columns:
issues.append(f"{col}: column missing")
continue
s = df[col]
if rule["kind"] == "numeric" and not pd.api.types.is_numeric_dtype(s):
issues.append(f"{col}: expected numeric, got {s.dtype}")
continue
missing = s.isna().mean()
if missing > rule["max_missing"]:
issues.append(f"{col}: {missing:.1%} missing (limit {rule['max_missing']:.1%})")
values = s.dropna()
if len(values) == 0:
continue
if rule["kind"] == "numeric":
bad = ((values < rule["min"]) | (values > rule["max"])).mean()
if bad > max_bad_fraction:
issues.append(
f"{col}: {bad:.1%} of values outside [{rule['min']}, {rule['max']}]"
)
else:
bad = (~values.isin(rule["allowed"])).mean()
if bad > max_bad_fraction:
issues.append(f"{col}: {bad:.1%} of values not in allowed set")
extra = sorted(set(df.columns) - set(spec))
if extra:
issues.append(f"unexpected columns: {extra}")
return issues
batch = pd.DataFrame({
"age": [34, 45, None, 29, 250, 52, 41, 38, 27, 60],
"income": [52000, -999, 61000, 48000, 75000, -999, 58000, 66000, 43000, 70000],
"country": ["US", "DE", "FR", "US", "UK", "DE", "US", "FR", "DE", "US"],
"promo": [1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
})
for issue in validate_batch(batch, SPEC):
print(issue)Running it prints five issues:
agehas 10.0% missing, over its 2.0% limit.agehas 11.1% of values outside the allowed range, caused by the 250.incomehas 20.0% of values outside its range, caused by the-999sentinels.countryhas 10.0% of values outside the allowed set, caused by"UK".- The batch has an unexpected
promocolumn.
Note that the -999 sentinel is caught by the range check, not by the missing-value check. If you only looked at null rates, income would look healthy.
Choosing limits
Derive limits from data instead of guessing. Compute them from the training set and a known-good production period, then review them with someone who knows the domain.
- Set
max_missinga little above the healthy rate, not at zero. If a feature is normally 2% null, a limit of 5% leaves room for noise. - Set
max_bad_fractionbased on how much bad data you can tolerate. Zero tolerance produces constant alerts. Too much tolerance hides real faults. - Review limits when you retrain. A new model may legitimately accept a wider range.
Small batches make fraction-based checks noisy. One bad row in a batch of ten is 10%. For low-volume services, aggregate over a time window, such as one hour, before evaluating the fractions.
Edge cases
- Type coercion upstream. Some readers convert bad values to NaN silently. Validate the raw data before the cleaning step, or you will only see inflated null rates.
- Unit and scale changes. Cents instead of dollars still passes a type check. A range check catches it if the limits are tight enough, and a drift test catches it later.
- New categories. An unseen category is not necessarily a bug, because a new product line may be real. Log it and treat it as a soft failure. Check how your encoder handles unknown values, since some raise errors and others map them to zeros.
- Legitimate missingness. Some features are null by design, such as "last purchase date" for new customers. Set per-feature limits and condition them on a segment if needed.
- Checks that never fail. If a limit has never fired, test it with a deliberately corrupted batch. A check you have not seen fail is a check you cannot trust.
Acting on a failed check
Pick a response per severity level. Reject the batch or use a fallback model for hard failures, such as missing required columns. For soft failures, score the data but attach a flag so you can analyze those predictions later. In every case, log the check results next to the predictions, so a drop in performance can be traced back to a bad input window.
Exercise
A feature tenure_months is 3% null in training. This week a monitor reports 3.4% null, and the range check shows 18% of values equal to 0, up from 2%. Which check family found the real problem, and what is the likely cause?
Show answer
The range (allowed-value) check found it. The null rate is within normal noise, but a jump in zeros suggests an upstream pipeline now writes 0 in place of missing values, a sentinel. The fix is to trace the upstream change, not to retrain the model.
Exercise
Why should you validate raw data before the cleaning step instead of only after it?
Show answer
Cleaning code may coerce bad values to NaN or impute them, which hides the original fault. Validating first lets you count the faults before they are masked.