Sub topic 16
Responding to Skew: Triage, Rollback, Fix, Retrain
This chapter assumes you can read a PSI or KS alert, because earlier chapters covered detection. It also assumes you know the four causes of skew (duplicated feature code, fit-time state, differing data sources, time leakage). It covers what to do in the hours and days after an alert fires. The order is to confirm the alert, classify it, contain the damage, fix the root cause, and decide whether to retrain.
The response at a glance
Most teams lose time by jumping to one action, usually retraining, before they know what kind of problem they have. The sequence below keeps the cheap, reversible steps first.
Step 1: Confirm the alert is real
Check these before anyone is paged:
- Sample size. PSI and KS on a few hundred rows are noisy. KS p-values also become tiny on very large samples, so look at the statistic as well as the p-value.
- Window. Compare against the right training slice. A weekday-only training set compared with weekend traffic will alert without any bug.
- The logger itself. If the logging code changed (a renamed field, a new null encoding), the monitor reports skew that the model never saw.
- Scope. Is one feature affected, or all of them? One feature points to a transform or a source. All features point to a schema, join, or logging change.
The script below ranks features so you can see the scope at once. It also compares null rates, because a changed missing-value rule often shows up there first.
import numpy as np
import pandas as pd
from scipy.stats import ks_2samp
def psi(expected, actual, bins=10):
edges = np.unique(np.quantile(expected, np.linspace(0, 1, bins + 1)))
edges[0], edges[-1] = -np.inf, np.inf
e = np.clip(np.histogram(expected, edges)[0] / len(expected), 1e-6, None)
a = np.clip(np.histogram(actual, edges)[0] / len(actual), 1e-6, None)
return float(np.sum((a - e) * np.log(a / e)))
def triage(train_df, serving_df):
rows = []
for col in train_df.columns:
t, s = train_df[col].dropna(), serving_df[col].dropna()
rows.append({
"feature": col,
"psi": psi(t, s),
"ks": ks_2samp(t, s).statistic,
"null_rate_train": train_df[col].isna().mean(),
"null_rate_serving": serving_df[col].isna().mean(),
})
return pd.DataFrame(rows).sort_values("psi", ascending=False)
rng = np.random.default_rng(0)
train_df = pd.DataFrame({"age": rng.normal(40, 10, 5000),
"income": rng.normal(60, 15, 5000)})
serving_df = pd.DataFrame({"age": rng.normal(0, 1, 5000), # fill-with-0 bug
"income": rng.normal(60, 15, 5000)})
print(triage(train_df, serving_df).round(3))A common rule of thumb reads PSI below 0.1 as stable, 0.1 to 0.25 as worth watching, and above 0.25 as a major shift. These thresholds are conventions, not laws. Tune them against your own false-alarm history.
Step 2: Classify it as skew or drift
Both show up as "serving distribution differs from training," but they need different responses. One test separates them: replay the logged raw requests through the offline feature code and compare the result with the features the model actually received.
- If the replayed features differ from the served ones, the two paths disagree. This is skew.
- If they match, the pipelines agree and the inputs themselves changed. This is drift (or a genuine upstream data change).
import numpy as np
import pandas as pd
def mismatch_rates(offline_features, served_features, rtol=1e-6):
"""Fraction of rows where offline and served values disagree, per feature."""
out = {}
for col in offline_features.columns:
a = offline_features[col].to_numpy(dtype=float)
b = served_features[col].to_numpy(dtype=float)
out[col] = float((~np.isclose(a, b, rtol=rtol, equal_nan=True)).mean())
return pd.Series(out)
def offline_transform(raw):
return pd.DataFrame({"age": raw["age"].fillna(40.0)})
raw = pd.DataFrame({"age": [30, None, 50, None]})
served = pd.DataFrame({"age": [30, 0, 50, 0]})
print(mismatch_rates(offline_transform(raw), served)) # age 0.5Timing is a second clue. Skew often begins at a single deploy or upstream migration, so the metric jumps at one timestamp. Drift usually moves gradually or follows a calendar pattern. Check the deploy log against the first alerting window.
| Signal | Points to skew | Points to drift |
|---|---|---|
| Onset | Step change at a deploy or migration | Gradual, seasonal, or event-driven |
| Replay vs served | Mismatch | Match |
| Affected features | Specific features or all at once | Often correlated real-world features |
| Offline metrics on fresh labels | Fine when features are recomputed offline | Also degraded |
| Typical fix | Repair a pipeline | Retrain or redesign |
Step 3: Contain the damage
Containment buys time and does not fix anything. Pick the least disruptive option that stops the harm.
- Roll back the change that introduced the skew. This works only if the previous version is known-good. If the skew came from a feature pipeline or upstream table, rolling back the model does nothing, because the old model reads the same bad features. Roll back the thing that changed.
- Fall back. Route to a simpler model, a rules baseline, or a safe default decision while you investigate.
- Gate the broken feature. If the model tolerates missing values by design, serve the feature as missing and accept a small accuracy loss. Do this only if training included missing values for that feature.
- Do nothing yet. If impact is small and the fix is quick, a controlled fix beats a rushed rollback.
Weigh severity (money, safety, user-visible errors), the age of the last good version, and how many decisions are made while you wait. Record the decision and who made it.
Step 4: Fix the root cause
Match the fix to the cause you found.
| Cause | Fix |
|---|---|
| Duplicated feature code | Move to one shared transformation used by both paths |
| Fit-time statistics or vocabularies | Bundle preprocessing with the model artifact |
| Source, schema, or missing-value mismatch | Add serving-time validation and align the source |
| Time leakage | Rebuild training data with point-in-time joins |
Write the failing parity test first. Reproduce the bug with a test that fails, apply the fix, and watch the test pass. The test then stays in CI so the same skew cannot return unnoticed.
Step 5: Decide whether to retrain
The question is which side was wrong.
- Serving was wrong, training was right. In the fill-with-mean-versus-0 example, training used 40 and production used 0. Correct the serving code to use 40. The model never learned anything incorrect, so no retraining is needed.
- Training was wrong. If the training set contained leaked future information, the model learned a signal that does not exist at prediction time. Fixing serving cannot help. Rebuild the dataset with point-in-time joins and retrain.
- Both changed on purpose. If the new serving behavior is the better design, change training to match and retrain.
Do not retrain on logged serving features until the root cause is fixed. Joining labels to features produced by a buggy path teaches the model the bug. Rebuild the training features from raw data with the corrected shared code instead.Retraining is also the standard response to confirmed drift, but it needs fresh, correctly built labels and a validation comparison against the current model. Retraining alone cannot fix a pipeline mismatch.
Step 6: Verify and close out
- Release the fix through a shadow deployment, then a canary, and compare its logged features with the training distribution.
- Confirm PSI and KS for the affected features return below your thresholds, and that replay mismatch rates are near zero.
- Watch the business metric and delayed-label accuracy for long enough to see the recovery.
- Write a short postmortem: the cause, why monitoring caught it late or early, and the test, validation rule, or alert you added.
Exercise
A PSI alert fires on the feature account_age_days the day after a deploy of the feature service. Replaying logged raw requests through the offline code gives values that match the served features exactly, and the training distribution still differs from serving. Is this skew or drift, and what do you do first?
Show answer
Because replay matches served values, the two code paths agree, so this is not a pipeline mismatch. Check whether the deploy changed the upstream data or its meaning (for example a new source or unit) and whether the monitoring window is valid. If the data genuinely changed, treat it as drift or an upstream data change: evaluate whether the model still performs on fresh labels, and retrain if it does not. If the deploy itself altered the input, roll back that change.
Exercise
You find that training used a feature computed with data available only after the prediction time. Serving is correct. Should you roll back, fix serving, or retrain, and why?
Show answer
Retrain. The model learned from leaked information, so changing serving cannot help. Rebuild the training set with point-in-time joins, retrain, validate, then release through shadow and canary. Rolling back is only a temporary containment if the current model is causing harm and an earlier version is known to be sound.