Sub topic 11
Prevention: Validate Inputs at Serving Time
Assume you know basic Python and pandas, have trained a supervised model, and understand how an API or batch job calls a model. This chapter focuses on validating the data that reaches the model. Validation does not replace shared feature logic, but it prevents many source, schema, and missing-value differences from becoming silent skew.
Why serving validation matters
A model expects a feature contract. A feature contract describes the fields, data types, allowed values, units, ranges, and missing-value rules that were used during training.
Without validation, a request can contain:
- A missing required field.
- A string where the model expects a number.
- An age in months when training used years.
- An unknown category.
- A value outside the range seen during training.
- A missing value handled differently from the training pipeline.
Some errors produce an API failure. More dangerous errors produce a valid prediction from an invalid feature. For example, the string "$80,000" might be converted incorrectly, or a missing age might become zero even though training used the median age.
| Contract rule | Example | Typical response |
|---|---|---|
| Required field | `age` must be present | Reject the request |
| Type | `income` must be numeric | Reject or quarantine |
| Range | `age` must be 0 through 120 | Reject and alert |
| Category | `country` must be a known value | Map only if training defines a safe unknown value |
| Missingness | `income` may be missing | Apply the same training-time rule |
Validate before prediction
Keep validation close to the model entry point. The validator should return normalized features only after every rule passes. It should not silently invent defaults unless that default is part of the fitted training pipeline.
from numbers import Real
ALLOWED_COUNTRIES = {"US", "CA", "GB"}
def validate_request(request: dict) -> dict:
required = {"age", "income", "country"}
missing = required - request.keys()
if missing:
raise ValueError(f"Missing fields: {sorted(missing)}")
age = request["age"]
income = request["income"]
country = request["country"]
if isinstance(age, bool) or not isinstance(age, Real):
raise ValueError("age must be numeric")
if not 0 <= age <= 120:
raise ValueError("age must be between 0 and 120")
if income is None or isinstance(income, bool) or not isinstance(income, Real):
raise ValueError("income must be a numeric value")
if income < 0:
raise ValueError("income must not be negative")
if country not in ALLOWED_COUNTRIES:
raise ValueError("country is not in the training vocabulary")
return {
"age": float(age),
"income": float(income),
"country": country,
}
request = {"age": 42, "income": 72000, "country": "US"}
features = validate_request(request)
print(features)The allowed country set must come from the training vocabulary, not from whatever categories happen to appear in recent requests. If the model was trained with an explicit unknown category, the validator can map unsupported values to that category. Otherwise, rejection is safer than silently changing the feature.
Where validation fits
Validation catches malformed or incompatible inputs. It cannot prove that a feature has the correct point-in-time meaning, nor can it detect every distribution shift. Pair it with offline/online parity tests and monitoring of logged serving features.
Exercise
The training pipeline filled missing income with the training median, but the serving validator rejects missing income. Is this automatically a bug?
Show answer
Yes, if missing income was an allowed production case. The serving path must apply the same fitted imputation rule or deliberately reject that case in both the contract and the client workflow.