Sub topic 8
Data drift and data volume triggers
This chapter covers two trigger families that react to the data itself: drift triggers, which fire when production inputs stop resembling the training data, and volume triggers, which fire when enough new data has arrived to make retraining worthwhile. It assumes you know the train, validate, test, deploy workflow, can read basic NumPy, and have seen PSI and the KS test introduced in the previous chapter. Here we focus on turning those statistics into reliable trigger signals.
Why data-based triggers exist
Performance triggers need labels, and labels often arrive late. A fraud label may take 60 days to confirm. A churn label may take a quarter. Data triggers use only what you have right now: the feature values flowing through the model. They are an early-warning signal, not proof that the model is worse.
That distinction drives the whole design:
- Drift says "the inputs changed." The model may or may not be hurt by it.
- Volume says "there is enough new data to learn from." It says nothing about whether the model needs it.
- Neither one replaces a performance check. They decide when to try retraining. The evaluation gate decides whether the result ships.
Choosing a reference window
Every drift statistic compares two samples. The choice of reference sample changes what the statistic means.
| Reference | What it measures | Weakness |
|---|---|---|
| Training data | Distance from what the model learned | Alerts stay on after you retrain unless the reference is updated |
| Trailing window (for example the previous 30 days) | Sudden change | Slow drift never accumulates enough difference to alert |
| Same period last year | Change after removing seasonality | Needs a year of history and breaks after a regime change |
For a trigger that decides on retraining, the training data is usually the right reference, because the question is "has the world moved away from what this model saw?" After each successful promotion, replace the reference with the new model's training data. If you forget, the trigger fires again right after deployment.
Computing drift per feature
The next example computes PSI and a KS test for one feature. PSI bins the reference data by its own quantiles, so each reference bin holds about the same share of rows. It then compares bin shares in the current data.
import numpy as np
from scipy.stats import ks_2samp
def psi(reference, current, bins=10):
"""Population Stability Index of one numeric feature."""
reference = np.asarray(reference, dtype=float)
current = np.asarray(current, dtype=float)
edges = np.unique(np.quantile(reference, np.linspace(0, 1, bins + 1)))
edges[0], edges[-1] = -np.inf, np.inf
ref_pct = np.histogram(reference, bins=edges)[0] / len(reference)
cur_pct = np.histogram(current, bins=edges)[0] / len(current)
ref_pct = np.clip(ref_pct, 1e-6, None)
cur_pct = np.clip(cur_pct, 1e-6, None)
return float(np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct)))
rng = np.random.default_rng(0)
reference = rng.normal(0.0, 1.0, 10_000)
current = rng.normal(0.5, 1.0, 10_000)
print("PSI:", round(psi(reference, current), 3))
result = ks_2samp(reference, current)
print("KS statistic:", round(result.statistic, 3), "p-value:", result.pvalue)A shift of half a standard deviation produces a PSI well above the common 0.2 alert level. Common rules of thumb read PSI below 0.1 as stable, 0.1 to 0.25 as moderate change, and above 0.25 as major change. These are conventions from credit scoring, not laws. Calibrate them on your own history.
PSI versus the KS test as a trigger
The two statistics behave differently at scale, and that matters for triggers.
- KS p-value. With large samples, the p-value becomes tiny for differences nobody cares about. With 10 million rows, a shift of 0.001 standard deviations can be "significant." A p-value threshold will fire constantly.
- KS statistic. The statistic itself (the maximum gap between the two cumulative distributions) does not grow with sample size. Thresholding it is more stable than thresholding the p-value.
- PSI. It measures effect size, so it does not inflate with volume. But with small current samples, PSI is noisy because sparse bins swing the log ratio.
Trigger on an effect-size number (PSI or the KS statistic). Use the p-value, if at all, as a secondary check on small windows.
From many features to one signal
A model with 200 features produces 200 drift scores. You need one decision. Three common aggregations:
- Maximum. Fires if any feature drifts. Sensitive, and prone to false alarms with many features.
- Weighted by importance. Weigh each feature's PSI by its model importance. A drifting feature the model barely uses should not trigger a retrain.
- Count above threshold. Fires when at least k features exceed the limit. Resists single-feature noise such as one broken upstream column.
A single feature that jumps to extreme drift often means a pipeline bug, such as a unit change or a column filled with nulls, not a real-world shift. Retraining on that data makes things worse. Route such cases to an alert for a human, and let the data validation stage (covered later in this tutorial) block the retrain.
Handling edge cases in drift detection
- Small windows. Require a minimum number of current rows before computing PSI. Below roughly 1,000 rows per feature with 10 bins, scores are mostly noise.
- Seasonality. Weekday traffic differs from weekend traffic. Compare equal-length windows that cover whole weeks, or the trigger fires every Monday.
- Missing values. Compute the null rate as its own drift signal. Dropping nulls before PSI hides the most common real-world failure.
- Constant features. If the reference has fewer unique values than bins,
np.uniqueshrinks the edge list. The code above handles this, but check that at least two bins remain. - Repeated alerts. Drift that persists keeps firing every check. Debounce it by requiring the condition on several consecutive windows, and by applying a cooldown after each retrain.
Data volume triggers
A volume trigger says "retrain once N new labeled rows have accumulated." It suits cases where more data directly improves the model, such as a recommender with growing catalogs or a text classifier with new labeled examples.
Count the right thing:
- Count labeled rows, not raw events. If only 5% of events get labels, 1 million events is 50,000 usable rows.
- Count new rows since the last training cutoff, not total table size.
- Consider class balance. 50,000 new rows with five positives will not help a rare-event model.
Volume works best as a gate on other triggers instead of a trigger alone. Drift with only 2,000 new rows means you would be retraining on too little data to represent the new distribution. The policy below combines these ideas, along with a maximum model age and a cooldown.
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@dataclass(frozen=True)
class TriggerConfig:
psi_threshold: float = 0.2
min_new_rows: int = 50_000
max_model_age: timedelta = timedelta(days=30)
cooldown: timedelta = timedelta(days=2)
def should_retrain(now, last_trained, max_feature_psi, new_rows, cfg):
"""Return (decision, reason) from schedule, drift, and volume signals."""
age = now - last_trained
if age < cfg.cooldown:
return False, "cooldown"
if age >= cfg.max_model_age:
return True, "max_model_age"
if max_feature_psi >= cfg.psi_threshold and new_rows >= cfg.min_new_rows:
return True, "drift_with_enough_data"
return False, "no_trigger"
now = datetime(2026, 11, 30, tzinfo=timezone.utc)
last = now - timedelta(days=10)
print(should_retrain(now, last, 0.31, 80_000, TriggerConfig()))This call returns (True, 'drift_with_enough_data'): the model is 10 days old, past the 2-day cooldown, PSI is 0.31, and 80,000 new rows exceed the 50,000 minimum. Returning a reason string matters. Log it with every decision, including "no_trigger," so you can later explain why a retrain did or did not happen.
Common errors
- Thresholding the KS p-value on large data. The trigger fires constantly. Use an effect-size measure.
- Never refreshing the reference. After a retrain, the old reference still shows drift and the trigger loops. Update it on promotion.
- Treating drift as proof of harm. Retraining on drift alone can ship a model that is no better. Always send the result through the evaluation gate.
- Ignoring upstream bugs. A broken pipeline looks like extreme drift. Check data quality before you retrain on it.
- Counting unlabeled rows toward volume. The model cannot train on them.
Exercise
A fraud model has 120 features. Your drift trigger uses the maximum PSI across features and fires about twice a week, but the evaluation gate rejects almost every challenger. Name two changes to the drift signal and one change to the policy that would reduce wasted retraining runs.
Show answer
Signal changes: (1) weigh each feature's PSI by its model importance, or require at least k features above the threshold, so one low-value or broken feature cannot fire the trigger; (2) require the condition on several consecutive windows to filter noise. Policy change: add a minimum number of new labeled rows and a cooldown, so drift alone with little data cannot start a run. Also check that the reference is refreshed after each promotion.
Exercise
A dataset has 10 million rows per window. A KS test on one feature returns p = 1e-30, but the KS statistic is 0.004. Should this fire a retraining trigger? Why?
Show answer
No. The p-value is tiny only because the sample is huge. A KS statistic of 0.004 means the two cumulative distributions differ by at most 0.4 percentage points, which is a negligible effect. Threshold the statistic (or PSI), not the p-value.