Sub topic 11
Prevention: Validate Inputs at Serving Time
This chapter assumes you know basic Python and pandas, and the earlier chapters on how training and serving paths differ and on shared transformations. You should also know how a model is called behind an API or batch job.
Shared code and bundled pipelines make the transformation identical in both paths. They do not control the raw data that reaches the transformation. If a client sends "41" instead of 41, renames a field, or sends 0 for a missing age, a perfectly shared pipeline will process the bad value and return a prediction. Input validation is the check at the serving boundary that catches these cases before they become silent skew.
Why the serving boundary needs its own check
During training you look at the data. You see the dtypes, the null counts, and the ranges. In production nobody looks at each request, and upstream teams change schemas without telling you. The model will accept almost any numeric input, so a wrong value produces a plausible-looking probability instead of an error.
Validation turns an unknown failure into a known one. Each request is checked against a contract derived from the training data, and a violation is either rejected or recorded.
The table lists what to check and which skew each check catches.
| Check | Example violation | Skew it catches |
|---|---|---|
| Required fields present | `country` missing from the payload | A renamed or dropped upstream field |
| Type | `"41"` (string) where a number is expected | A serialization change in the client |
| Nullability | `null` income when training had no nulls | A new source of missing values |
| Range | `age = 400`, or `age = 0` when training had 30 to 50 | Unit changes, sentinel values, fill-with-0 bugs |
| Allowed categories | Country `"BR"` never seen in training | A new market or a changed encoding |
| Unexpected fields | `income_usd` appears alongside `income` | A schema change nobody announced |
Derive the contract from training data
Do not write the schema by hand in the serving code. Compute it from the training data when you fit the model, and save it next to the model artifact. Then the schema and the model always share a version. This is the same principle as bundling preprocessing: anything fitted at training time travels with the model.
A schema has two kinds of numeric limits.
- Observed limits are the minimum and maximum seen in training. A value outside them is unusual but may be legitimate, so it produces a warning.
- Hard limits come from domain knowledge, such as an age between 0 and 120. A value outside them is impossible, so it produces an error.
The following example needs only pandas and the standard library.
import json
import math
import pandas as pd
def build_schema(df, numeric, categorical, hard_limits):
"""Derive a serving contract from the training DataFrame."""
columns = {}
for col in numeric:
s = df[col]
low, high = hard_limits[col]
columns[col] = {
"type": "numeric",
"nullable": bool(s.isna().any()),
"min": float(s.min()),
"max": float(s.max()),
"hard_min": float(low),
"hard_max": float(high),
}
for col in categorical:
s = df[col]
columns[col] = {
"type": "categorical",
"nullable": bool(s.isna().any()),
"allowed": sorted(s.dropna().unique().tolist()),
}
return {"columns": columns}
def validate_request(request, schema):
"""Return (errors, warnings). Errors mean the request must not be scored."""
errors, warnings = [], []
columns = schema["columns"]
for name in request:
if name not in columns:
warnings.append(f"unexpected field: {name}")
for name, spec in columns.items():
if name not in request:
errors.append(f"missing field: {name}")
continue
value = request[name]
if value is None or (isinstance(value, float) and math.isnan(value)):
if not spec["nullable"]:
errors.append(f"{name}: null not allowed")
continue
if spec["type"] == "numeric":
if isinstance(value, bool) or not isinstance(value, (int, float)):
errors.append(f"{name}: expected number, got {type(value).__name__}")
elif not math.isfinite(value) or not spec["hard_min"] <= value <= spec["hard_max"]:
errors.append(f"{name}: {value} outside hard limits")
elif not spec["min"] <= value <= spec["max"]:
warnings.append(
f"{name}: {value} outside training range [{spec['min']}, {spec['max']}]"
)
elif value not in spec["allowed"]:
warnings.append(f"{name}: unseen category {value!r}")
return errors, warnings
train = pd.DataFrame({
"age": [30, 40, None, 50],
"income": [3000, 4200, 5100, 6000],
"country": ["DE", "FR", "DE", "US"],
})
schema = build_schema(
train,
numeric=["age", "income"],
categorical=["country"],
hard_limits={"age": (0, 120), "income": (0, 10_000_000)},
)
# Save the schema in the same directory as model.joblib
with open("schema.json", "w") as f:
json.dump(schema, f, indent=2)
print(validate_request({"age": 35, "income": 4500, "country": "FR"}, schema))
print(validate_request({"age": 0, "income": 4500, "country": "BR"}, schema))
print(validate_request({"age": "41", "income": None}, schema))The three calls print:
([], [])
([], ["age: 0 outside training range [30.0, 50.0]", "country: unseen category 'BR'"])
(['age: expected number, got str', 'income: null not allowed', 'missing field: country'], [])The second request is the fill-with-0 bug from the start of this tutorial. The value 0 is a legal age, so a hard-limit check alone would pass it. The observed range of 30 to 50 flags it. Age is nullable in the training data, so a real None is accepted, while a 0 that stands in for a missing value is not.
Decide what happens on a violation
A validator is only useful if each outcome has a defined behavior. Three options exist, and you can use different ones for different checks.
- Reject. Return an error (HTTP 422, or a dead-letter record in a batch job) and do not call the model. Use this for missing fields, wrong types, and impossible values. The caller learns about the problem immediately.
- Score and flag. Return the prediction, but log the warning with the request ID. Use this for out-of-range values and unseen categories, where the model can still produce a reasonable answer.
- Substitute a default. Replace the bad value and continue. Use this only for a documented, tested case, such as treating a missing optional field the way training did.
Handle missing values explicitly
Missing data is the most common source of quiet skew. Set the policy per field and record it in the schema, as the nullable flag does above.
- If a field never had nulls in training, a null at serving time is an error. The imputer you fitted never saw a null, so its behavior is not tested.
- If a field had nulls in training, accept null but do not accept sentinels such as
0,-1, or"N/A". Validate those through range and category checks. - Track the null rate per field in production. A field that was 2% null in training and is 40% null today needs attention even if every individual request is valid.
Common errors
- Validating only types. Type checks pass for
age = 0. Add range and null-rate checks. - Hand-written schemas that drift. If the schema is edited separately from the model, it will no longer describe the data the model was trained on. Generate and version it with the model.
- Hard limits that are really observed limits. If you reject everything outside the training range, you will reject legitimate new users. Keep errors for impossible values and warnings for unusual ones.
- Rejecting without alerting. A rising reject rate is a signal. If nobody watches it, the API fails quietly in a different way. Alert on the reject rate and on the warning rate per field.
- Validating after transformation. Check the raw request before the pipeline. After one-hot encoding, an unseen category has already become a row of zeros and cannot be detected.
- Treating validation as detection of drift. Per-request checks find broken data. They do not notice that the average age shifted from 40 to 36. Distribution comparison, covered in a later chapter, handles that.
Where this fits
Validation covers the data-source and schema causes of skew. It does not fix duplicated feature code or fit-time state, which shared transforms and bundled pipelines address. Think of it as the guard at the door: it makes sure that what enters the shared pipeline is the kind of data the pipeline was built for. The counters it produces also feed the logging and monitoring described next.
Exercise
Your training data for income ranged from 3,000 to 6,000 and had no nulls. After a client update, serving requests start arriving with income = -1 to mean "unknown". Which checks in the schema above would catch this, and should the request be rejected or scored with a warning?
Show answer
With hard limits of 0 to 10,000,000, -1 falls outside the hard limits, so it produces an error and the request is rejected. If it passed the hard limits, the observed range of 3,000 to 6,000 would flag it as a warning. Rejecting is the right choice because -1 is a sentinel, not a real income, and the model would treat it as a very low income. The reject counter for income then shows the client change, and the fix belongs upstream: either the client sends a real null (which also fails, since income is not nullable) or the schema and training pipeline are updated together to handle missing income.
Exercise
Why should the schema be saved with the model artifact rather than defined in the serving code?
Show answer
The schema describes the data the model was trained on, so it must change whenever the model is retrained. Saving it with the artifact gives both a single version. Rolling back the model also rolls back the schema, and the validator can never enforce limits that belong to a different model.