Sub topic 5
The as-of join: latest value at or before the prediction time
This chapter assumes you know basic supervised learning, SQL joins and window functions, and pandas DataFrames. It also assumes you are comfortable with timestamps and time zones. By the end you will be able to build a point-in-time correct join in pandas and SQL, and to recognize the errors that quietly break it.
Why an ordinary join is wrong
A label row says "at prediction_ts, customer 7 had not churned yet, and later they did." A feature table holds many rows per customer, one for each time the feature was computed. You need to pick exactly one feature row for each label row.
An equality join on customer_id returns every feature row for that customer, so each label row is multiplied. A join on the latest row per customer, which is what you get by keeping only the current value, uses values computed after the prediction time. That is temporal leakage: the model sees information it could not have had when the prediction was made.
The as-of join solves this with one rule: for each label row, take the most recent feature row for the same entity whose timestamp is at or before the prediction time.
The rule in one picture
Consider one customer with three feature rows and two prediction times.
The January 25 prediction gets the January 20 row. The February 10 row is in the future for that prediction, so it must not be used. The January 5 row is valid but older than a better candidate, so it is skipped.
The as-of join in pandas
pd.merge_asof implements this rule. It requires both inputs to be sorted by their time keys, and the by argument restricts matches to the same entity.
import pandas as pd
# labels: customer_id, prediction_ts, churned
# features: customer_id, feature_ts, avg_spend_30d
labels = labels.sort_values("prediction_ts")
features = features.sort_values("feature_ts")
train = pd.merge_asof(
labels,
features,
left_on="prediction_ts",
right_on="feature_ts",
by="customer_id",
direction="backward",
tolerance=pd.Timedelta("30D"),
)Each argument matters:
left_onandright_onname the two time columns. The left frame is the label table, so it controls the output rows.by="customer_id"makes the match happen only within the same entity. Without it, a label could pick up another customer's feature row.direction="backward"means "the nearest row at or before". The default is alsobackward, but spelling it out documents the intent. The other values,forwardandnearest, both can select rows from the future, so they are almost never correct for training data.tolerancerejects matches older than the given gap. When the best candidate is more than 30 days old, the feature columns come back asNaN. The next chapter covers how to choose this value.
By default merge_asof allows an exact match, so a feature row stamped exactly at prediction_ts is included. Whether that is right depends on your system. If a feature is computed from events up to and including its timestamp, but is only published after that moment, an exact match would be too optimistic. In that case pass allow_exact_matches=False for a strict "before" rule.
The as-of join in SQL
Most warehouses have no built-in as-of join, so you build it from a conditional join and a window function. The join condition keeps only feature rows that are not newer than the prediction. ROW_NUMBER then ranks the survivors from newest to oldest, and you keep rank 1.
WITH candidates AS (
SELECT
l.customer_id,
l.prediction_ts,
l.churned,
f.avg_spend_30d,
f.event_ts AS feature_ts,
ROW_NUMBER() OVER (
PARTITION BY l.customer_id, l.prediction_ts
ORDER BY f.event_ts DESC
) AS rn
FROM labels AS l
LEFT JOIN feature_history AS f
ON f.customer_id = l.customer_id
AND f.event_ts <= l.prediction_ts
)
SELECT customer_id, prediction_ts, churned, avg_spend_30d, feature_ts
FROM candidates
WHERE rn = 1;Three details deserve attention:
- The time condition belongs in the
ONclause. If you putf.event_ts <= l.prediction_tsin aWHEREclause, label rows with no earlier feature row are dropped, because theLEFT JOINturns into an inner join. You lose exactly the rows that tell you about missing history. - The
PARTITION BYincludesprediction_ts. A customer can appear in the label table many times. Partitioning by customer alone would keep only one row per customer overall. - Ties need a tiebreaker. If two feature rows share the same
event_ts,ROW_NUMBERpicks one arbitrarily, and the choice can change between runs. Add a second sort column, such asingested_ts DESC, so the result is deterministic.
The join produces one intermediate row for every earlier feature row of every label row. For a customer with 500 feature rows and 40 labels, that is 20,000 candidate rows before the filter. On large tables this is the main cost. Reduce it by adding a lower bound such as AND f.event_ts >= l.prediction_ts - INTERVAL '30' DAY, which doubles as the tolerance.
Adding a tolerance in SQL
The pandas example returns NaN for stale matches. To get the same behavior in SQL, include the lower bound in the join condition.
LEFT JOIN feature_history AS f
ON f.customer_id = l.customer_id
AND f.event_ts <= l.prediction_ts
AND f.event_ts >= l.prediction_ts - INTERVAL '30' DAYInterval syntax varies by warehouse. Some use INTERVAL 30 DAY or DATEADD. The logic is the same: a stale row never becomes a candidate, so the left join yields NULL for the feature columns.
Handling rows that arrive late
Event time says when something happened. Ingestion time says when your system learned about it. If a corrected value for January 20 is loaded on February 3, then a training row with a prediction time of January 25 should not use it, because on January 25 the system did not have it yet.
Adding an ingestion filter fixes this:
WITH candidates AS (
SELECT
l.customer_id,
l.prediction_ts,
l.churned,
f.avg_spend_30d,
ROW_NUMBER() OVER (
PARTITION BY l.customer_id, l.prediction_ts
ORDER BY f.event_ts DESC, f.ingested_ts DESC
) AS rn
FROM labels AS l
LEFT JOIN feature_history AS f
ON f.customer_id = l.customer_id
AND f.event_ts <= l.prediction_ts
AND f.ingested_ts <= l.prediction_ts
)
SELECT customer_id, prediction_ts, churned, avg_spend_30d
FROM candidates
WHERE rn = 1;Now both clocks are checked. The row must describe a moment at or before the prediction, and the system must have already stored it. When a feature row has been corrected, the history holds two rows with the same event_ts. The ingested_ts DESC tiebreaker then selects the newest correction that was available at prediction time.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Training rows have more rows than labels | The right side has duplicate keys and you used a plain join, or the `PARTITION BY` is too coarse | Keep `rn = 1` per `(entity, prediction_ts)` and check row counts |
| Many label rows vanish | Time condition placed in `WHERE` instead of `ON` | Move it to the `ON` clause of the `LEFT JOIN` |
| `merge_asof` raises a sorting error | Inputs not sorted by the time key | Sort each frame by its own time column |
| `merge_asof` raises a dtype error | Time columns have different types, such as `datetime64[ns]` against `datetime64[us]` or a mix of naive and timezone-aware values | Convert both to the same type and the same time zone, preferably UTC |
| Offline metrics look too good | `direction="nearest"` or `forward`, or a missing `by` | Use `backward` and always set `by` |
| Results change between runs | Ties on `event_ts` with no tiebreaker | Add `ingested_ts DESC` to the ordering |
| Many `NaN` values after the join | Tolerance is shorter than the feature refresh interval | Compare the tolerance to how often features are written |
Verifying the result
The join logic is simple, but it is easy to break during a refactor, so assert its guarantees right after it runs.
# After the as-of join
joined = train.dropna(subset=["feature_ts"])
# 1. No feature may be newer than the prediction time.
assert (joined["feature_ts"] <= joined["prediction_ts"]).all()
# 2. The label table must keep exactly one row per (customer, prediction time).
assert not train.duplicated(["customer_id", "prediction_ts"]).any()The first assertion needs the right-side time column in the output, which is why the examples keep feature_ts as a column. The second catches accidental row multiplication. A later chapter builds these into a proper test suite.
Worked example
Suppose the feature table holds these rows for customer 7:
| feature_ts | avg_spend_30d |
|---|---|
| 2026-01-05 | 40.0 |
| 2026-01-20 | 55.0 |
| 2026-02-10 | 80.0 |
and the label table holds predictions on 2026-01-25 and 2026-02-15, plus a third on 2026-04-01. With a 30-day tolerance the as-of join returns:
| prediction_ts | feature_ts | avg_spend_30d |
|---|---|---|
| 2026-01-25 | 2026-01-20 | 55.0 |
| 2026-02-15 | 2026-02-10 | 80.0 |
| 2026-04-01 | NaN | NaN |
The April prediction found its best candidate, February 10, was 50 days old and discarded it. Whether to drop that row, impute a default, or let the model handle the missing value is a modeling decision. What matters is that the missing value is visible rather than silently filled with something stale.
Exercise
A teammate writes the SQL as-of join but puts f.event_ts <= l.prediction_ts in the WHERE clause instead of the ON clause, with a LEFT JOIN. The training set is smaller than the label table. Why, and how do you fix it?
Show answer
In the WHERE clause the condition is evaluated after the join. Label rows with no feature row at all have NULL for f.event_ts, and NULL <= l.prediction_ts is not true, so those rows are filtered out. The LEFT JOIN behaves like an inner join. Move the condition into the ON clause so unmatched labels survive with NULL features.
Exercise
Your feature table has a row for 2026-01-20 that was corrected and reloaded on 2026-02-03. You are building a label with prediction time 2026-01-25. Which row should it use, and which condition makes that happen?
Show answer
It should use the original, uncorrected row, because the correction was not available on 2026-01-25. The condition f.ingested_ts <= l.prediction_ts excludes the reloaded row, so only the original one is a candidate.
Exercise
Why is direction="nearest" unsafe in pd.merge_asof when building training data?
Show answer
nearest picks the closest feature row in either direction. When a row after the prediction time is closer than the latest earlier one, the join uses future information, which is temporal leakage.