All my work / Storage & data systems · by Ravindra Sawant
SnapshotDB
MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode.
Verified 2026-11-28; CI re-runs the acceptance tests on every push.
The problem
Concurrent transactions must see consistent data without blocking each other unnecessarily. This multiversion key/value store implements snapshot isolation, first-committer-wins conflicts and an atomic write-ahead log - and shows why snapshot isolation is not serializable.
What I found
- The classic doctors-on-call schedule violates its invariant under snapshot isolation (write skew) and is blocked by the optional serializable mode.
- A process killed after the WAL fsync but before the in-memory publish recovers both keys of the transaction atomically.
- Garbage collection keeps exactly the versions a long-running reader still needs, and reclaims them the moment it finishes.
Architecture
begin() ─(lock)─► snapshot = global_ts, register active snapshot
tx.get(k) ─► local write set ─► chains[k] = (versions, commit_ts list): newest ts ≤ snapshot (bisect) ─► tombstone ⇒ None
tx.put/delete ─► local write set (bounded) tx.scan(lo, hi) ─► sorted keys ∪ local writes
commit() ─(commit lock)─► for each written key: latest_ts > snapshot ⇒ WriteConflict (first committer wins)
[serializable] any read key or scanned-range key changed since snapshot ⇒ SerializationFailure
─► ts = global_ts + 1 ─► WAL: u32 len | u32 crc32 | {ts, tx, ops} ─► fsync ─► install versions ─► global_ts = ts
recovery ─► replay complete frames in ts order; truncate an incomplete tail; complete bad CRC / out-of-order ts ⇒ CorruptWAL
gc() ─(lock)─► floor = oldest active snapshot (or global_ts); per key keep newest ≤ floor + newer; drop tombstoned chains
when no snapshots are active (atomic pair swap so lock-free readers stay consistent)
- Read-only transactions commit without allocating a timestamp.
- A WAL write error marks the DB failed (fail closed) — restart to recover.
- Schedules in
examples/*.jsonare interleaved deterministically in file order (mvcc scenario).
| anomaly | snapshot | serializable (coarse) |
|---|---|---|
| dirty read / partial commit | prevented | prevented |
| lost update (same key) | prevented (FCW) | prevented |
| non-repeatable read | prevented | prevented |
| write skew | allowed | prevented |
| phantom (range) | stable snapshot; writer commits | writer aborts if range changed |
Requirements → tests
| Req | Pri | Requirement | Proven by | Status |
|---|---|---|---|---|
| FR-01 | P0 | begin at global committed version; get/put/delete with read-your-writes and repeatable snapshot reads | T01 | pass |
| FR-02 | P0 | Committed version chains; newest commit_ts <= snapshot; tombstones; uncommitted never visible | T01, T05 | pass |
| FR-03 | P0 | Serialized commit validation, first-committer-wins, one commit ts, atomic publish, rollback | T02, T03 | pass |
| FR-04 | P0 | One checksummed WAL frame per transaction, fsync before ack, ordered recovery, reject corrupt frame | T04 | pass |
| FR-05 | P1 | Safe version GC by oldest snapshot, snapshot range scans, coarse serializable read/range validation | T05, T03 | pass |
| Test | What it proves | Result |
|---|---|---|
| T01 | Repeatable read under concurrent commit; own writes visible; uncommitted invisible; rollback leaves nothing | pass |
| T02 | Barrier-synchronized concurrent commits: same key -> exactly one conflict; disjoint keys -> both commit | pass |
| T03 | Doctors-on-call write skew: invariant violated under SI (expected); serializable mode aborts one | pass |
| T04 | Kill after WAL fsync before publish -> recovered atomically; torn frame ignored; mid-WAL corruption fails | pass |
| T05 | Long reader pins versions through GC; reclaim after release; phantom behaviour under SI vs serializable | pass |
Benchmark
| Target (hypothesis from the spec) | Goal | Actual | |
|---|---|---|---|
| hot-key skew raises the write-write conflict rate (expected FCW behaviour) | hot > uniform | 0.019 vs 0.0005 | met |
| coarse serializable aborts at least as often as SI on identical workloads | >= | mean 0.0041 vs 0.0030 | met |
| GC reclaims superseded versions after the workload | > 0 | 314838 | met |
tps_si_uniform= 48576conflict_rate_hot= 0.019fsync_commit_p95_us= 52.1
quick run · 2026-11-28T23:57:43+00:00 · No universal TPS target: fsync dominates durable commits. GIL limits thread scaling.
Design questions
What does snapshot isolation guarantee?
Every transaction reads a consistent committed snapshot and two concurrent transactions cannot both commit writes to the same key (first committer wins).
Why is SI not serializable?
Write skew: two transactions read overlapping data but write disjoint keys, so no write-write conflict is detected, yet the combined result matches no serial order (doctors on call).
How do you make a multi-key commit atomic?
Write all of the transaction's writes as ONE checksummed log frame, fsync it, then install the versions and publish the commit timestamp; recovery replays only complete frames.
When can old versions be garbage collected?
Keep the newest version at or below the oldest active snapshot plus everything newer; long-running readers pin history, so cap or monitor them.
How does SSI differ from this serializable mode?
SSI tracks rw-antidependencies and aborts only dangerous structures; this mode conservatively aborts any transaction whose reads or scanned ranges changed - simpler, more aborts.
Limitations
- Single process, one global commit lock, no SQL/secondary indexes/deadlock manager
- Serializable mode is optimistic read/range validation, not production SSI
Run it
git clone https://github.com/ravirs/snapshotdb.git && cd snapshotdb
pip install -r requirements.txt
PYTHONPATH=src python -m mvccdb 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
- Watermark Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints
- Warden Data governance catalog: explainable grants, row filters, column masks, lineage impact
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