Sub topic 11
Late-arriving and corrected data
This chapter assumes you can write SQL joins and window functions, use pandas, and have read the earlier chapters on the as-of join and append-only feature history. You should know the difference between event time and ingestion time. This chapter uses both to handle data that shows up late or gets fixed after the fact.
Why one timestamp is not enough
An as-of join on event time alone answers this question: "What was the latest feature value that described the world at or before the prediction time?" That is not the question a production model faces. At serving time, the model sees only what the system had received by that moment.
Two situations make the answers differ:
- Late-arriving data. An event happened at 10:00 but reached your warehouse at 14:00 because of a batch delay, a mobile client that was offline, or a slow upstream partner.
- Corrected data. A value was written, then later replaced. A refund is reversed, a bad sensor reading is repaired, or a backfill recomputes a feature with a fixed bug.
If you build training data today using only event time, you see the late rows and the corrected values. At the original prediction time, the system had not seen them. The training set therefore contains information the model could never have had. This is temporal leakage, and it is quiet: the join is correct by event time and the leak is invisible in the output.
Two time axes: bitemporal data
A table that records both clocks is called bitemporal. Each row carries:
event_ts: when the fact became true in the world (valid time).ingested_ts: when your system first stored that row (transaction time).
A row is usable for a prediction at time T only if both conditions hold:
event_ts <= T: the fact had already happened.ingested_ts <= T: the system already knew about it.
The second condition is what the chapter is about. Because ingested_ts >= event_ts in a healthy pipeline, it is the stricter filter whenever data is delayed.
At 12:00 the model could not use the 10:00 event. A training build must reproduce that blindness.
Filtering on both timestamps
The topic's SQL example adds the second condition to the join. Here it is as a complete query, with the schema stated.
-- labels(customer_id, prediction_ts, churned)
-- feature_history(customer_id, event_ts, ingested_ts, avg_spend_30d)
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;The ORDER BY matters. It first picks the row with the newest event time. If two rows share an event time (an original and a correction), the one ingested later wins, but only among rows already ingested by prediction_ts, because the join filter removed the rest.
A worked example
Suppose customer 7 has these rows in feature_history:
| event_ts | ingested_ts | avg_spend_30d | Note |
|---|---|---|---|
| 2026-03-01 00:00 | 2026-03-01 01:00 | 40.0 | original value |
| 2026-03-01 00:00 | 2026-03-04 09:00 | 55.0 | correction after a bug fix |
| 2026-03-02 00:00 | 2026-03-05 08:00 | 60.0 | arrived three days late |
Now consider a label with prediction_ts = 2026-03-03 12:00.
- Event-time-only join: the newest row with
event_ts <= prediction_tsis the 03-02 row, so the model trains on 60.0. At that moment the system had not received it. - Bitemporal join: only the first row passes both filters (the correction arrived on 03-04, the late row on 03-05). The value is 40.0, which is what serving would have returned.
Whether 40.0 or 55.0 is "more true" is a separate question. Point-in-time correctness asks what the system knew. If your training goal is different (see the section on choosing a policy), you must decide that on purpose.
The same filter in pandas
merge_asof has only one time key, so it cannot apply two time conditions in one call. The reliable approach is to make ingested_ts the as-of key after you have worked out which rows count as visible. For moderate data sizes, a merge followed by filters is clear and correct.
import pandas as pd
def bitemporal_asof(labels: pd.DataFrame, features: pd.DataFrame) -> pd.DataFrame:
"""Latest feature row per label with event_ts <= T and ingested_ts <= T."""
pairs = labels.merge(features, on="customer_id", how="left")
visible = pairs[
(pairs["event_ts"] <= pairs["prediction_ts"])
& (pairs["ingested_ts"] <= pairs["prediction_ts"])
]
best = (
visible.sort_values(["event_ts", "ingested_ts"])
.groupby(["customer_id", "prediction_ts"], as_index=False)
.tail(1)
)
keys = ["customer_id", "prediction_ts"]
out = labels.merge(
best[keys + ["event_ts", "ingested_ts", "avg_spend_30d"]],
on=keys,
how="left",
)
return out
labels = pd.DataFrame(
{
"customer_id": [7],
"prediction_ts": [pd.Timestamp("2026-03-03 12:00")],
"churned": [0],
}
)
features = pd.DataFrame(
{
"customer_id": [7, 7, 7],
"event_ts": pd.to_datetime(
["2026-03-01 00:00", "2026-03-01 00:00", "2026-03-02 00:00"]
),
"ingested_ts": pd.to_datetime(
["2026-03-01 01:00", "2026-03-04 09:00", "2026-03-05 08:00"]
),
"avg_spend_30d": [40.0, 55.0, 60.0],
}
)
print(bitemporal_asof(labels, features))Running this prints one row with avg_spend_30d equal to 40.0. The cross-merge by customer grows with rows per customer times labels per customer, so for large tables do the filtering in SQL or in a warehouse engine.
Choosing a policy for corrections
Three policies are common, and they answer different questions.
| Policy | Filter | Use when |
|---|---|---|
| Known-at-prediction | `event_ts <= T` and `ingested_ts <= T` | You want training data that matches what serving saw. This is the default. |
| Corrected history | `event_ts <= T` only, using the latest correction | The serving system will recompute features from clean data and you can prove it. |
| Known-at-label-time | `ingested_ts <= label_available_ts` | You are training on labels that matured later and want one consistent snapshot. |
Pick one deliberately and write it down. Mixing policies between training and serving is a form of training-serving skew.
Gotchas and edge cases
Using the wrong ingestion timestamp
ingested_ts must record when your system could first read the row. Common mistakes:
- Copying
event_tsintoingested_tsduring a backfill. This makes every historical row look instantly available and erases the delay you are trying to model. - Using a pipeline job's start time rather than the commit time. A row written at 14:00 by a job that started at 11:00 was not readable at 12:00.
- Overwriting rows in place. An
UPDATEdestroys the original value and its ingestion time, so you cannot rebuild what the system knew earlier. Append a new row instead.
Backfills
When you backfill a new feature across old dates, the rows are ingested today but describe the past. Under the known-at-prediction policy, every backfilled row has ingested_ts later than most predictions, so the new feature will be null for old labels. This is correct if the feature did not exist then. If instead you want to train with the feature as if it had always existed, you are choosing the corrected-history policy for that feature. Recording that choice is better than faking timestamps. Store a separate column such as available_ts for the time you claim the value would have been computable, and say how it was derived.
Time zones
Compare timestamps in one zone, ideally UTC. A naive ingested_ts in local time compared with a UTC prediction_ts can shift visibility by hours and silently admit or drop rows near the boundary. In pandas, mixing naive and aware timestamps raises an error, which is useful. In some SQL engines the comparison happens without a warning.
Equal timestamps
The filter uses <=. A row ingested at exactly the prediction time counts as visible. Decide whether serving would have seen it. If predictions run at the start of a batch and ingestion commits at the same second, use < for ingestion, or define prediction_ts as the time the feature lookup was issued.
Deletions
Some corrections remove a row, such as a fraudulent transaction purged from history. Model this as a tombstone row with its own ingested_ts and a deleted flag, not a physical delete. Then the as-of query can return "no value" for predictions made after the deletion and the original value before it.
Testing for late-data leakage
An event-time check alone passes even when late data leaks. Add a check on ingestion time.
# After the bitemporal as-of join
joined = out.dropna(subset=["ingested_ts"])
assert (joined["event_ts"] <= joined["prediction_ts"]).all()
assert (joined["ingested_ts"] <= joined["prediction_ts"]).all()
assert not out.duplicated(["customer_id", "prediction_ts"]).any()A stronger test replays history. Pick a past date, rebuild the training rows for it, and compare them with what the production feature store logged at that time. A match rate well below 100% points to missing ingestion times, in-place updates, or a mismatch between the batch and serving logic.
Exercise
A feature row has eventts 2026-05-10 08:00 and ingestedts 2026-05-12 08:00. A label has predictionts 2026-05-11 09:00. Under the known-at-prediction policy, can this row be joined to the label? Then say what would change if the table had no ingestedts column.
Show answer
No. The eventts passes (08:00 on 05-10 is before 09:00 on 05-11), but ingestedts is 05-12, after the prediction time, so the system did not yet have the row. Without an ingestedts column, the join can only filter on eventts, so the row would be joined and leak a value the system did not have at prediction time.
Exercise
A teammate backfills a new feature and sets ingestedts equal to eventts so that "the join works for old labels". What is wrong with this, and what is a better approach?
Show answer
It makes every row look available at its event time, so the training set contains values that production could not have computed then, and offline metrics will be inflated. Keep the true ingestion time. If the feature could truly have been computed historically, store a separate available_ts (with a documented derivation) and filter on it, or accept nulls for old labels.