Sub topic 7
Cause 4: Time Leakage and Point-in-Time Correctness
This chapter assumes you can write pandas code, know the train/validate/predict workflow, and have seen the earlier chapters on duplicated feature code, fit-time statistics, and data source differences. Those causes make the same feature differ between two code paths. Time leakage is different. The code can be identical in both paths and the training data can still contain information that does not exist when the model predicts in production.
What time leakage is
A prediction is made at a specific moment. At that moment the system knows only what has happened so far. A training example must be built from the same restricted view. If a training row includes a feature value that was computed after the prediction moment, the model learns from the future. Production never offers that future, so the signal disappears.
This is a form of skew because the training distribution of the feature does not match what serving can supply. It is also hard to notice. Validation metrics look excellent, since the validation set was built with the same leak. Accuracy drops only after deployment, and no error is raised.
Two terms are used here:
- Label time is the moment at which a prediction would have been made, or the moment the label became known, depending on how you define the example. Pick one meaning and apply it consistently. This chapter uses it as the prediction moment.
- Point-in-time correctness means every feature in a training row is the value that was available at the row's label time, and no later value.
How leakage gets in
Leakage rarely looks like a mistake in the code. It usually comes from a reasonable-looking shortcut.
| Source | What happens | Why serving differs |
|---|---|---|
| Latest-value join | Training joins each label to the current row in a feature table | The table holds today's value, but the label is from weeks ago |
| Overwritten tables | A dimension table is updated in place, so history is lost | The old value that serving would have seen is gone |
| Late-arriving data | An event happened on Monday but was loaded on Thursday | At prediction time on Tuesday the event was not yet visible |
| Window overshoot | A "last 30 days" aggregate is computed to the end of the label day or beyond | Serving can only see data up to the request |
| Target-derived features | A feature such as "account closed flag" is set as a result of the outcome | The flag does not exist before the outcome |
| Random split on time-ordered data | Rows from the future land in the training set | Production always predicts forward in time |
Late-arriving data deserves attention. There are two timestamps on each record: the event time (when the thing occurred) and the ingestion time (when your system learned about it). Point-in-time correctness has to respect ingestion time. If serving only knew about an event after it was loaded, training must treat the event as unknown until then, even though its event time is earlier.
A worked example
Suppose you predict churn. Each label records whether a user churned, and a feature logins_30d is recomputed periodically. The naive approach joins each label to the latest feature value for that user. That value was computed after the label, so it can reflect the churn itself: users who are about to leave stop logging in, and the latest value shows the drop.
The as-of join solves this. For each label, it takes the most recent feature value computed at or before the label time.
import pandas as pd
labels = pd.DataFrame({
"user_id": [1, 1],
"label_time": pd.to_datetime(["2026-01-10", "2026-01-20"]),
"churned": [0, 1],
}).sort_values("label_time")
features = pd.DataFrame({
"user_id": [1, 1, 1],
"feature_time": pd.to_datetime(["2026-01-05", "2026-01-15", "2026-01-25"]),
"logins_30d": [12, 7, 2],
}).sort_values("feature_time")
# For each label, take the latest feature value computed at or before label_time
train = pd.merge_asof(
labels, features,
left_on="label_time", right_on="feature_time",
by="user_id", direction="backward",
)
print(train[["label_time", "feature_time", "logins_30d"]])The output pairs the label on 2026-01-10 with the feature from 2026-01-05 (12 logins), and the label on 2026-01-20 with the feature from 2026-01-15 (7 logins). The value of 2 from 2026-01-25 is never used, because it did not exist yet.
A naive join on user_id alone would have attached a feature to each label without regard to time. Depending on how duplicates were resolved, the model would see 2 for a label from 2026-01-10. That value is far more predictive of churn than anything a live system could know on that date.
Details of merge_asof that matter
The example is short, and several of its details are easy to get wrong.
- Both sides must be sorted by the time key.
merge_asofraises an error if they are not, so sort explicitly. by="user_id"restricts matching to the same entity. Without it, a label could pick up another user's feature.direction="backward"gives the latest value at or before the label time. The default is also backward, but stating it makes the intent visible to reviewers."forward"and"nearest"leak the future and should be rare in training-set code.allow_exact_matchesdefaults toTrue, so a feature computed at exactly the label time is used. Decide whether that is right. If the feature job finishes after the timestamp it is stamped with, an exact match is a leak. Settingallow_exact_matches=Falseis the safer choice in that case.tolerancelimits how stale a matched value may be. Serving would never use a feature that is a year old without noticing, but the as-of join will silently do so. A tolerance such aspd.Timedelta("7D")turns a stale match into a missing value, which you can then handle on purpose.
Leakage beyond joins
Joins are the common place to look, but not the only one.
Splitting data
For problems where production predicts forward in time, split by time. Train on earlier periods and validate on later ones. A random split puts future rows in training and past rows in validation, so the validation score measures interpolation rather than forecasting. The result is a good-looking metric that production will not reproduce.
Aggregates and fit-time statistics
Statistics fitted on the full dataset, such as a mean, a target encoding, or a scaler, carry information from validation and later rows into training. Fit them on the training period only. Chapter 5's fitted-state point applies here with a time dimension: the statistic must be computed from data before the prediction moment.
Windows
When computing "events in the last 30 days" for a label at time t, the window is (t - 30 days, t]. Check that the upper bound is t and not the end of the day, and that the lower bound is computed from t and not from the date the job runs.
Detecting leakage
Leakage leaves traces you can look for before deployment.
- Suspiciously strong features. A single feature with extreme importance, or a model whose offline score is much higher than a simple baseline from earlier versions, deserves suspicion.
- Time-split versus random-split gap. If the score falls sharply when you switch from a random to a time-based split, the random split was leaking.
- Feature timestamps after label timestamps. Keep
feature_timein the training frame during development and assert that it never exceedslabel_time. - Drop after launch. If serving features match training features in the parity tests from a later chapter and accuracy still falls, time leakage in the labels or joins is a likely cause.
A check you can add to the training-set build is short.
import pandas as pd
def assert_point_in_time(train: pd.DataFrame) -> None:
"""Fail if any joined feature value is newer than its label."""
leaked = train[train["feature_time"] > train["label_time"]]
if not leaked.empty:
raise ValueError(f"{len(leaked)} rows use features from after label_time")
assert_point_in_time(train)
print("point-in-time check passed")This check runs on the train frame from the previous example and passes there. Rows with no matching feature have a missing feature_time, and the comparison treats them as not leaked, so also count and review those rows separately.
How this connects to prevention
Building point-in-time-correct data by hand is possible for one table and a few features. It becomes error-prone with dozens of features from different sources, each with its own timestamps. That is one reason feature stores exist. A feature store keeps feature history with timestamps and offers a point-in-time join that performs this as-of logic for every feature consistently, which a later chapter covers. Whatever tool you use, the rule stays the same: for every training row, use only what serving could have known at that moment.
Exercise
A training set joins each purchase label to a customer_segment column in a customer table that is updated in place each night. The model scores very well offline and poorly in production. Name the likely cause, explain how it produces this pattern, and give two changes that fix it.
Show answer
The likely cause is time leakage from a latest-value join. The table holds only the current segment, so a purchase from months ago is paired with a segment assigned later, possibly as a result of that purchase (for example "high-value customer"). The model learns from information that is unavailable at prediction time, which inflates offline scores but gives nothing in production. Fixes: (1) keep history by storing segment changes with a valid-from timestamp, such as a slowly changing dimension or a snapshot table, and join with an as-of join using direction="backward" on the purchase time; (2) add an assertion in the training build that every feature timestamp is not later than the label time, and use a tolerance so stale matches become missing values.
Exercise
In pd.merge_asof, why can setting direction="nearest" produce leakage, and which two arguments would you use to make a join stricter?
Show answer
With "nearest", a feature stamped after the label time can be chosen if it is closer than the previous one, so future values enter training. Use direction="backward" to allow only earlier values, plus allow_exact_matches=False to exclude values stamped at exactly the label time, and tolerance to limit how stale a match may be.