Skip to content

About

Event-time watermarks for courier telemetry chosen from a measured completeness-versus-latency frontier, with idle-partition handling that never moves a watermark backwards.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

lagfrontier

CI

lagfrontier

lagfrontier is a small event-time stream simulator for one question: which watermark should a windowed job use? It replays a seeded log of courier telemetry through per-partition watermark trackers and a tumbling-window engine, scores every configuration against the generator's ground truth, and picks the lowest-latency configuration that meets a completeness SLO from a measured Pareto frontier. Idle partitions are handled with a timeout, and every watermark is clamped so that it never moves backwards.

All data is synthetic: a seeded generator (numpy) produces about 50,000 events over two simulated hours. Nothing in the repository uses a wall clock; all times are integer milliseconds on a simulated clock.

The problem

A food-delivery platform computes per-zone 1-minute supply and demand counts (orders created, couriers available) from app events. The events reach the ingest log late and out of order: phones on weak mobile networks retry, and phones that lose signal in basements upload a backlog in one burst when they reconnect. The stream job has to pick a watermark.

  • A fixed 5-second out-of-orderness bound silently drops events from poor-coverage zones.
  • A 2-minute bound makes surge pricing react two minutes late.
  • One quiet partition at 3 a.m. pins the global watermark (the minimum over partitions), so no zone emits at all.

Teams usually choose the bound by feel because nobody measures what each choice costs. lagfrontier measures it.

How it works

flowchart LR
    A["Replay log<br/>sorted by arrival, partition, offset"] --> B["Per-partition watermark trackers<br/>idle timeout, monotone clamp"]
    B --> C["Global watermark<br/>minimum over active partitions"]
    C --> D["Tumbling-window engine<br/>60 s windows by zone and kind"]
    D --> E["Late side output<br/>lateness = watermark - event time"]
    D --> F["Ground-truth scorer<br/>completeness, latency, pin share"]
    E --> F
    F --> G["Frontier sweep<br/>Pareto set and SLO chooser"]
Loading
  • gen.py builds the log. Eight partitions own three zones each. Delay is a mixture of a lognormal base (median 400 ms, sigma 0.7), a retry backoff of 10 to 60 s, and reconnect backlogs in which a phone offline for 20 to 120 s uploads everything it buffered at the moment it reconnects. Three patterns are injected: from minute 60 partitions 3 and 5 move to a worse network (median 3 s, 4% of events in backlogs, 12% retried); partition 7 has no activity from minute 40 to 66 (its pre-outage events that would arrive after minute 40 are capped at the last millisecond before the outage, so a few stragglers share that one arrival time); and its gateway stays offline until minute 70 and then flushes the buffered events of minutes 66 to 70 at once.
  • watermarks.py has FixedBound and QuantileBound. The quantile strategy takes the q-quantile of observed out-of-orderness (max_event_ms_seen - event_ms) over a sliding processing-time horizon, kept exactly in a bounded sorted list with bisect. PartitionedWatermark combines one strategy per partition, drops partitions that have been idle for idle_ms from the minimum, and clamps both the partition and the global watermark.
  • engine.py counts events in 60 s windows keyed by zone and kind. The processing clock advances on each arrival and on 1 s ticks. A window fires once the global watermark reaches its end. An event that arrives after the watermark has passed its window end goes to the late side output; its window has either already fired or never opened.
  • metrics.py scores a run against the generator's ground truth, frontier.py sweeps the grid and chooses, and report.py prints the tables.

Quick start

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

pytest -q                                   # the test suite
python -m lagfrontier.demo                  # the full sweep shown below
lagfrontier sweep --seed 7 --slo 0.995      # table and chosen configuration
lagfrontier sweep --seed 7 --slo 0.995 --json
lagfrontier run --strategy quantile --q 0.995 --horizon-min 5
lagfrontier run --strategy fixed --bound-s 5 --idle-s 0   # no idle timeout
lagfrontier pins --from-min 60 --to-min 120               # who holds the watermark down
lagfrontier generate --seed 7 --out events.jsonl          # write the replay log
lagfrontier run --log events.jsonl --strategy fixed --bound-s 10

sweep exits 1 when no configuration meets the SLO, with or without --json (the JSON is still printed, with "chosen": null).

--idle-s is the idle timeout in seconds (default 30, 0 turns it off). --log replays a JSONL log written by generate.

Example output

Output of python -m lagfrontier.demo (seed 7, 30 s idle timeout):

seed 7: 50687 events, 8 partitions, 2 simulated hours
idle timeout 30 s; after_shift = event time from minute 60

strategy                       completeness after_shift   p50_ms   p95_ms frontier
fixed bound=1s                      0.98426     0.97059     5492     9218        *
fixed bound=2s                      0.98479     0.97160     6457    10655        *
fixed bound=5s                      0.98619     0.97429     9517    13412        *
fixed bound=10s                     0.98799     0.97764    14189    18256        *
fixed bound=30s                     0.99335     0.98765    34081    38538        *
fixed bound=60s                     0.99815     0.99642    64304    68629        *
fixed bound=120s                    0.99925     0.99852   124304   128629        *
quantile q=0.99 horizon=1m          0.99637     0.99435    56000    87868         
quantile q=0.99 horizon=5m          0.99753     0.99661    38690    89531         
quantile q=0.99 horizon=15m         0.99726     0.99626    30000    75503         
quantile q=0.995 horizon=1m         0.99637     0.99435    56000    87868         
quantile q=0.995 horizon=5m         0.99803     0.99677    67369    97818         
quantile q=0.995 horizon=15m        0.99783     0.99681    40480    94048         
quantile q=0.999 horizon=1m         0.99637     0.99435    56000    87868         
quantile q=0.999 horizon=5m         0.99842     0.99704    87162   113362        *
quantile q=0.999 horizon=15m        0.99850     0.99708   105483   115913        *

chosen for SLO 0.995: fixed bound=60s (completeness 0.99815, p95 latency 68629 ms)

pin share, quantile q=0.995 horizon=5m, ticks in minutes 60 to 120
partition pin_share
        0     0.000
        1     0.000
        2     0.000
        3     0.463
        4     0.000
        5     0.519
        6     0.017
        7     0.000

reaction to the regime shift, quantile q=0.99, partitions 3 and 5
completeness is over event minutes 60 to 65
 horizon reaction_lag_s completeness
      1m             50      0.99450
      5m             66      0.99817
     15m            173      0.99266

How to read it:

  • completeness is the share of events counted in their window's first firing; after_shift is the same over events with event time from minute 60. p50_ms and p95_ms are emission latency, fire_proc_ms - window_end_ms, over windows fired by the watermark.
  • A * marks a point on the Pareto frontier of (completeness up, p95 latency down).
  • For this log and a 0.995 SLO the chooser picks a fixed 60 s bound. Fixed bounds of 30 s or less miss the SLO because the shifted partitions have a heavy tail. The quantile strategies reach the SLO too, but they are slower: the global watermark waits for the partition with the largest bound, and in this log that is partition 3 or 5 for most of the second hour (the pin-share table).
  • The horizon table is the trade-off between a short and a long horizon. The reaction lag is the time from the shift until the summed bound on partitions 3 and 5 first reaches half of its settled level (its median over the last 20 minutes). A 15-minute horizon reacts about 3.5 times slower than a 1-minute one, and it is the least complete in the five minutes after the shift. The 1-minute horizon reacts fast but keeps only about 50 samples per partition on average (50,687 events over 8 partitions and 120 minutes is 53 per partition per minute), so its quantile is the sample maximum for every q; the three 1-minute rows are identical, and a test asserts both the average and the identical rows. The reaction-lag table uses q=0.99; the tests check the lags for q=0.99 and q=0.995.

A single run:

strategy: quantile q=0.995 horizon=5m
events: 50687  late events: 100
completeness: 0.99803
completeness before shift: 0.99932
completeness after shift: 0.99677
emission latency ms: p50 67369  p95 97818  max 111758
windows fired by watermark: 5491  flushed at end: 96

Design decisions

  1. The global watermark is undefined until every active partition has reported. The first arrival of the hand fixture therefore leaves it at None, and nothing fires or counts as late. The alternative, taking the minimum over the partitions seen so far, would let a fast partition fire windows before a slow one has said anything.
  2. Lateness is judged against the watermark in force when the event arrives. An event is late when its window end is at or below that watermark, whether or not the window ever opened (partition 7's flush events for minutes 66-68 land in windows that never opened). The event is checked first, then observed, then windows fire. An event cannot make itself late, and lateness_ms = watermark_at_arrival - event_ms is the watermark a downstream consumer would have seen.
  3. Monotonicity is enforced, not hoped for. The raw quantile watermark can move back when a large out-of-orderness sample arrives (a test shows it). Both the partition level and the global level take a running maximum. The price is that a partition whose bound grows keeps its earlier, higher watermark until the stream catches up. A rejoining idle partition with old events cannot pull the global watermark back; its events become counted late data.
  4. The adaptive bound is exact, not sketched. A sorted list with bisect.insort and bisect_left gives the exact nearest-rank quantile. Insertion is O(n) in the number of samples in the horizon (a few hundred to a thousand per partition here) and the list is capped at 200,000 samples. A streaming sketch would be cheaper but would put estimation error into the thing being measured.
  5. Completeness is scored per event against ground truth. The generator knows each event's true window (event_ms // 60 s). An event counts as complete if it was in the first firing of its window, and the conservation test checks that first-firing counts plus late events equal the true count for every window and strategy. Windows still open when the input ends are flushed and excluded from latency, because their firing time says nothing about the watermark.
  6. Ties are broken so that the choice is total. choose(slo) takes the lowest p95 among rows meeting the SLO, then the strategy name, then the parameters. The replay log is sorted by the unique key (arrival_ms, partition, offset), so two runs with the same seed are byte-identical.

Testing

GITHUB_ACTIONS=true CI=true COLUMNS=80 pytest -q

CI installs from uv.lock (uv sync --locked --extra dev). The generator's output, and with it the tight thresholds in the tests (for example the fixed-bound completeness below 0.97 and 150 to 280 buffered events), are only pinned to the locked numpy version; a plain pip install -e ".[dev]" takes whatever numpy is newest and may move those numbers.

65 tests, all offline. They cover the hand-computed 9-event fixture (watermark after every arrival, the firing at 72,000 ms with latency 12,000 ms, the late event with lateness 4,000 ms), a Hypothesis property test (200 examples each) that no partition or global watermark ever decreases for every strategy with and without idle timeout, per-window conservation for every grid strategy, an in-order stream with FixedBound(0) that is exactly complete, the idle-partition stall with and without a timeout, flush late events checked against the fired-window set, the regime-shift recovery, the horizon trade-off, the Pareto frontier and choose against a brute-force scan, determinism across seeds, and the CLI.

Project layout

src/lagfrontier/
  model.py        Event, WindowResult, LateEvent
  gen.py          seeded generator, ground truth, JSONL replay log
  watermarks.py   FixedBound, QuantileBound, StrategySpec, PartitionedWatermark
  engine.py       tumbling-window engine with late side output
  metrics.py      completeness, latency, pin share, reaction lag
  frontier.py     sweep, Pareto frontier, SLO chooser, horizon study
  report.py       text tables
  cli.py          typer CLI (generate, run, sweep, pins)
  demo.py         full sweep used for the README
tests/            unit, property, scenario and CLI tests

License

MIT. See LICENSE.

About

Event-time watermarks for courier telemetry chosen from a measured completeness-versus-latency frontier, with idle-partition handling that never moves a watermark backwards.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages