A database that never disagrees, even when nobody is online.
Build an embeddable OLTP engine whose external surface looks like SQLite — tables, secondary indexes, joins, foreign-key cascades, uniqueness — and whose internal representation is CRDT all the way down. Multiple writers mutate locally without coordination. Merges converge. Invariants survive.
Motivation
Local-first applications, multi-region deployments, and offline-tolerant systems all break against the same wall. CRDTs have solved blobs, registers, sequences, and sets. The relational primitives developers actually use — secondary indexes under concurrent inserts, foreign-key cascades under partition, range queries with deterministic order, uniqueness constraints — collapse the moment two writers diverge. Replicache, ElectricSQL, PowerSync, and Y-sweet each ship a partial answer. The full relational story remains open. It is a real systems problem with a real commercial wedge.
Challenge
Identify which relational invariants are natively CRDT-expressible (set membership, last-writer-wins fields, monotonic counters), which require lattice-respecting encoding (multi-value registers for conflicting cell writes, observed-remove sets for membership under concurrent insert/delete), and which fundamentally require a coordination protocol (uniqueness, escrow-style constraints, foreign-key existence under deletion). For each category, defend a chosen semantics and prove convergence — informally but rigorously.
Required Capabilities
- SQL Surface
CREATE TABLEwith a primary key and at least one secondary index.INSERT/UPDATE/DELETEover N concurrent peers without a coordinator. - Deterministic ReadsRange queries that return a deterministically merged result regardless of the order in which peer updates were applied.
- Foreign KeysCascade behavior under partition with a chosen, documented, defended semantics — not silence.
- UniquenessAt least one uniqueness constraint enforced via an explicit escrow or reservation protocol. Pure CRDTs cannot do this. Address it directly.
- SyncA pairwise sync protocol with bounded metadata and a written argument for eventual convergence.
Stretch Vectors
- BitemporalTransaction-time and valid-time queries over the merged history.
- Causal ReadsMonotonic-read and read-your-writes guarantees at the client.
- Schema MigrationOnline schema change under partition — the unsolved final boss.
Anti-Patterns · Auto-Disqualifying
- Server-Authoritative + Optimistic UIThis is the problem being solved, not the solution. Submissions that fall back to a single source of truth on conflict will be rejected.
- Row-Level LWWLast-writer-wins on the entire row is degenerate and fails on any non-trivial schema. Cell-level resolution is the floor.
- Unbounded MetadataVector clocks or version vectors that grow without bound in writer count. Garbage collection is part of the protocol, not an afterthought.
Deliverable
A working engine — Rust + WASM, TypeScript + IndexedDB, or any language with strong type discipline. Two laptops offline. Both INSERT rows. Both UPDATE different columns of the same row. One DELETEs a parent row while the other INSERTs a child. Reconnect over an unreliable network. Show: a deterministic merged state on both peers, a transcript of how each invariant was preserved, and a five-page architectural defense of every coordination decision you made.
The interesting code is not in the SQL parser. It is in the moments where the lattice breaks and you have to pick — and own — a coordination protocol.
The engine ships as either an embedded library OR a local-process daemon speaking a documented wire protocol. Pick one and stay with it.
Embeddeddb = open("./mydb", peer_id="A")
db.execute("CREATE TABLE ...")
db.execute("INSERT ...")
db.sync_with(peer_b) # pairwise, bidirectional
state_hash = db.snapshot_hash()
DaemonPOST /sql { "stmt": "INSERT ...", "params": [...] }
POST /sync { "peer": "B", "since": "<cursor>" }
GET /snapshot -> { "hash": "...", "tables": {...} }
All teams test against the same schema. Custom schemas are permitted in writeup discussion but not in the judged scenario.
SQLCREATE TABLE users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT
);
CREATE TABLE orders (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status TEXT NOT NULL,
total_cents INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX orders_by_user ON orders(user_id, status);
Three peers A · B · C. All start empty and disconnected. Operations execute locally in the order shown.
Sync semantics — Sync(a, b) is symmetric and bidirectional. Either argument may initiate; on return both peers reflect each other's known state per the engine's merge rules. Peer state changes only via local execution or sync; there is no broadcast.
TraceA: INSERT users (u1, alice@x.com, "Alice")
A: INSERT users (u2, bob@x.com, "Bob")
B: INSERT users (u3, alice@x.com, "Alice'") # uniqueness conflict on email
C: (after one-way sync from A — holds u1, u2)
C: DELETE users WHERE id = u1 # parent delete under partition
A: INSERT orders (o1, u1, "pending", 1200) # child insert vs deleted parent
A: UPDATE users SET name = 'Alice Cooper' WHERE id = u1
B: UPDATE users SET email = 'alice@ex.org' WHERE id = u1 # cell-level conflict
# Pairwise sync A↔B ↔ B↔C ↔ A↔C until quiescent.
Required assertions, run by judges:
- Bit-identical merged state across A, B, C — verified by snapshot hash.
- Uniqueness invariant on
users.emailholds. The winning row is documented and the loser is recoverable (not silently dropped). - Foreign-key behavior for
o1against the deletedu1is documented and consistent with your stated semantics (kept-with-tombstone / cascaded / promoted-to-orphan — your choice, but pick one and defend it). - Cell-level merge on
users.u1preserves both updates (name and email) without whole-row LWW. - Convergence is invariant under sync ordering: a randomized re-run produces the same final hash.
Sync metadata per row must be bounded by O(writers), where writers is the count of distinct peers that have written that row. Version vectors / vector clocks that grow per write are auto-disqualifying. Garbage collection is part of the protocol, not an afterthought.
Foreign-key behaviour under partition is not a per-row choice. Your engine declares one policy as a first-class property, applied uniformly across every FK conflict, every table, every run. Three policies are accepted:
- cascadeThe child row vanishes with the parent. Implementation cost: lowest. Concurrent child writes that referenced the deleted parent are lost — you must defend this trade-off in the writeup.
- tombstoneThe child row survives. Its
user_idcolumn references a tombstoned row preserved in metadata. Queries see the child; the engine documents that the parent is logically deleted but referentially live. - orphanThe child row survives with
user_idset toNULLor a documented sentinel. The relationship is severed; the child stands alone.
You declare the policy to the benchmark via --fk-policy {cascade|tombstone|orphan}. The harness asserts observed state matches the declaration on the (o1, u1) conflict in the reference scenario. Switching policy mid-run, or picking different policies for different tables, is disqualifying — one principled choice, defended in the writeup.
- PermittedExisting CRDT primitives (Automerge, Yjs, Loro, Diamond Types, Y-CRDT) used as register / sequence / set building blocks. The relational layer — indexes, joins, FK, uniqueness, query — must be your own work.
- ForbiddenUsing a server-side relational engine (Postgres / MySQL / SQLite as authoritative store) as the merged source of truth. SQLite as a local read-side cache is fine.
- RequiredDisclose every dependency in your README, including version pins.
- RepositoryGit link, public or private. Apache-2.0 / MIT preferred.
- QuickstartREADME must produce a green run on a clean machine in under 5 minutes.
- ReproducibilityDockerfile, Nix flake, or equivalent. The reference scenario must produce a bit-identical hash on judges' machines.
- Demo5-minute screen-recorded walkthrough of the reference scenario.
- Writeup3-page PDF defending: lattice choices per type, uniqueness protocol, FK protocol, sync protocol, metadata-growth analysis.
- AutomatedJudges run the reference scenario container. Check merged-state hash determinism and all invariants listed above.
- ChaosA hidden variant reorders the operation trace with a fresh random seed. Final state must hash identically to the original run.
- ManualWriteup graded on architectural defense, particularly the uniqueness and FK protocols.
- Live15-minute Q&A. Expect questions on convergence proofs and corner cases.
The full evaluation harness is open and runs on your machine. Pure Python, stdlib only, no network access, no external dependencies. Five steps from clone to score.
- Step 1 · Clone
Shell
git clone https://github.com/Sauhard74/Anvil-P-E cd Anvil-P-E/bench-p01-crdt - Step 2 · Read the interface
Open
adapter.py. Seven methods every submission must implement:open_peer,apply_schema,execute,sync,snapshot_hash,snapshot_state,close. - Step 3 · Write your adapter
Create
adapters/myteam.pyas a thin shim over your engine. For non-Python engines, bridge via subprocess, gRPC, or HTTP.adapters/myteam.py
from adapter import Adapter class Engine(Adapter): def __init__(self): self.peers = {} # peer_id -> your engine def open_peer(self, peer_id): self.peers[peer_id] = MyEngine.new() def apply_schema(self, peer_id, stmts): for s in stmts: self.peers[peer_id].execute(s) def execute(self, peer_id, sql, params=()): self.peers[peer_id].execute(sql, params) def sync(self, peer_a, peer_b): self.peers[peer_a].sync_with(self.peers[peer_b]) def snapshot_hash(self, peer_id): return self.peers[peer_id].state_hash() def snapshot_state(self, peer_id): return self.peers[peer_id].dump_tables() def close(self): for p in self.peers.values(): p.shutdown() - Step 4 · Self-check
Run the condensed battery.
--quickuses fewer seeds for fast iteration.Shell
You'll see a per-axis pass/fail matrix and a weighted score. Iterate until all axes pass.python self_check.py --adapter adapters.myteam:Engine \ --fk-policy tombstone --quick - Step 5 · Full run with arbitrary seeds
When the condensed run is green, drop
--quickfor the full battery. Stress-test with any L2 seeds — if your engine is correct, every seed passes.Shell
python run.py --adapter adapters.myteam:Engine --fk-policy tombstone \ --randomized-seeds 9999 31415 27182 16180 11235 \ --rand-peers 5 --rand-ops 150 --out report.json
The bench resists hardcoding by design. Three layers of evaluation:
- L1 · CanonicalThe 3-peer trace described above. Passing is necessary but not sufficient.
- L2 · Property-basedPass
--randomized-seedsany integers. Generator produces fresh ops per seed; assertions are pure CRDT invariants — convergence, uniqueness, idempotent sync. A hardcoded solution cannot pass because the expected hash is unknown until the run. - L3 · AdversarialHeld-out seeds and hand-crafted edge cases at higher parameter values. Used only at final evaluation. Not distributed.
Repository · Sauhard74/Anvil-P&E