All my work / Storage & data systems · by Ravindra Sawant
Watermark
Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints.
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;
idleexcludes a partition until it sends again;endon all partitions sets WM = +∞ (explicit EOF flush). - Window id =
key|start|end; late rows keyed by (partition, offset, window_start) → replay is idempotent. oracle.pyrecomputes the watermark from scratch for every arrival (O(n²)) as an independent reference.
Requirements → tests
| Req | Pri | Requirement | Proven by | Status |
|---|---|---|---|---|
| FR-01 | P0 | Ingest partitioned events (id, key, ts, value); validate; track source offsets; arrival order | T01, T05 | pass |
| FR-02 | P0 | Tumbling + sliding half-open event-time windows; keyed count/sum; monotonic per-partition/global WM | T01, T02, T03 | pass |
| FR-03 | P0 | Finalize at WM >= end + lateness; late-event output beyond it; optional preliminary updates | T02, T03 | pass |
| FR-04 | P0 | Atomic SQLite checkpoint of offsets + WM + state + outputs; restore and replay; deterministic window keys | T04 | pass |
| FR-05 | P1 | Event-id dedup with bounded retention, idle/end signals, state metrics, malformed side output | T05, T03 | pass |
| Test | What it proves | Result |
|---|---|---|
| T01 | Boundary events (0, 59, 60): half-open tumbling and overlapping sliding windows vs oracle | pass |
| T02 | Out-of-order inside lateness accepted; after finalization routed late; no reopen; WM never decreases | pass |
| T03 | Unseen partition stalls WM; idle marker unblocks; returning partition can't move WM back; EOF flushes; stalled trace vs oracle | pass |
| T04 | Crash before/after checkpoint at 7 cut points; restore + replay gives identical rows and no duplicate window keys | pass |
| T05 | Duplicate ids within retention, malformed events counted + side output, state cap fails visibly, config validation | pass |
Benchmark
| Target (hypothesis from the spec) | Goal | Actual | |
|---|---|---|---|
| state returns to zero at explicit EOF | 0 | 0 | met |
| recovery produces identical finalized results | all parity | [True, True, True] | met |
| hypothesis: longer disorder/lateness -> fewer late drops, more state | trade-off | late 0.0466 -> 0.0, state 329 -> 554 | met |
| shorter checkpoint interval replays fewer records | monotonic | [8004, 8004, 10004] | met |
events_per_s= 53537late_ratio_ooo30_disorder5= 0.0466late_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 # benchMore 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