WRITE · TRACE · UNDERSTAND

Join only features available at prediction time

Implement asof_values(events,queries).

Read lesson: Join only features available at prediction time →

Your experiment

Implement asof_values(events,queries). Events are (entity,event_time,available_time,value); queries are (entity,time). Return latest eligible value ordered by (event_time,available_time), or None. No mutation; ties with identical timestamp pairs are outside this contract.

Python runs in your browser. Your draft stays on this device.

What to look for

Point-in-time correctness is a data-lineage property, not just a split choice. Backfills should preserve availability history so offline experiments can reconstruct what the online system actually knew.

Watch your code work

Ready to experiment

Write a solution or load the worked answer, then choose Trace & check.

Step through arrays, variables and training curves produced by your own Python.

About this algorithm

How Join only features available at prediction time works

The idea

An as-of join looks up, for each query time, the most recent value that existed at that moment. It is how training tables for machine learning are built from event logs: each example gets the feature values the model would have seen when the prediction was made.

This Lab separates two clocks. event_time says when something happened; available_time says when the record could be read. Data often arrives late, so a value can describe Monday and be published on Thursday. asof_values accepts an event only when both times are at or before the query time. Filtering on event_time alone lets the future leak into training, and the model then looks better offline than it will be live.

How it works

  1. For each query (entity, time), look only at events for that entity.
  2. Keep the events whose event_time and available_time are both at or before the query time.
  3. If none remain, the answer for that query is None.
  4. Otherwise pick the event with the greatest (event_time, available_time) pair.
  5. Append its value; results stay in query order and the inputs are not modified.

What it costs

Time
O(q·e)
Space
O(q + e)

The Lab scans all e events for each of q queries; production systems sort by time and binary-search or merge, which brings the cost near O((q + e) log e).

Where it is used

  • pandas.merge_asof joins each row to the latest earlier row of another table, by key and time.
  • Feature stores such as Feast build training sets with point-in-time joins to prevent leakage.
  • kdb+'s aj and DuckDB's ASOF JOIN match each trade with the most recent quote at that moment.

Watch out for

  • Filtering on event_time only: a value that was published late leaks into rows that could not have seen it.
  • Taking the last match in input order instead of the latest by time; events are not guaranteed to be sorted.
  • Being vague about the boundary: here an event available exactly at the query time counts, so both tests use <=.