Sub topic 1
Why a model can look good offline and fail in production
A churn model scores 0.94 AUC on the validation set. A month after launch, the same model performs barely better than a coin flip. Nothing crashed, and the code is the same. The usual cause is that the training data contained information that did not exist yet when the prediction would have been made. This is temporal data leakage, and this chapter explains how it happens and why it is hard to see. It also covers what to look for. Later chapters build the tools that prevent it.
Prerequisites
This chapter assumes you already know:
- Basic supervised machine learning: features, labels, and a train/validation split.
- SQL joins and window functions.
- Basic pandas DataFrame operations.
- Timestamps and time zones, including the difference between a local time and UTC.
You do not need any feature store or MLOps tooling. All examples use plain pandas and SQL.
What temporal leakage is
Temporal data leakage happens when a training row contains a feature value that was not yet known at the moment the model would have made its prediction. The model learns a pattern that depends on that future information. At serving time the information is not available, so the pattern disappears.
Every prediction has a prediction time. It is the moment the system must decide, such as "will this customer churn in the next 30 days?" asked on 1 February. A feature is legitimate for that row only if its value was knowable at or before that moment. Anything computed from later events is leakage, even if the column name looks harmless.
Leakage is not the same as ordinary overfitting. An overfit model does poorly on held-out data from the same period. A leaky model can do very well on held-out data, because the held-out rows leak in the same way as the training rows. Standard validation cannot detect it.
A concrete example
Suppose a customer's tickets_total counts lifetime support tickets. The feature table stores one row per day or per update. The label table records that customer 1 churned after the prediction time of 1 February.
The mistake is to join each label row to the latest feature value instead of the value as of the prediction time.
import pandas as pd
features = pd.DataFrame({
"customer_id": [1, 1, 1],
"feature_ts": pd.to_datetime(["2026-01-01", "2026-02-01", "2026-03-01"]),
"tickets_total": [0, 1, 6],
})
labels = pd.DataFrame({
"customer_id": [1],
"prediction_ts": pd.to_datetime(["2026-02-01"]),
"churned": [1],
})
# Leaky: take the newest feature row for each customer, whatever its timestamp.
latest = (
features.sort_values("feature_ts")
.groupby("customer_id")
.tail(1)[["customer_id", "tickets_total"]]
)
leaky = labels.merge(latest, on="customer_id")
# Correct: take the newest row at or before the prediction time.
correct = pd.merge_asof(
labels.sort_values("prediction_ts"),
features.sort_values("feature_ts"),
left_on="prediction_ts",
right_on="feature_ts",
by="customer_id",
direction="backward",
)
print(leaky[["customer_id", "tickets_total"]])
print(correct[["customer_id", "tickets_total"]])The leaky join returns tickets_total = 6. The correct join returns 1. The six tickets include five that were filed during the weeks when the customer was already unhappy and leaving. The model learns that "many tickets means churn". That pattern is real, but the model could not have used it on 1 February, when the count was 1.
The code runs without errors in both cases. Nothing in pandas warns you that the first join is wrong. The row count is the same, the types are the same, and the metric improves.
How the future gets into a training set
Leakage rarely comes from one obvious bug. It enters through several routes, and most of them are joins or aggregations that look reasonable.
| Source | How it happens | Example |
|---|---|---|
| Latest-value join | A dimension or feature table holds only the current value, and training rows are joined to it. | `customer.plan_type` is overwritten when a customer downgrades, so the downgrade is visible in older rows. |
| Aggregates over the whole table | A statistic is computed over all rows, then attached to each row. | `avg_spend` uses the full year, including months after the prediction. |
| Wrong timestamp | The join uses the time a record was created in the real world, but the system only learned about it later. | A refund dated 3 January is loaded on 20 January. |
| Corrections and backfills | A value is fixed after the fact, and the fixed value replaces the original. | A fraud flag is added to a transaction two weeks later. |
| Random splits | Rows from the same entity or period land in both training and validation. | Row 900 from March trains the model that is validated on row 899 from March. |
| Label-derived features | A feature is computed from the same events that define the label. | `days_since_last_login` measured after the churn window starts. |
The first four are time-ordering errors in feature construction. The fifth is an evaluation error. The sixth is a definition error. All of them let the model see something it could not see in production.
Why the offline metric goes up
The model's training objective is to find any signal that separates the labels. It cannot tell whether a signal comes from the past or the future. If a future value is available in the training row, and it correlates with the label, the model will weight it heavily.
Future information is often a very strong signal, because it is a consequence of the outcome. A customer who churned filed a cancellation ticket. A loan that defaulted has a collections note. A transaction that was fraud has a chargeback. These features are almost proxies for the label.
At serving time, the feature has its real value as of that moment, usually empty or small. The model receives inputs that look unlike anything it was trained on, and its learned shortcut gives no help.
The size of the gap
There is no typical size for the drop. In the example above, the model might go from 0.94 offline to 0.60 online. In other cases the leak is small and the metric drops by one or two points, which is easy to blame on drift. The gap depends on how strongly the leaked feature tracks the label and how much weight the model puts on it.
Two properties make the problem expensive:
- It is silent. No exception is raised. The only visible signal is that the offline score looks better than expected.
- It is found late. You often learn about it after deployment, when the online metric is measured against real outcomes, which can take weeks for slow labels such as churn or default.
Warning signs
Some patterns suggest leakage before you ship.
- The validation score is much higher than a simple baseline or earlier model versions, with no matching change in features.
- A single feature dominates the importance ranking, especially one that is a consequence of the outcome.
- Performance on the most recent time period is much lower than on older periods.
- A model trained on a random split scores far higher than the same model trained on an earlier period and tested on a later one.
- Re-running the pipeline a month later gives different training rows for the same prediction times.
The time-based comparison is the most practical check. If you train on data before a cutoff and evaluate on data after it, the score is often noticeably lower than with a random split. The difference is a rough measure of how much the random split flatters the model, although it can also reflect normal drift.
import pandas as pd
cutoff = pd.Timestamp("2026-01-01")
train_df = train[train["prediction_ts"] < cutoff]
valid_df = train[train["prediction_ts"] >= cutoff]This split makes the validation set strictly later than the training set, which mirrors how the model is used. It does not fix leakage inside the features, but it removes one cause of inflated scores.
Edge cases that catch careful people
Time zones. If labels are in UTC and features are in local time, a feature stamped "2026-02-01 00:00" in a UTC-8 zone is actually known at 08:00 UTC. Comparing the raw values can let it through hours early. Convert everything to UTC before comparing.
Equal timestamps. When a feature time equals the prediction time, the feature may or may not have been available. If the feature is computed from the same batch that triggers the prediction, it was not. Decide on <= or < deliberately and apply it consistently.
Entities that change. A customer who switches segments, regions, or plans produces different feature values over time. Joining on the entity ID alone attaches the current segment to old rows.
Labels with a delay. A label such as "churned within 30 days" is only known 30 days after the prediction time. Rows from the last 30 days have incomplete labels. Including them as negatives teaches the model that recent customers never churn.
Derived tables. A feature table may itself have been built from a leaky join. Leakage compounds through layers, so checking the final table is not enough if you do not know how upstream tables were built.
What the rest of this tutorial builds
The fix is not a single trick. It is a set of habits applied from data collection to evaluation:
- Record three clocks for every fact: when it happened, when your system learned of it, and when the prediction is made.
- Store feature history instead of overwriting the latest value.
- Join labels to features with an as-of join, which takes the latest value at or before the prediction time.
- Limit how stale a joined value may be.
- Split by time, not at random.
- Add automated tests that fail when a row contains a feature newer than its prediction time.
The next chapter defines the three clocks precisely, since every later technique depends on keeping them apart.
Exercise
A feature table stores one row per customer with the column lifetime_orders, which is updated in place each night. You build a training set by joining each label row to this table on customer_id. The model's validation AUC is 0.95 on a random split. Name two separate problems with this setup that could inflate the score.
Show answer
First, the table holds only the latest value, so each training row sees an order count that includes orders placed after its prediction time. That is a latest-value join leak. Second, the random split places rows from the same customer and period in both training and validation, so the validation set is not later than the training set and does not resemble production. A fix needs stored feature history joined as of the prediction time, plus a split on a time cutoff.
Exercise
In the pandas example in this chapter, why does the leaky join return tickets_total = 6 for a prediction made on 1 February, and what value should it return?
Show answer
The leaky join keeps the newest row per customer regardless of its timestamp, which is the row from 1 March with a value of 6. The prediction time is 1 February, so the correct value is the latest row at or before it, which is 1 (the 1 February row). pd.merge_asof with direction="backward" returns it.
Exercise
Why can a leaky model still score well on a held-out validation set, so that ordinary validation does not catch the problem?
Show answer
The validation rows are built with the same faulty join as the training rows, so they also contain future information. The model uses the same shortcut on both sets and scores well on both. Validation only detects leakage if the validation features are built the way they will be available in production.