All my work / Storage & data systems · by Ravindra Sawant

Watermark

Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints.

Python 3.11+ · SQLite 429 lines of core code source on GitHub ↗ CI status

4/4 core requirements 11 tests passing 4/4 benchmark targets

Verified 2026-11-28; CI re-runs the acceptance tests on every push.

The problem

Real event streams arrive late, out of order and sometimes twice. This engine separates event time from processing time with per-partition watermarks, windowed aggregation, lateness routing and checkpoints that commit atomically with the output.

What I found

  • After a simulated crash at seven different points, restore-and-replay produced results identical to an uninterrupted run and to a deliberately naive O(n²) reference oracle.
  • A silent partition blocks the global watermark until an idle marker excludes it - and a returning partition can never move the watermark backwards.
  • Raising the disorder bound from 5 s to 30 s dropped late events from 4.7% to 0% while peak window state grew 329 → 554.

Architecture

source (JSONL, per-partition offsets) ─► skip offsets < committed next_offset (replay) ─► parse/validate
   ├─ malformed ─► errors side output (counted)          ├─ control: idle | end
   └─ event ─► dedup (key,id within retention) ─► window assignment (aligned, half-open)
             ─► for each window: WM ≥ end + lateness ? late output : keyed state[count,sum] (+ preliminary row)
             ─► max_ts[p] ─► WM = max(WM, min_active(max_ts[p] − disorder)) ─► finalize ready windows
every N records / finish() ─► ONE SQLite transaction: outputs upsert (final never reopens), late, errors,
                              state snapshot, dedup, next offsets, {wm, max_ts, idle, ended}
  • Event-vs-watermark order: an event is judged against the watermark before it advances it.
  • Unseen active partitions block the global watermark; idle excludes a partition until it sends again; end on all partitions sets WM = +∞ (explicit EOF flush).
  • Window id = key|start|end; late rows keyed by (partition, offset, window_start) → replay is idempotent.
  • oracle.py recomputes the watermark from scratch for every arrival (O(n²)) as an independent reference.

Requirements → tests

ReqPriRequirement Proven byStatus
FR-01P0Ingest partitioned events (id, key, ts, value); validate; track source offsets; arrival orderT01, T05pass
FR-02P0Tumbling + sliding half-open event-time windows; keyed count/sum; monotonic per-partition/global WMT01, T02, T03pass
FR-03P0Finalize at WM >= end + lateness; late-event output beyond it; optional preliminary updatesT02, T03pass
FR-04P0Atomic SQLite checkpoint of offsets + WM + state + outputs; restore and replay; deterministic window keysT04pass
FR-05P1Event-id dedup with bounded retention, idle/end signals, state metrics, malformed side outputT05, T03pass
TestWhat it provesResult
T01Boundary events (0, 59, 60): half-open tumbling and overlapping sliding windows vs oraclepass
T02Out-of-order inside lateness accepted; after finalization routed late; no reopen; WM never decreasespass
T03Unseen partition stalls WM; idle marker unblocks; returning partition can't move WM back; EOF flushes; stalled trace vs oraclepass
T04Crash before/after checkpoint at 7 cut points; restore + replay gives identical rows and no duplicate window keyspass
T05Duplicate ids within retention, malformed events counted + side output, state cap fails visibly, config validationpass

Benchmark

Target (hypothesis from the spec)GoalActual
state returns to zero at explicit EOF00met
recovery produces identical finalized resultsall parity[True, True, True]met
hypothesis: longer disorder/lateness -> fewer late drops, more statetrade-offlate 0.0466 -> 0.0, state 329 -> 554met
shorter checkpoint interval replays fewer recordsmonotonic[8004, 8004, 10004]met
  • events_per_s = 53537
  • late_ratio_ooo30_disorder5 = 0.0466
  • late_ratio_ooo30_disorder30 = 0.0

quick run · 2026-11-28T23:57:54+00:00

Design questions

Event time vs processing time?

Event time is when the event happened (in the record); processing time is when the engine sees it. Windows on event time give correct results despite delays and reordering.

What is a watermark?

The engine's assertion that no more events older than WM are expected. Here WM = min over active partitions of (max seen ts - disorder bound), never decreasing.

Why can one partition stall everything?

The global watermark is a minimum; a silent partition holds it back. Idle detection excludes it, at the risk of its late data becoming late events.

How do you get exactly-once output here?

Atomically commit source offsets, operator state and deterministic outputs in one transaction, then replay from committed offsets; external sinks need idempotent keys or 2PC.

What does allowed lateness trade?

Longer lateness keeps more window state open and delays final results, but drops fewer late events.

Limitations

  • Single logical operator; no distributed barriers, joins, session windows or retractions
  • Exactly-once only within the local SQLite sink

Run it

git clone https://github.com/ravirs/watermark.git && cd watermark
pip install -r requirements.txt
PYTHONPATH=src python -m streamwin demo   # demo
PYTHONPATH=src python -m pytest -q   # test
PYTHONPATH=src python benchmarks/bench.py --quick   # bench

More systems I've built from scratch

Storage & data systems

  • Strata LSM-tree key-value storage engine: WAL, SSTables with Bloom filters, atomic manifest, compaction
  • Tidelog Kafka-style durable partitioned log broker: CRC'd records, offsets, generation-fenced consumer groups
  • Floe Iceberg-style table format: immutable Parquet, manifests, snapshots, time travel, compare-and-swap commits
  • Flint Spark-style batch engine: lazy lineage, stage planning, shuffles, broadcast and salted skew joins
  • Warden Data governance catalog: explainable grants, row filters, column masks, lineage impact
  • SnapshotDB MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode

AI infrastructure

  • Nearline HNSW-style vector search index from scratch, measured against exact search
  • KVPager Paged KV cache with copy-on-write forks and prefix reuse (PagedAttention-style)
  • Batchwise LLM inference scheduler simulator: static vs continuous vs chunked-prefill batching
  • Steadyhand Durable AI agent runtime: allowlisted tools, approvals, budgets, crash recovery, replay
  • Toolgate Model Context Protocol gateway: curated tools, signed identity, tenant policy, approvals, audit

Distributed systems

  • Quorum Deterministic Raft consensus simulator with fault injection and an always-on invariant checker
  • Tandem Collaborative text editor on a sequence CRDT: offline edits, any delivery order, always converges
  • Burrow Minimal Linux container runtime in Go: namespaces, pivot_root, cgroup v2 limits

← See all my work: apps, ML/AI and systems