Sub topic 13
Detection: log the features the model actually received
This chapter assumes you can write Python and pandas, know the train, validate, predict workflow, and have a rough picture of a model served behind an API or batch job. It also assumes you know what a histogram, a mean, and a variance are.
The earlier chapters covered how skew gets in and how to prevent it. Prevention is never complete. A new upstream service, a schema change, or a code path nobody tested can still produce features that differ from training. You can only detect that if you have a record of what the model saw. This chapter is about building that record.
Why the request is not enough to log
The first idea is usually to log the incoming request. That is useful for debugging, but it is not what the model consumed. Between the request and the model there is a transformation step: parsing, imputation, scaling, encoding, joins against a feature store. Skew often lives in that step.
Consider the missing-age bug from earlier in this tutorial. The request contained "age": null. If you log only the request, the log shows a null, which looks fine. The model received 0, and training had 40. Only a log of the post-transformation values shows the problem.
You usually want two layers:
| Layer | What it holds | What it answers |
|---|---|---|
| Raw request | The payload as received | Did the caller send what we expect? Can we replay this request? |
| Model input | The feature values after all transforms, exactly as passed to `predict` | Does the model see the same distribution it was trained on? |
| Model output | Prediction, score, model version | Did predictions shift, and which model produced them? |
Logging the model input is the one that detects skew. The raw request helps you find the cause once you know there is a problem.
What a useful log record contains
Each record should let you compare serving data with training data later. A minimal set of fields:
- A request identifier, so you can join the record to later labels.
- A timestamp in UTC, so you can slice by time window and apply point-in-time rules.
- The model name and version, and the version of the feature or preprocessing code.
- The feature values, with the same column names used in training.
- The prediction and, for classifiers, the score.
- Optionally the raw request, or a reference to where it is stored.
Record the feature names exactly as training defines them. If the training set calls a column logins_30d and the log calls it logins_30_days, every later comparison needs a mapping, and mappings rot.
The following sketch logs one structured JSON line per prediction. It works with the bundled pipeline shown earlier in the tutorial, so features is the frame that is passed to the model.
import json
import logging
import time
import uuid
import pandas as pd
logger = logging.getLogger("serving.features")
logging.basicConfig(level=logging.INFO, format="%(message)s")
MODEL_VERSION = "churn-2026-11-01"
def predict_and_log(model, features: pd.DataFrame, raw_request: dict) -> float:
"""Score one row and log the features the model actually received."""
score = float(model.predict_proba(features)[0, 1])
record = {
"request_id": str(uuid.uuid4()),
"ts": time.time(),
"model_version": MODEL_VERSION,
"features": features.iloc[0].to_dict(),
"score": score,
"raw_request": raw_request,
}
logger.info(json.dumps(record, default=str))
return scoreFor this to be useful, features must be the frame built from the same transformation that the model uses. If your pipeline is bundled inside the model artifact, the preprocessed matrix is internal to the pipeline. In that case, log the input columns to the pipeline (the pre-bundled frame) and also consider logging a few intermediate values, such as the imputed numeric columns, by calling model.named_steps["preprocess"].transform(features) on a sampled subset.
The logging path must not create new skew
A logging step that changes values is itself a source of skew. Watch for these:
- Logging before the transform. The log shows values the model never saw.
- Rounding or truncating. Storing floats with two decimals hides small shifts, and storing strings can change types.
- Dropping nulls silently. Some serializers omit null keys. A missing key and a null both need to appear as nulls, or you cannot count missing values.
- Logging a different code path. If a fallback route (for example a cached prediction) skips the log call, the sample is biased.
Sampling, volume, and cost
Logging every feature of every request can be expensive and may carry personal data. Three controls help.
- Sample. For distribution comparisons, a uniform random sample of a few thousand rows per day per feature is often enough. Sample by request, not by feature, so rows stay intact and you can still examine feature combinations.
- Log always on errors and anomalies. Keep every record where validation failed or the score was extreme. A uniform sample would miss them.
- Minimize and protect sensitive fields. Hash or drop identifiers you do not need, and apply the same access controls and retention limits as for the training data.
Keep the sampling rate in the record or in configuration, so later analysis can weight correctly when you combine uniform samples with always-logged rare cases.
Where the logs go and how they are shaped
Write logs to storage that you can query in bulk, such as object storage with partitioned files, or a warehouse table. Partition by date and model version. You will compare a time window of serving data against a fixed reference, so being able to read "all records for model X on day D" cheaply matters more than real-time access.
The reference is the training data, or a snapshot of the features at the time of training. Save it with the model. A summary is often enough: for numeric features, the quantile edges and counts; for categorical features, the category frequencies and the share of missing values. A snapshot saved at training time is stable, while recomputing it later from a table that has since changed gives a different baseline.
A first look: simple checks on the log
Before running a distribution test, simple summaries already catch many bugs. Load a day of logged features and compare a few statistics with the training reference.
import pandas as pd
def summarize(df: pd.DataFrame, numeric_cols: list[str]) -> pd.DataFrame:
rows = []
for col in numeric_cols:
s = df[col]
rows.append({
"feature": col,
"null_rate": s.isna().mean(),
"mean": s.mean(),
"std": s.std(),
"min": s.min(),
"max": s.max(),
})
return pd.DataFrame(rows).set_index("feature")
train = pd.DataFrame({"age": [30, 40, 40, 50], "income": [50, 60, 55, 70]})
serving = pd.DataFrame({"age": [0, 0, 41, 0], "income": [52, 61, 58, None]})
report = summarize(train, ["age", "income"]).join(
summarize(serving, ["age", "income"]), lsuffix="_train", rsuffix="_serve"
)
print(report.T)Here the serving mean of age is about 10 against a training mean of 40, and income has a null rate of 25% in serving against 0% in training. Neither number needs a statistical test to be worrying. The next chapter turns these comparisons into formal metrics.
What to compare
Compare per feature first. Per-feature checks are easy to read and point to a cause. Look at:
- Null rate and the share of any sentinel value such as
0or-1. - Mean, spread, minimum, maximum, and selected quantiles for numeric features.
- Category frequencies for categorical features, and the share of values not seen in training.
- Type and range violations.
Also compare the prediction distribution. If the average score moves while individual features look stable, the cause may be an interaction between features, a changed model version, or drift rather than skew.
Gotchas
- Serving traffic is not training data. The population can differ legitimately, for example when the model is rolled out to a new region. A difference is a reason to investigate, not proof of a bug. The chapter on skew versus drift covers how to tell them apart.
- Delayed labels. Logged features have no label at logging time. Keep the request identifier so you can join labels when they arrive. Label joins must respect time: use the feature values as logged, not recomputed ones, which are the recomputation trap that point-in-time joins avoid.
- Feature-store lookups. Log the values actually returned by the lookup, including nulls from missing entities or stale entries. Do not log the value you expected.
- Logging cost on the hot path. Write logs asynchronously or to a queue so a slow log sink does not add latency or cause failed predictions.
- Version drift in the log schema. When you add or rename a feature, bump the feature version in the record. Otherwise, a window containing both versions looks like a distribution shift.
Summary of the practice
Log the transformed model input, tagged with model version, timestamp, and request identifier. Use the training column names. Sample uniformly, keep anomalies separately, protect sensitive fields, and store the training reference alongside the model. With these in place, detecting skew becomes a query rather than an investigation.
Exercise
A service logs the incoming JSON request for every prediction but not the features passed to the model. A bug fills missing age values with 0 during preprocessing, while training filled them with the mean of 40. Why does the request log fail to reveal this bug, and what should be logged instead?
Show answer
The request log shows age as null, which looks the same as in training data, because the bug happens after the request is received, in the transformation step. The model input is the 0, and only a log of the post-transformation features (the values passed to predict, with training column names, model version, timestamp, and request identifier) shows the mean of age falling from about 40 to near 0 and the spike at the sentinel value.
Exercise
Your team samples 1% of requests uniformly for the feature log and also keeps every request that failed validation. Why should the two sets be kept separate when you estimate the normal serving distribution of a feature?
Show answer
Records that failed validation are over-represented by design, since all of them are kept while normal requests are sampled at 1%. Mixing them in makes unusual values appear more common than they really are, so the estimated serving distribution looks more different from training than it is. Use the uniform sample for the distribution estimate and use the failure records for debugging and for counting failure rates.