In SQL, join on created time and keep the online TTL
Here is the created-time join in SQL, for one member's daily genre-affinity rows.
SELECT l.member_id, l.title_id, l.shown_at, l.played,
f.value AS genre_affinity
FROM labels AS l
LEFT JOIN LATERAL (
SELECT value
FROM member_genre_affinity AS f
WHERE f.member_id = l.member_id
AND f.created_at <= l.shown_at -- online when served
AND f.created_at > l.shown_at - INTERVAL '2 days' -- the online TTL
ORDER BY f.created_at DESC
LIMIT 1
) AS f ON TRUE;
Read it from the inside out.
LATERALlets the subquery see the current label rowl, so it runs once per label.- It keeps that member's rows that were online by
shown_at, and less than 2 days old then. - It sorts them newest first and takes one.
LEFT JOIN ... ON TRUEkeeps every label.genre_affinityisNULLwhen no row qualifies.
The TTL line matters as much as the first condition. A key-value store keeps serving the last value it holds until that value expires. Say row C went online Mar 3 at 04:10, then the batch failed for 3 days, and the online TTL is 2 days. Serving reads C, 0.52, until Mar 5 at 04:10, then nothing: a default. Training must get the same, so the offline TTL must equal the online one.
In the editor, write a new as_of(rows, t, ttl) that joins on created time and keeps the online TTL, like the SQL. Each row is a (value, event time, created time) tuple of datetimes: the tests use the three daily rows A, B and C, which land at 04:10 on Mar 1, 2 and 3.