Sub topic 9
Testing that no feature comes from the future
This chapter assumes you can build an as-of join in pandas or SQL, as covered earlier in this tutorial. It also assumes you know the three clocks (event time, ingestion time, prediction time) and can read a basic pytest test. The goal is to turn "I think the join is correct" into checks that run on every build and fail loudly when it is not.
What a leakage test can and cannot prove
A leakage test checks an invariant: a statement that must hold for every row of the training set. For point-in-time correctness there are four:
- Every joined feature has
feature_ts <= prediction_ts. - Every joined feature has
ingested_ts <= prediction_ts, meaning the system already knew the value. - Every joined feature is no older than the allowed tolerance.
- The join kept exactly one row per label row.
These checks inspect the output of the join. They do not prove that the features were computed without future data. A rolling average stored with a correct timestamp can still have been computed from rows that arrived later. Tests on the joined table catch join mistakes. Tests that rebuild the data with extra future rows catch computation mistakes. You need both kinds.
Invariant checks on the joined table
The code below builds a small training set with merge_asof, then runs the four invariants. It collects every problem before failing, so one run tells you everything that is wrong.
The fixture contains a late-arriving row on purpose. Customer 1 has a feature value for 2026-01-05 that was only ingested on 2026-01-09. The label is predicted on 2026-01-06, so the system did not know that value yet. A plain merge_asof on event time cannot see this, and the ingestion check catches it.
import pandas as pd
def build_training_set(labels, features, tolerance="30D"):
labels = labels.sort_values("prediction_ts")
features = features.sort_values("feature_ts")
return pd.merge_asof(
labels,
features,
left_on="prediction_ts",
right_on="feature_ts",
by="customer_id",
direction="backward",
tolerance=pd.Timedelta(tolerance),
)
def check_training_set(train, n_labels, tolerance="30D"):
problems = []
if len(train) != n_labels:
problems.append(f"row count {len(train)} != label count {n_labels}")
if train.duplicated(["customer_id", "prediction_ts"]).any():
problems.append("duplicate (customer_id, prediction_ts) rows")
# Rows with no feature match have NaT here and are skipped on purpose.
joined = train.dropna(subset=["feature_ts"])
n_future = (joined["feature_ts"] > joined["prediction_ts"]).sum()
if n_future:
problems.append(f"{n_future} rows use feature_ts after prediction_ts")
n_unknown = (joined["ingested_ts"] > joined["prediction_ts"]).sum()
if n_unknown:
problems.append(f"{n_unknown} rows use values ingested after prediction_ts")
age = joined["prediction_ts"] - joined["feature_ts"]
n_stale = (age > pd.Timedelta(tolerance)).sum()
if n_stale:
problems.append(f"{n_stale} rows are staler than {tolerance}")
if problems:
raise AssertionError("; ".join(problems))
def make_fixture():
ts = pd.to_datetime
labels = pd.DataFrame({
"customer_id": [1, 2],
"prediction_ts": ts(["2026-01-06", "2026-01-06"]),
"churned": [0, 1],
})
features = pd.DataFrame({
"customer_id": [1, 1, 2],
"feature_ts": ts(["2026-01-01", "2026-01-05", "2026-01-02"]),
"ingested_ts": ts(["2026-01-01", "2026-01-09", "2026-01-02"]),
"avg_spend_30d": [10.0, 20.0, 5.0],
})
return labels, features
if __name__ == "__main__":
labels, features = make_fixture()
train = build_training_set(labels, features)
try:
check_training_set(train, n_labels=len(labels))
except AssertionError as err:
print("Leakage check failed:", err)Running it prints Leakage check failed: 1 rows use values ingested after prediction_ts. The fix is the bitemporal join from the SQL example earlier in the tutorial: filter on ingested_ts <= prediction_ts as well as event_ts <= prediction_ts. After the fix, this same test is what keeps the filter from being removed by accident.
Why the checks use dropna
A label with no feature inside the tolerance gets NaT in feature_ts. Any comparison with NaT evaluates to False. If you wrote assert (train["feature_ts"] <= train["prediction_ts"]).all() without dropping those rows, the assertion would fail on every unmatched label. It would report a leak that does not exist. Teams often react by deleting the check. Drop the unmatched rows first, and track the unmatched share separately (see below).
The future-poisoning test
Invariant checks look at one output. A stronger test changes the input and asserts that the output does not move. If you add feature rows that lie in the future of every label, a correct pipeline must produce exactly the same training set.
import pandas as pd
from pandas.testing import assert_frame_equal
# build_training_set and make_fixture are defined in the previous block.
from leakage_checks import build_training_set, make_fixture
def test_future_rows_do_not_change_training_set():
labels, features = make_fixture()
features = features[features["ingested_ts"] <= "2026-01-06"]
baseline = build_training_set(labels, features)
poison = labels[["customer_id", "prediction_ts"]].copy()
poison["feature_ts"] = poison["prediction_ts"] + pd.Timedelta("1D")
poison["ingested_ts"] = poison["feature_ts"]
poison["avg_spend_30d"] = 1e9 # absurd value, impossible to miss
poison = poison.drop(columns="prediction_ts")
poisoned_features = pd.concat([features, poison], ignore_index=True)
rebuilt = build_training_set(labels, poisoned_features)
assert_frame_equal(baseline, rebuilt)Save the earlier block as leakage_checks.py and this one as test_leakage.py, then run pytest. The test uses the fixture without the late row so that it isolates one question: does the future influence the result?
The poison value of 1e9 matters. A small, plausible value could sit inside normal variation and hide a leak in a rounded comparison. An absurd value makes any leak obvious in the diff.
Run the same idea against your real feature pipeline, not only the join. Recompute a rolling-window feature on a history that has extra rows after the cutoff, then compare the values at earlier timestamps. If they change, the window reaches into the future.
Statistical smoke tests
Structural checks cannot catch a feature that is derived from the label itself, such as a "days since last cancellation request" that is only populated for customers who churned. Two cheap statistical checks find these:
- Single-feature strength. Fit a depth-limited model on each feature alone and compute its validation AUC. A single behavioral feature with an AUC above roughly 0.9 deserves a manual look. The threshold depends on the problem, so record the AUC per feature and flag large jumps between builds instead of using one fixed number.
- Null-rate shift. Compare the share of unmatched (
NaT) rows between training and your latest serving logs. Training with 1% nulls and serving with 25% nulls means training saw values that serving cannot produce in time.
These checks produce suspicion, not proof. Treat a flag as a reason to open the feature definition.
Common errors in leakage tests
| Symptom | Cause | Fix |
|---|---|---|
| Assertion fails on rows with no match | `NaT` comparisons return `False` | Drop unmatched rows before comparing, and report the unmatched share as its own metric |
| Test passes but offline metrics still look too good | Only `feature_ts` was checked, not `ingested_ts` | Carry `ingested_ts` through the join and assert on it |
| `merge_asof` raises an error about dtypes or ordering | Time columns have different types or time zones, or are unsorted | Convert both sides to one timezone-aware dtype, and sort by the `on` column |
| Test passes on a tiny fixture and never fails | The fixture contains no leaking case | Include a late row, a row exactly at `prediction_ts`, and a row after it |
| Checks pass when the check function is called on a different table than the one used for training | The test builds its own training set | Run the checks inside the pipeline on the real output |
| Boundary rows pass `<=` but were not available | A value stamped exactly at `prediction_ts` may have been computed after the prediction was made | Decide the boundary rule once, and prefer `ingested_ts <` or an explicit availability delay if features are computed in batch |
Boundary rows
Whether feature_ts == prediction_ts is allowed is a design decision, not a detail. A feature stamped at midnight and a prediction made at midnight might be consistent in an event-time sense, while the batch job that produced the feature finished at 02:00. The ingestion check covers this only if ingested_ts records when the value became readable. Put one line in your pipeline documentation that states the rule, and add a fixture row exactly at the boundary so the rule is tested.
Where to run the checks
Run the invariant checks inside the training pipeline, immediately after the join and before any model code. A check that only runs in a separate test suite validates the fixture, not the data you train on. Run the future-poisoning test in continuous integration against a small synthetic history, since it needs a controlled input. Log the number of rows checked, the unmatched share, and the maximum age. These numbers become a time series that shows drift in your feature freshness.
When a check fails, stop the pipeline and keep the failing table. The error message from check_training_set lists counts. Sampling a few offending rows from the saved table usually shows the cause within minutes.
Exercise
A teammate writes assert (train["feature_ts"] <= train["prediction_ts"]).all() and it fails on a dataset where 3% of labels have no feature within the 30-day tolerance. What is the most likely reason it fails, and what is the right fix?
Show answer
Labels with no match have NaT in feature_ts, and a comparison with NaT is False, so the assertion fails even though no feature comes from the future. Drop rows where feature_ts is missing before the comparison, and track the unmatched share as a separate metric.
Exercise
You add an invariant check that feature_ts <= prediction_ts and it passes, yet the model still shows suspiciously high validation AUC. Name two checks from this chapter that could find a leak the invariant missed.
Show answer
Check ingested_ts <= prediction_ts to catch late-arriving or corrected values that the system did not know yet. Run the future-poisoning test, which adds absurd feature rows after every prediction time and asserts the training set does not change, to catch window features computed from future rows. A single-feature AUC check can also point to a feature derived from the label.