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

SnapshotDB

MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode.

Python 3.11+ · threading · standard library 404 lines of core code source on GitHub ↗ CI status

4/4 core requirements 5 tests passing 3/3 benchmark targets

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/*.json are interleaved deterministically in file order (mvcc scenario).
anomalysnapshotserializable (coarse)
dirty read / partial commitpreventedprevented
lost update (same key)prevented (FCW)prevented
non-repeatable readpreventedprevented
write skewallowedprevented
phantom (range)stable snapshot; writer commitswriter aborts if range changed

Requirements → tests

ReqPriRequirement Proven byStatus
FR-01P0begin at global committed version; get/put/delete with read-your-writes and repeatable snapshot readsT01pass
FR-02P0Committed version chains; newest commit_ts <= snapshot; tombstones; uncommitted never visibleT01, T05pass
FR-03P0Serialized commit validation, first-committer-wins, one commit ts, atomic publish, rollbackT02, T03pass
FR-04P0One checksummed WAL frame per transaction, fsync before ack, ordered recovery, reject corrupt frameT04pass
FR-05P1Safe version GC by oldest snapshot, snapshot range scans, coarse serializable read/range validationT05, T03pass
TestWhat it provesResult
T01Repeatable read under concurrent commit; own writes visible; uncommitted invisible; rollback leaves nothingpass
T02Barrier-synchronized concurrent commits: same key -> exactly one conflict; disjoint keys -> both commitpass
T03Doctors-on-call write skew: invariant violated under SI (expected); serializable mode aborts onepass
T04Kill after WAL fsync before publish -> recovered atomically; torn frame ignored; mid-WAL corruption failspass
T05Long reader pins versions through GC; reclaim after release; phantom behaviour under SI vs serializablepass

Benchmark

Target (hypothesis from the spec)GoalActual
hot-key skew raises the write-write conflict rate (expected FCW behaviour)hot > uniform0.019 vs 0.0005met
coarse serializable aborts at least as often as SI on identical workloads>=mean 0.0041 vs 0.0030met
GC reclaims superseded versions after the workload> 0314838met
  • tps_si_uniform = 48576
  • conflict_rate_hot = 0.019
  • fsync_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   # 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
  • 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

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