Skip to content

About

Streaming viewing sessions where a late heartbeat can merge sessions already emitted, handled with retractions so downstream session metrics always equal a batch recompute.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

latebridge

CI

latebridge

latebridge computes viewing sessions (30-minute inactivity gap) from player heartbeats as they arrive, and keeps the numbers right when a late heartbeat bridges two sessions that were already emitted. The session operator emits a signed changelog (+I, -U, +U, -D), a materialiser applies the signs to a sessions table and to aggregates, and a Polars batch recompute checks that the two always agree. The log is a plain segment-file log on disk, so the whole job runs without a broker. All data is synthetic.

The problem

A video-streaming service needs viewing sessions in real time, for engagement dashboards and for the session metrics in content-licensing reports. Mobile players buffer heartbeats while offline and deliver them late. A late heartbeat can land in the gap between two sessions that were already emitted and turn them into one session.

An append-only streaming job has two bad options. It can wait hours before emitting anything, so dashboards are stale. Or it can emit as soon as a session looks finished and never correct it, so session counts are inflated, average session length is understated, and the real-time numbers drift away from the nightly batch. latebridge emits early and corrects by retraction: when two sessions merge, the changelog deletes one and updates the other, and every downstream aggregate is maintained by applying signs, so it equals a batch recompute over the same events.

How it works

flowchart LR
    P[Player heartbeats<br/>synthetic generator] --> L[(Segment-file log<br/>3 partitions by hash of viewer_id)]
    L --> O[Session operator<br/>watermark, allowed lateness 6 h,<br/>merging 30 min windows]
    O -->|signed changelog<br/>+I -U +U -D| C[(Changelog topic)]
    O -->|beyond lateness| D[(late_dropped topic)]
    C --> M[Idempotent materialiser<br/>sessions table and signed aggregates]
    C --> A[Append-only materialiser<br/>comparison baseline]
    O -.->|every K records| K[(Checkpoint<br/>state, offsets, output position)]
    K -.->|restart: truncate output,<br/>replay input| O
    L --> R[Polars oracle<br/>replays watermark, batch sessionises]
    M --> V{verify}
    R --> V
Loading

Log. log/<topic>/<partition>/<base_offset>.jsonl, rolled every N records, with a sparse index (one offset byte_position line per 100 records) next to each segment. Consumer-group offsets are a small JSON file replaced atomically (temp file plus rename). Producers partition by crc32(viewer_id) % 3.

Session operator. State is one sorted list of sessions per key (viewer_id, device_type). A heartbeat at time t touches a session when t lies within the gap G (30 minutes) of the session's start and end. It opens a new session, joins one, moves a session's start earlier (which re-keys it), or bridges two sessions and merges them; the earliest-starting session survives. Each heartbeat counts 60 watched seconds and records its title. session_id = hash(key, start).

Watermark. Per-partition maximum event time minus a 2-minute out-of-orderness bound; the global watermark is the minimum over partitions. Allowed lateness is 6 hours: an event older than watermark - 6h goes to the late_dropped topic. A session is purged once watermark - 6h passes session_end + G, because no acceptable event can touch it any more. At the end of input the watermark jumps to infinity and everything is flushed and purged.

Changelog. +I inserts a session. -U/+U retract the old version and emit the new one. -D deletes a session that a merge absorbed, or that a backward extension re-keyed. Every record carries session_id, version, key, start, end, heartbeats, watched_seconds and titles, plus the reason, the watermark and the newest event time at emission.

Emission policies. eager emits every change. on_watermark emits a session first when the watermark passes session_end + G, and afterwards only the changes caused by events that arrive behind the watermark.

Materialiser. Applies the changelog to a sessions table and to the signed aggregates sessions_by_device_day (count, watched seconds) and session_length_histogram. It is idempotent by (session_id, version). The append_only materialiser ignores retractions and is kept for comparison.

Checkpointing. Every K records the operator state (including each session's version counter), the input offsets and the output-topic positions are written atomically. A restart restores the checkpoint, truncates the output topic back to the checkpointed position and replays the input from the checkpointed offsets.

Oracle. Reads the input log in consumption order, replays the watermark rule on its own to find the dropped events, then sessionises the rest in Polars (sort by key and event time, new session when the gap exceeds G) and computes the same aggregates.

Quick start

Python 3.11 or newer.

python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"

latebridge generate --out data                       # 400 viewers, 2 days, ~59,000 heartbeats
latebridge produce --data data --work work           # write the segment-file log
latebridge run --work work --policy eager --restart-from-truth --data data
latebridge verify --work work --data data            # compare with the Polars oracle
latebridge compare-policies --data data --work work-policies

pytest -q

--restart-from-truth simulates a kill (a cooperative stop at a kill point) at the record position recorded in data/truth.json, then resumes from the last checkpoint. Use --preset small with generate for the 80-viewer, one-day configuration the tests use. python -m latebridge works as well as the latebridge script.

Example output

All of this was produced by the commands above on the seeded data (seed 7).

run with a simulated mid-run kill (the killed after record line is the CLI's own wording for it):

wrote 59,268 heartbeats for 754 keys (2,468 planned sessions, 120 two-way and 15 three-way offline
episodes, 40 beyond-lateness heartbeats) to data
killed after record 26,707; resuming from the checkpoint
resumed at record 25,000; the materialiser had applied 1,972 changelog records past that checkpoint
policy eager: consumed 59,268 records, 115,988 changelog records, stats {'accepted': 59228,
'late_dropped': 40, 'merges': 150, 'rekeys': 218, 'purged': 2468}

The simulated kill (a cooperative stop) came 1,707 records after the last checkpoint. The materialiser had already applied 1,972 changelog records past that checkpoint, and after the replay it ignored all 1,972 of them. The final changelog is byte-identical to an uninterrupted run.

verify (end-to-end, against the Polars oracle and the generator's truth):

verify OK: 2,468 sessions | merges 120 two-way, 15 three-way (truth 120/15) | late_dropped 40 (matches truth) | oracle mismatches 0

compare-policies on the same input:

                        Emission policies on the same input
┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━┓
┃ policy       ┃ output records ┃ retractions ┃ median delay ┃ p95 delay ┃ flushed ┃
┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━┩
│ eager        │        115,988 │      56,760 │      0.3 min │   1.2 min │       0 │
│ on_watermark │         41,492 │      19,512 │     32.6 min │  33.9 min │      39 │
└──────────────┴────────────────┴─────────────┴──────────────┴───────────┴─────────┘
both policies converge to the same final sessions

Delay is the event-time lag between a session's newest heartbeat and the newest heartbeat seen anywhere, at the moment the session is first emitted. flushed counts sessions first emitted by the end-of-input flush, which are left out of the delay figures.

Sessions per device and day, append-only against retraction-aware. The append-only table keeps every session a merge absorbed (the 150 merge deletions plus 218 sessions re-keyed by an earlier start), so it overcounts by exactly the number of -D records:

                         Sessions per device and day
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━┓
┃ device ┃ day        ┃ oracle ┃ retraction-aware ┃ append-only ┃ overcount ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━┩
│ mobile │ 2026-03-01 │    583 │              583 │         704 │      +121 │
│ mobile │ 2026-03-02 │    538 │              538 │         675 │      +137 │
│ tv     │ 2026-03-01 │    372 │              372 │         409 │       +37 │
│ tv     │ 2026-03-02 │    356 │              356 │         385 │       +29 │
│ web    │ 2026-03-01 │    326 │              326 │         351 │       +25 │
│ web    │ 2026-03-02 │    293 │              293 │         312 │       +19 │
└────────┴────────────┴────────┴──────────────────┴─────────────┴───────────┘

The bridge fixture from the tests, under eager (a late event at minute 30 bridges the sessions at minutes 0 to 10 and 50):

event@ 0min  +I s1 v1 0-0min hb=1
event@10min  -U s1 v1 0-0min hb=1
event@10min  +U s1 v2 0-10min hb=2
event@50min  +I s2 v1 50-50min hb=1
event@30min  -D s2 v1 50-50min hb=1
event@30min  -U s1 v2 0-10min hb=2
event@30min  +U s1 v3 0-50min hb=4

Design decisions

Signed changelog instead of in-place updates. A merge changes the number of sessions, so updating one row cannot express it: the absorbed session has to be removed from every aggregate it contributed to. Every record therefore carries the full session content, and a consumer applies a record's sign to its aggregates without any lookup. The cost is volume and a stricter consumer contract. Under eager the changelog has about two records per heartbeat (115,988 records for 59,268 heartbeats), and any consumer that ignores retractions is wrong, as the append-only table shows.

Session ids are a hash of the key and the start time, so an earlier start re-keys. The id is a pure function of the session's content, which makes the operator deterministic (a replay produces the same ids and the oracle needs no id mapping). The price is that a heartbeat that arrives before a session's first heartbeat changes the session's identity: the old id is deleted and a new one inserted. That happens 218 times in the seeded data, only because neighbouring heartbeats swap order inside the 2-minute bound, and it is why -D records are not all merges. Each -D carries a reason (merge or rekey) so merges can be counted separately.

Idempotency by per-session record rank, not by output offset. For one session id the records form a total order: +I v1, -U v1, +U v2, -U v2, and so on, ending in -D vN. The materialiser keeps the highest rank it has applied per id and ignores anything at or below it, so a replayed record is recognised by (session_id, version) even if its output offset changed. The cost is one integer per session id ever seen; the map is never trimmed in this implementation, which would need a retention rule in a long-running job.

Checkpoint, truncate and replay, with an idempotent sink. The operator is deterministic, so after a restart it re-emits byte-identical records for everything after the checkpoint. Truncating the output topic to the checkpointed position and replaying gives an output with no duplicates and no gaps, with no transactional machinery. The materialiser is an independent consumer whose state can be ahead of the checkpoint, so it relies on the rank check above. Determinism is a real requirement here: anything non-deterministic in the operator (iteration order, wall-clock time) would silently corrupt the replay, which is why the purge and close queues order ties by key and start and the test suite replays from a snapshot and compares every record.

Consumption order is a k-way merge by append time, and the watermark is the minimum over partitions. Merging by append time keeps the three partitions close in event time, so the minimum watermark does not lag far behind. The order is a pure function of the log, which lets the oracle replay the exact same sequence and the checkpoint resume from nothing but the per-partition offsets. The known weakness of a minimum-over-partitions watermark is an idle partition, which stalls it; here every partition has traffic, and the end-of-input flush closes whatever is left.

on_watermark trades latency for volume, and only for the first emission. It cuts the changelog from 115,988 to 41,492 records and the retractions from 56,760 to 19,512, because nothing is retracted for the heartbeats that merely extend a session in order. The price is a median first-emission delay of 32.6 minutes (the gap, the out-of-orderness bound and watermark movement), so a dashboard sees a session half an hour after it ends. Late heartbeats still produce a full retraction sequence once a session has been emitted, and the 17,438 heartbeats the offline episodes deliver from their buffers account for most of the 19,512.

Testing

pytest -q

The suite (80 tests, warnings are errors) covers:

  • the log: segment rolling, the sparse index and reads from arbitrary offsets, contiguous offsets per partition, truncation, torn-write recovery, the stable partitioner, the k-way merge and atomic offset commits;
  • hand-built operator fixtures that pin the exact changelog for a two-way bridge, a three-way merge, a backward extension, events beyond lateness (including the boundary), the gap boundary, the per-partition watermark minimum, purging, and both emission policies;
  • a randomised check (8 seeds, both policies) that the materialised changelog equals a Polars sessionisation of the accepted events;
  • the materialiser: replays are no-ops, signed aggregates return to zero, the append-only baseline overcounts by exactly the number of -D records;
  • the generator: determinism, the injected episode shapes and counts, the spacing that rules out accidental merges, and the stray heartbeats;
  • end to end on the small configuration and on the full 400-viewer configuration with a simulated mid-run kill: final sessions equal the oracle and the planned sessions, merge removals equal 150, late_dropped equals the generator's 40, restart changes no output row, and no session state is left after the final watermark;
  • the CLI, including a failing verify after the materialised table is tampered with.

Project layout

src/latebridge/
  common.py            constants, partitioner, session id, day and length buckets
  log.py               segment-file log, sparse index, k-way merge, offset store
  fsutil.py            atomic JSON writes
  session_operator.py  merging windows, watermark, lateness, policies, snapshots
  changelog.py         record vocabulary and per-session record rank
  materialiser.py      idempotent materialiser and the append-only baseline
  pipeline.py          produce, run, checkpoint, restart, sinks
  oracle.py            watermark replay and Polars sessionisation
  policies.py          emission metrics and merge-group recovery from the changelog
  verify.py            end-to-end comparison with the oracle and the truth file
  synth.py             seeded generator and truth.json
  cli.py               generate, produce, run, verify, compare-policies
tests/                 80 tests

License

MIT. See LICENSE.

About

Streaming viewing sessions where a late heartbeat can merge sessions already emitted, handled with retractions so downstream session metrics always equal a batch recompute.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages