Review the prerequisites
Suitable for: Developers who can read failing assertions and compare two execution records.
- Algebra and business semantics of parallel state merging
- The reducer defines how deltas become shared facts. Replay requires that repeated input does not change the result, and parallelism requires that it does not rely on accidental arrival order; but deduplication, sorting, and conflict handling must obey business semantics, and all lists cannot be mechanically turned into sets.
How does the mechanism work?
Step-by-step explanation
- Why is list append not necessarily idempotent?
Recovery can reapply updates, so reason about idempotency using record identity.
- What should I do if two nodes return the same ID but different bodies?
Merging both deduplicates records and determines which content becomes trusted state.
- If the input version changes after restoration, can the old results still be used?
Idempotent updates do not establish that output remains applicable; also check input consistency.
Debugging · Diagnose failures
Debug · Preserve a red baseline, discriminate causes and rerun the same inputs
Objectives of this level: Reproduce a real local failure and retain a complete repair evidence trail.
Visual guide · Replay an event without rollback
This single-source protocol retains durable event identities. Replaying e1 returns its old receipt while the current state stays running at cursor 2. Select the figure to open it at full size.
Keep the repaired implementation and tests from the previous layer unchanged. Save the following baseline.py and run_experiment.py beside them. These are the remaining complete files needed for this experiment. The baseline intentionally contains the known defect; this is an authored repair drill, not an undisclosed production incident.
Before running, record two competing explanations: H1, running was not persisted across close/reopen; H2, running persisted but old e1 was treated as a fresh overwrite. The distinguishing observation is the task snapshot immediately after reopen and before e1 redelivery. Also predict whether an interrupted receipt insert leaves state and effect rows behind.
STATE_REPLAY_MODULE=baseline python3 -B -m unittest discover -v
python3 -B -m unittest discover -v
python3 -B run_experiment.py ./evidence
The first command must exit1; the second exits0. The experiment expects that contrast, exits0 and saves baseline-tests.txt, repaired-tests.txt, repair.diff and results.json. It uses the same test file and fresh temporary databases for both modules. Logs include actual stdout/stderr, exit codes, environment and source hashes; elapsed test-run time is not a service performance benchmark.
baseline.py
"""Intentionally broken: overwrite state; commit before the receipt; no replay identity."""
import json
import sqlite3
class Ledger:
def __init__(self, path):
self.db = sqlite3.connect(path, timeout=5, isolation_level=None)
self.db.executescript('''
CREATE TABLE IF NOT EXISTS tasks(id TEXT PRIMARY KEY, tenant TEXT, status TEXT, cursor INTEGER);
CREATE TABLE IF NOT EXISTS events(task_id TEXT, event_id TEXT, seq INTEGER, digest TEXT);
CREATE TABLE IF NOT EXISTS effects(id INTEGER PRIMARY KEY, task_id TEXT, event_id TEXT, action TEXT);
CREATE TABLE IF NOT EXISTS receipts(task_id TEXT, event_id TEXT, body TEXT);
''')
def close(self):
self.db.close()
def create(self, task_id, tenant):
self.db.execute("INSERT OR IGNORE INTO tasks VALUES(?,?,'waiting',0)", (task_id, tenant))
def apply(self, task_id, tenant, event):
self.db.execute('UPDATE tasks SET status=?,cursor=? WHERE id=?',
(event['status'], event['seq'], task_id))
self.db.execute('INSERT INTO events VALUES(?,?,?,?)',
(task_id, event['event_id'], event['seq'], json.dumps(event, sort_keys=True)))
self.db.execute('INSERT INTO effects(task_id,event_id,action) VALUES(?,?,?)',
(task_id, event['event_id'], event['status']))
receipt = {'receipt_id': task_id + ':' + event['event_id'],
'event_id': event['event_id'], 'seq': event['seq'], 'status': event['status']}
self.db.execute('INSERT INTO receipts VALUES(?,?,?)',
(task_id, event['event_id'], json.dumps(receipt, sort_keys=True)))
return {'status': 'committed', 'receipt': receipt}
def snapshot(self, task_id):
row = self.db.execute('SELECT status,cursor FROM tasks WHERE id=?', (task_id,)).fetchone()
return dict(status=row[0], cursor=row[1], **{table: self.db.execute(
'SELECT COUNT(*) FROM ' + table + ' WHERE task_id=?', (task_id,)).fetchone()[0]
for table in ['events', 'effects', 'receipts']})
run_experiment.py
"""Run the same local schedules and behavior tests against bad and repaired ledgers."""
import datetime
import difflib
import hashlib
import importlib
import json
import os
import platform
import sqlite3
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent
def event(seq=1, status='ready', event_id='e1'):
return {'event_id': event_id, 'source': 'executor', 'seq': seq, 'status': status}
def schedules(module):
Ledger = importlib.import_module(module).Ledger
with tempfile.TemporaryDirectory(prefix='state-replay-') as tmp:
path = str(Path(tmp) / 'replay.sqlite')
ledger = Ledger(path)
ledger.create('ticket-1', 'A')
first = ledger.apply('ticket-1', 'A', event())
ledger.apply('ticket-1', 'A', event(2, 'running', 'e2'))
before_close = ledger.snapshot('ticket-1')
ledger.close()
ledger = Ledger(path)
before_replay = ledger.snapshot('ticket-1')
replay = ledger.apply('ticket-1', 'A', event())
after_replay = ledger.snapshot('ticket-1')
ledger.close()
path = str(Path(tmp) / 'rollback.sqlite')
ledger = Ledger(path)
ledger.create('ticket-1', 'A')
ledger.db.execute("CREATE TRIGGER fail_receipt BEFORE INSERT ON receipts "
"BEGIN SELECT RAISE(ABORT, 'injected_receipt_failure'); END")
try:
ledger.apply('ticket-1', 'A', event())
except sqlite3.IntegrityError as exc:
interruption = str(exc)
rollback = ledger.snapshot('ticket-1')
ledger.close()
path = str(Path(tmp) / 'race.sqlite')
ledger = Ledger(path)
ledger.create('ticket-1', 'A')
barrier = threading.Barrier(2)
outcomes, failures = [], []
def worker():
own = Ledger(path)
try:
barrier.wait(timeout=5)
outcomes.append(own.apply('ticket-1', 'A', event())['status'])
except BaseException as exc:
failures.append(type(exc).__name__ + ':' + str(exc))
finally:
own.close()
workers = [threading.Thread(target=worker) for _ in range(2)]
for worker_thread in workers:
worker_thread.start()
for worker_thread in workers:
worker_thread.join(timeout=10)
if any(worker_thread.is_alive() for worker_thread in workers):
raise RuntimeError('worker_did_not_stop')
race = ledger.snapshot('ticket-1')
ledger.close()
return {'reopen_replay': {'first': first, 'before_close': before_close,
'before_replay': before_replay, 'replay': replay, 'after_replay': after_replay},
'interrupted_receipt': {'exception': interruption, 'after': rollback},
'two_connections': {'outcomes': sorted(outcomes), 'failures': failures, 'after': race}}
def main():
out = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else ROOT / 'evidence'
out.mkdir(parents=True, exist_ok=True)
runs = {}
for label, module in [('baseline', 'baseline'), ('repaired', 'state_replay')]:
env = dict(os.environ, STATE_REPLAY_MODULE=module, PYTHONDONTWRITEBYTECODE='1')
command = [sys.executable, '-B', '-m', 'unittest', 'discover', '-v']
started = time.perf_counter()
run = subprocess.run(command, cwd=ROOT, env=env, capture_output=True, text=True, timeout=30)
log = run.stdout + run.stderr
(out / (label + '-tests.txt')).write_text(log)
runs[label] = {'module': module, 'command': command, 'exit_code': run.returncode,
'elapsed_seconds': time.perf_counter() - started,
'log': label + '-tests.txt', 'log_sha256': hashlib.sha256(log.encode()).hexdigest(),
'observations': schedules(module)}
before = (ROOT / 'baseline.py').read_text()
after = (ROOT / 'state_replay.py').read_text()
diff = ''.join(difflib.unified_diff(before.splitlines(True), after.splitlines(True),
fromfile='baseline.py', tofile='state_replay.py'))
(out / 'repair.diff').write_text(diff)
fixed = runs['repaired']['observations']
assert runs['baseline']['exit_code'] == 1
assert runs['repaired']['exit_code'] == 0
assert fixed['reopen_replay']['after_replay'] == {
'status': 'running', 'cursor': 2, 'events': 2, 'effects': 2, 'receipts': 2}
assert fixed['two_connections']['outcomes'] == ['committed', 'replayed']
assert fixed['two_connections']['after']['effects'] == 1
result = {
'executed_at': datetime.datetime.now(datetime.timezone.utc).isoformat(),
'environment': {'python': platform.python_version(), 'sqlite': sqlite3.sqlite_version,
'platform': platform.platform()},
'input_origin': 'authored single-source state-transition events; actual local SQLite execution',
'test_origin': 'same test_state_replay.py for both modules; 10 test methods including negative controls',
'source_sha256': {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
for p in sorted(ROOT.iterdir()) if p.is_file()},
'runs': runs,
'diagnosis': {
'observation': 'Both modules reopen at running/cursor 2; only the bad baseline regresses after e1 delivery.',
'excluded_hypothesis': 'The durable running state was lost during close/reopen.',
'cause': 'The baseline treats a repeated old event as a fresh overwrite and commits state before the receipt.',
'repair': 'Check durable identity before transition; serialize writers and atomically commit state/cursor/event/effect/receipt.',
'negative_controls': ['changed payload with same event ID', 'different event ID at same sequence',
'sequence gap', 'new backward event', 'foreign tenant', 'wrong source', 'bool sequence']},
'limits': ['One local SQLite database and one executor sequence per task; no remote effect was sent.',
'Two threads used two SQLite connections. This is not a multi-host or throughput test.',
'The trigger aborts receipt insertion. No process kill, disk corruption or power-loss test ran.',
'Caller tenant and source are authored trusted-adapter inputs, not authenticated credentials.',
'No live model, tokens, bill, production incident or population reliability claim.']}
(out / 'results.json').write_text(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True) + '\n')
print(json.dumps({label: {'test_exit': run['exit_code'],
'replay_state': run['observations']['reopen_replay']['after_replay'],
'race': run['observations']['two_connections'],
'interrupted': run['observations']['interrupted_receipt']['after']}
for label, run in runs.items()}, ensure_ascii=False, indent=2, sort_keys=True))
if __name__ == '__main__':
main()
Actual observations and the cause they distinguish
| Schedule | Broken baseline | Repaired implementation |
|---|---|---|
| Before close and immediately after reopen | running/cursor2, two effects | running/cursor2, two effects |
| Deliver original e1 after reopen | ready/cursor1, three effects | running/cursor2, two effects; original receipt replayed |
| Two connections deliver e1 | committed + committed; two effects | committed + replayed; one effect |
| Trigger aborts receipt insert | ready/cursor1, one event/effect, zero receipts | waiting/cursor0, zero event/effect/receipt |
Both versions persist running, rejecting H1 for this input. The bad apply method then overwrites current state with an already committed event, supporting H2. Its autocommit statements also leave a local effect without a receipt. The repair's two necessary changes are durable identity reconciliation before evaluating a new transition, and one writer transaction around all local facts. Merely rejecting all backward messages would hide the duplicate acknowledgment problem; merely adding a cursor would not detect changed content under an old identity.
The shared suite ran 10 methods: baseline exited1 with 11 assertion failures, including two subcases in one method; repaired exited0. Negative controls include same ID with changed content, same sequence with different ID, a sequence gap, a new backward event, a foreign tenant, an incorrect source and bool as seq. Preserve these checks when making a smaller repair; do not change expectations to fit output.
The trigger tests a statement error inside the transaction. It does not simulate process death mid-COMMIT, disk damage or a remote action. Thread races use separate connections on one host; no claim of cross-host serialization follows.
Transaction timeline: race and receipt failure
Visual guide · Writer serialization and one atomic boundary
Two separate schedules from run_experiment.py: a two-connection same-event race and a receipt-insert trigger failure. A/B order is illustrative; sorted outcomes and final rows were observed. Select the figure to open it at full size.
These are separate fresh databases, not one continuous incident. In the race, two threads each construct a Ledger with its own SQLite connection, then cross the same barrier. Label whichever connection obtains the writer lock first A; wall-clock return order is not asserted. A enters BEGIN IMMEDIATE, sees no e1, validates seq1 and waiting→ready, then writes task status/cursor, events, effects, and receipts before commit. B can inspect the protected history only after obtaining that writer position. It finds the same e1/digest and returns replayed. Actual sorted outcomes were ['committed','replayed'], final ready/cursor1 and counts1/1/1; baseline returned two commits and left two effects.
For the interruption schedule, start over at waiting/cursor0. fail_receipt is a real SQLite BEFORE INSERT ON receipts trigger that raises injected_receipt_failure. The repaired transaction may have executed UPDATE task, INSERT event, and INSERT effect, but those changes are still uncommitted. When receipt insertion raises, leaving the transaction context rolls all writes back: snapshot is waiting/cursor0 and counts0/0/0. The separate existing test removes the trigger and reapplies e1 successfully. The captured experiment itself records the failure snapshot; it does not claim to kill a process or survive power loss.
Concrete counterexample: “receipt missing, therefore no effect” is false in the baseline. Autocommit leaves ready/cursor1, events1/effects1/receipts0 after the same exception. Likewise, moving the receipt insert later without enclosing the other writes in the transaction leaves the defect. Verify the full snapshot and error log, not only the response label. Two different event IDs claiming seq1 are another boundary: the test expects one commit and one sequence_conflict, not two independent operations at the same cursor.
Failure log, repaired log, repair diff, snapshots and source hashes. The observed baseline test process exited1 and repaired exited0 (10 methods). These schedules prove this local contract; they measure neither service throughput nor multi-host exclusion or remote-write atomicity.
Debug a green-looking replay using the durable ledger
In the replay exercise, record the current snapshot and cursor before delivering the original event again. If they move backward, checking only the final completed label hides the first failure. If a conflicting payload is accepted, inspect the event digest and saved receipt before blaming arrival order. A transaction-abort probe must leave all covered local rows unchanged.
Continue through the same interrupted return and run the unchanged verifier. Source-bound evidence separates expected conflict rejection from completed business effect. A copied green report cannot establish either; the verifier reads the actual database and receipt binding.
Continue the connected project article and inspect the executable entrypoint.
code example
A stale delivery is not a fresh backward command
After running, original e1/seq1/ready replays. New e3/seq3/ready fails status_transition. Keeping both assertions prevents a repair that rejects useful acknowledgments or permits a new backward write.
Acceptance task for this level
Write the two hypotheses before running. Execute all three commands, attach the before-replay observation that excludes H1, the bad/repair diff and unchanged-input red/green logs. Explain the separate identity and partial-commit faults, then retain every negative control.
Reading this browser’s record…
Hide the answer and check your understanding
Would checking seq<=cursor and silently returning success be an adequate repair?
Expand reference derivation
No. It fails to detect the same event ID with changed payload or another identity occupying a sequence, and it cannot return the exact old receipt. Retain identity/content evidence and distinguish conflict from identical replay.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.
- LangGraph:Thinking in LangGraph
- LangGraph: Checkpointing and cross-thread storage
- LangGraph: state and reducer
- Public fixed function contract
- Shared function runner
- Source-only practice package
- Harness Journey: one connected practical project
- Bilingual project guide and fault exercises
- Harness Journey source ZIP