Sub topic 9
Testing That No Feature Comes From the Future
This chapter assumes you know supervised learning, pandas DataFrames, SQL joins, and basic train/validation splits. The goal is to make temporal leakage an automated failure rather than a code-review guess.
What the test must prove
For every training row, each feature must satisfy:
- Its event time is at or before the row's prediction time.
- Its ingestion time is at or before the prediction time when data availability matters.
- The join produced exactly one row for each entity and prediction time.
- The validation data occurs after the training data when evaluating a time-dependent problem.
A feature can have an old event time but a late ingestion time. For example, a purchase happened on January 5, but the source system received it on January 8. A prediction made on January 6 could not have used that purchase if the model reads the source system.
| Check | Failure it detects |
|---|---|
| `event_ts <= prediction_ts` | A feature uses future events |
| `ingested_ts <= prediction_ts` | A feature was unavailable at prediction time |
| One row per entity and prediction time | A many-to-one join duplicated labels |
| Training time before validation time | A random split makes evaluation unrealistic |
Keep the timestamps in the training set
Do not discard the feature timestamp after joining. Keep the timestamp used to select the feature value, and keep the ingestion timestamp when your source has one. These columns make the data auditable and allow tests to inspect the join.
import pandas as pd
train = pd.DataFrame(
{
"customer_id": ["c1", "c1", "c2"],
"prediction_ts": pd.to_datetime(
["2026-01-10", "2026-01-20", "2026-01-15"],
utc=True,
),
"feature_ts": pd.to_datetime(
["2026-01-09", "2026-01-19", "2026-01-14"],
utc=True,
),
"ingested_ts": pd.to_datetime(
["2026-01-09", "2026-01-19", "2026-01-14"],
utc=True,
),
"avg_spend_30d": [42.0, 45.0, 18.0],
}
)
joined = train.dropna(subset=["feature_ts"])
# A selected feature cannot describe a future event.
assert (joined["feature_ts"] <= joined["prediction_ts"]).all()
# The feature must also have been available to the pipeline.
assert (joined["ingested_ts"] <= joined["prediction_ts"]).all()
# The join must preserve one label row per customer and prediction time.
assert not train.duplicated(
["customer_id", "prediction_ts"]
).any()These assertions stop execution with AssertionError when a condition is false. In a production pipeline, place them before writing the training set or starting model training.
Test missing and stale matches
A failed as-of join often produces a missing feature. Missing values are not automatically leakage, but they can show that the feature was unavailable or outside its freshness limit. Test the missing-rate policy explicitly.
For example, a feature with a 30-day tolerance should not silently use a value from 90 days ago. You might allow missing values for some features, reject them for others, or record the missing rate as a monitored metric.
Validate the time split
A leakage-free join can still produce an optimistic score if the split is random. For a system that predicts future cases, train on earlier prediction times and validate on later ones.
cutoff = pd.Timestamp("2026-01-18", tz="UTC")
train_df = train[train["prediction_ts"] < cutoff]
valid_df = train[train["prediction_ts"] >= cutoff]
assert train_df["prediction_ts"].max() < valid_df["prediction_ts"].min()The exact cutoff should be chosen before model evaluation. If repeated experiments select a cutoff after inspecting validation results, the validation set can become part of the tuning process.
A practical validation flow
Run these checks on every generated dataset, not only on the first version of the query. A later schema change, join condition, or backfill can reintroduce leakage.
Exercise
A joined row has featurets = 2026-02-10, ingestedts = 2026-02-11, and prediction_ts = 2026-02-12. Is it valid if the feature event happened before the prediction?
Show answer
No. The feature was not available in the system until after the prediction time, so the ingestion-time check must reject it.