Sub topic 13
Reproducing a Training Set Months Later
This chapter assumes you have read the earlier chapters on as-of joins and on late-arriving data. You should know that a point-in-time correct join returns, for each label row, the newest feature value known at the prediction time. You should also know that ingested_ts records when a row reached your system. Basic SQL, pandas, and hashing are enough for the rest.
Why a rerun gives different rows
An audit, a regression investigation, or a retrain with a new algorithm often needs the exact training set from months ago. Running the same query again rarely returns it. A point-in-time correct join does not guarantee this, because the inputs keep changing after the first build.
| Source of drift | What happens | Fix |
|---|---|---|
| Late or corrected feature rows | New rows land in `feature_history` with old `event_ts` values | Filter on `ingested_ts` against a pinned cutoff |
| Label maturation | Churn labels for recent predictions become known later, or get revised | Pin a label cutoff and keep label history |
| Deliberate backfills | A feature definition is fixed and old history is rewritten | Version feature definitions and keep the old rows |
| Ties in ordering | Two rows share the same `event_ts` and the database picks either one | Add a deterministic tie-breaker |
| Query or code edits | Someone changes a filter, a tolerance, or a library version | Store the query text hash and the environment |
| Deleted or compacted data | Retention jobs remove old history | Archive or snapshot before deleting |
The goal is not to freeze the whole warehouse. It is to record enough information that you can reconstruct the same rows, and to detect when you cannot.
Pin the knowledge cutoff
In earlier chapters, ingested_ts <= prediction_ts kept each training row honest. A reproducible build needs a second, global bound: the knowledge cutoff, the moment at which you stopped looking at the data. It is a property of the build, not of any row.
The two bounds do different jobs:
ingested_ts <= prediction_tsprevents leakage. Information the system did not have at prediction time must not be used.ingested_ts <= build_cutoffprevents drift. Anything that arrived after the original build must not change the rebuilt set.
For most feature rows the first bound already makes the result stable. A correction that arrives after the prediction time is excluded either way. The cutoff matters in three cases: labels that mature later, backfills that deliberately carry an old ingested_ts, and rows whose ingested_ts is itself unreliable.
The query below uses both bounds. It assumes the labels table has a labeled_ts column that records when each label became known, and that feature_history has a unique row_id.
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, f.row_id 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
AND f.ingested_ts <= :build_cutoff
WHERE l.labeled_ts <= :build_cutoff
)
SELECT customer_id, prediction_ts, churned, avg_spend_30d
FROM candidates
WHERE rn = 1;Pass :build_cutoff as a bound parameter and store its value with the training set. Do not substitute CURRENT_TIMESTAMP inside the query. A query that reads the clock produces a different answer every time it runs.
Break ties deterministically
The ORDER BY ends with f.row_id DESC. Without it, two feature rows with the same event_ts and ingested_ts are ordered arbitrarily. The database may return a different winner after a statistics update, a different join plan, or a different cluster size. The rebuilt set then differs in a few rows, and you cannot tell why. Any total order works, as long as it is stable across runs.
The same applies to pandas. merge_asof requires sorted inputs, and sorting on a non-unique key is not guaranteed to keep the original order of equal rows unless you request a stable sort. Pass kind="stable" or add a unique column to the sort key.
features = features.sort_values(["feature_ts", "row_id"], kind="stable")Record a manifest
The knowledge cutoff alone is not enough. Store a small manifest next to every training set you may need to reproduce. It should contain:
- the hash of the exact SQL or code that built the set;
- the knowledge cutoff;
- the identifiers or versions of the input tables (snapshot IDs, table versions, or partition lists);
- the feature definition versions;
- the library and runtime versions;
- the row count, the column list, and a content fingerprint.
The fingerprint lets you check a rebuild without keeping a second copy of the data. It must not depend on row order, because the database does not promise one. It should hash every row and combine the hashes after sorting by the unique key.
import hashlib
import json
import pandas as pd
def fingerprint(df: pd.DataFrame, keys: list[str]) -> str:
"""Hash of the table contents, independent of row and column order."""
ordered = df.sort_values(keys).reset_index(drop=True)
ordered = ordered[sorted(ordered.columns)]
row_hashes = pd.util.hash_pandas_object(ordered, index=False)
return hashlib.sha256(row_hashes.to_numpy().tobytes()).hexdigest()
def build_manifest(df, sql_text, knowledge_cutoff, keys):
return {
"sql_sha256": hashlib.sha256(sql_text.encode("utf-8")).hexdigest(),
"knowledge_cutoff": knowledge_cutoff.isoformat(),
"row_count": int(len(df)),
"columns": sorted(df.columns),
"fingerprint": fingerprint(df, keys),
}
original = pd.DataFrame(
{
"customer_id": [1, 2, 3],
"prediction_ts": pd.to_datetime(["2026-01-05", "2026-01-05", "2026-01-06"]),
"avg_spend_30d": [40.0, 12.5, None],
"churned": [0, 1, 0],
}
)
keys = ["customer_id", "prediction_ts"]
cutoff = pd.Timestamp("2026-02-01T00:00:00Z")
manifest = build_manifest(original, "SELECT 1", cutoff, keys)
print(json.dumps(manifest, indent=2))
# A rebuild with shuffled rows matches. A changed value does not.
shuffled = original.sample(frac=1.0, random_state=0)
print(fingerprint(shuffled, keys) == manifest["fingerprint"]) # True
changed = original.copy()
changed.loc[0, "avg_spend_30d"] = 41.0
print(fingerprint(changed, keys) == manifest["fingerprint"]) # FalseSave the manifest as JSON in the same location as the dataset, and register its path with the trained model. When a model is questioned months later, the manifest tells you which data produced it.
The rebuild workflow
The following diagram shows the loop: record at build time, then rebuild and compare when needed.
A mismatch is useful information. Compare the row counts first. A different count points to deleted history or changed label filters. The same count with a different fingerprint points to changed values, tie-breaking, or a changed feature definition. Joining the two sets on the key and diffing columns usually shows the cause within minutes.
Keep the history that makes the rebuild possible
A manifest only helps if the inputs it names still exist. Three storage rules matter.
- Append only. Corrections are new rows with a later
ingested_ts. Never update a feature row in place, because the old value is what the first build saw. - Versioned definitions. If the logic behind
avg_spend_30dchanges, write the new values under a new feature name or version. Backfilling the old name with new logic silently rewrites history, and a rebuild with the old cutoff will either mix definitions or fail the fingerprint check. - Retention that respects reproducibility. If a retention job deletes rows older than a year, a rebuild after that point cannot match. Either archive the rows, or save a snapshot of the training set itself for models that must remain auditable.
Table formats with snapshots, such as Delta Lake, Iceberg, or a warehouse's time-travel feature, make this cheaper. You record the snapshot ID in the manifest and read the table at that version. Time travel windows are usually limited, so check how long yours lasts. For a regulated model, a copy of the final training set in object storage is often simpler and more reliable than relying on a retained snapshot.
Edge cases
- Deletion requests. If a customer's data must be erased, an exact rebuild is no longer possible. Record in the manifest or an audit log that the set was built before the deletion, and expect the fingerprint to differ afterward. Privacy obligations take precedence over reproducibility.
- Time zones. Store timestamps in UTC and write the cutoff with an explicit offset, as in the example. A cutoff of
2026-02-01without a zone is interpreted differently by different systems. - Floating-point values. The same SQL can yield slightly different sums on different engines or versions because summation order changes. If the fingerprint matters, round feature values to a fixed precision before hashing, and say so in the manifest.
- Sampling. If the build samples rows, use a stored seed, or better, a hash of the key such as
MOD(HASH(customer_id), 100) < 10. A seeded random sample depends on row order, and row order is not stable. - Library versions. Joins and hashing can change behavior across pandas releases. Record versions, or run the build in a pinned container image and store the image digest.
Summary
A point-in-time correct join prevents leakage, but it does not freeze the inputs. To reproduce a set later, bound the build with a knowledge cutoff on ingested_ts and on label availability. Order ties deterministically and store a manifest with a query hash, cutoff, input versions, and a row-order-independent fingerprint. Keep feature history append-only and versioned. Then compare fingerprints on every rebuild.
Exercise
A team rebuilds a churn training set four months after the original build, using the same SQL and the same inputs tables. The ingested_ts <= prediction_ts filter is in place and the row counts match, but the fingerprint differs on about 0.2% of rows. List two likely causes and the fix for each.
Show answer
First, the label table changed: churn labels for some customers were revised after the original build. The fix is to filter labels with labeled_ts <= :build_cutoff using the stored cutoff, and to keep label history instead of updating labels in place. Second, ties in the as-of ordering: feature rows with identical event_ts and ingested_ts were resolved arbitrarily. The fix is to add a unique row_id as the final ORDER BY tie-breaker. Other valid causes are a backfill that rewrote a feature under the same name (fix by versioning the feature definition) and a changed library version affecting numeric values (fix by pinning the environment).
Exercise
Why must the fingerprint function sort the rows by a unique key before combining row hashes, and why is it a mistake to run the rebuild query with CURRENT_TIMESTAMP as the cutoff?
Show answer
The database does not guarantee row order, so two identical sets can come back in different orders, and a hash over the raw order would differ. Sorting by a unique key makes the fingerprint depend only on content. Using CURRENT_TIMESTAMP as the cutoff admits corrections and labels that arrived after the original build, so the rebuild would be a different dataset. The cutoff must be the stored value from the manifest.