Sub topic 3
Testing that no feature comes from the future
This chapter assumes you can write an as-of join in pandas or SQL, filter with window functions, and reason about event and ingestion timestamps.
Testing that no feature comes from the future
A correct join can break later. A changed filter, a new feature source, or a bad key can bring future rows back. Run assertions after every build:
import pandas as pd
def check_no_future_features(train: pd.DataFrame) -> None:
joined = train.dropna(subset=["feature_ts"])
leaked = joined[joined["feature_ts"] > joined["prediction_ts"]]
if not leaked.empty:
raise ValueError(f"{len(leaked)} rows use features newer than prediction time")
if train.duplicated(["customer_id", "prediction_ts"]).any():
raise ValueError("the join duplicated label rows")Rolling-window features that exclude future rows
A 30-day average must end at the prediction time. Bound the window on both sides in the join:
SELECT
l.customer_id,
l.prediction_ts,
AVG(t.amount) AS avg_spend_30d
FROM labels AS l
LEFT JOIN transactions AS t
ON t.customer_id = l.customer_id
AND t.event_ts <= l.prediction_ts
AND t.event_ts > l.prediction_ts - INTERVAL '30 days'
GROUP BY l.customer_id, l.prediction_ts;The LEFT JOIN keeps labels for customers with no transactions in the window.
Late-arriving and corrected data
A row can have an event time before the prediction time but arrive after it. Add a filter on ingestion time:
AND f.ingested_ts <= l.prediction_tsThis reproduces what the system knew at prediction time, including values that were later corrected.
Keeping training and serving consistent
Training and serving must apply the same window edges and null handling. Put the feature logic in one shared definition, or test both paths against the same sample rows.
| Check | What it catches |
|---|---|
| Shared feature definition | Different window edges in SQL and Python |
| Sample-row comparison | Null handling that differs between paths |
Reproducing a training set months later
Store the query text in version control. Record the ingestion cutoff used for the build. Rerunning with the same query and cutoff must return the same rows.
Exercise
A label has predictionts 2026-03-10. A feature row has eventts 2026-03-09 and ingested_ts 2026-03-12. Should the join use it?
Show answer
No. The row was ingested after the prediction time, so the system did not know that value on 2026-03-10. Filter on ingestedts <= predictionts.