Join training labels to features without leaking the future
Feature stores build training sets with a point-in-time join: each label gets the feature value that was known AT the label's time, never a later one. Getting this wrong leaks the future into training and the model looks great offline and fails in production.
Write pit_join(labels, features, ttl, default).
- labels: list of (entity, ts) in any order.
- features: list of (entity, ts, value) in any order. If the same (entity, ts) appears more than once, the LAST one in the list wins (a correction).
- For each label, pick the feature row of the same entity with the largest ts that is <= the label ts. If none exists, or label_ts - feature_ts > ttl (stale), use default.
Return the list of values in the same order as labels. It must handle a few thousand rows quickly (sort once per entity and binary search; the bisect module is fine).
def pit_join(labels, features, ttl, default)Example
features [("u1", 10, 0.5), ("u1", 20, 0.7)], labels [("u1", 15), ("u1", 5), ("u1", 40)], ttl 15, default -1: [0.5, -1, -1] (40 - 20 = 20 > 15 is stale).
Understand the idea
When building a training set, each label must get the feature value that was known at the label's time, never a later one. Otherwise the model quietly learns from the future, looks great offline and fails in production. Values that are too old also expire after a ttl. Worked example: features for u1: (10, 0.5), (20, 0.7), (20, 0.9), the last being a correction that wins. ttl = 10, default -1. Label (u1, 25): the latest feature at or before 25 is ts 20, value 0.9, and 25 - 20 = 5 is within ttl. Label (u1, 8): no feature at or before 8, so -1. Label (u1, 35): latest is ts 20, but 35 - 20 = 15 > 10, stale, so -1. Answer [0.9, -1, -1]. Rule: group features by entity, keep the last value for duplicate timestamps, sort timestamps once, then for each label binary search for the largest ts <= label ts; return default if none or if label_ts - ts > ttl; keep the label order. Picking the nearest timestamp in either direction leaks the future. This is what feature stores do to build leak-free training data.