Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Algebra and business semantics of parallel state merging

Move from field-owned batch merging to durable replay identity, atomic local commits and explicit remote boundaries.

Learning objectives: Explain and run durable cursor/identity/receipt reconciliation; diagnose stale replay and partial commits; design multi-source and retention boundaries.

Content checked: 2026-10-30 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Implementation · Build it. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Developers who can run Python standard-library programs and inspect SQL transactions.

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
  1. Why is list append not necessarily idempotent?

    Recovery can reapply updates, so reason about idempotency using record identity.

  2. 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.

  3. 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.

Implementation · Build it

Implement · Commit state, cursor, event and receipt together

Objectives of this level: Run a complete durable single-source protocol and verify two-connection replay.

Visual guide · Replay an event without rollback

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.

Create an empty folder on a computer. Save the two complete files below with their exact names. Python 3.9+ and the standard library are sufficient. No download, network or model key is required. Run from that folder:

python3 -B -m unittest discover -v

The executed reference run passed all 10 test methods. The tests include real close/reopen, two threads with separate SQLite connections, and a database trigger that aborts receipt insertion. They do not mock database behavior.

The protocol before the code

Each task has one executor source, cursor0 and initial state waiting. New state-transition events must have exactly event_id, source, seq, status. seq is a positive integer, never bool, and must equal cursor+1. A new event advances exactly one state waiting→ready→running→completed; no-op/read/log events are outside this transition stream. An occupied sequence with another event ID is sequence_conflict. This intentionally simple single-source contract does not invent an ordering for independent producers.

BEGIN IMMEDIATE claims the SQLite writer before reading event history. After checking the bound tenant, an existing (task_id,event_id) must have the identical normalized request digest, otherwise event_conflict. An identical match returns the saved receipt before testing a new transition. A new ID must claim the next unoccupied sequence and a legal state transition. State/cursor, event identity, local effect row and receipt then commit in one transaction; an exception rolls them all back. The hash compares content; it is not a signature or access token. The caller must bind source and tenant through a trusted adapter. snapshot is a privileged local diagnostic, not a tenant read API.

state_replay.py

"""One local SQLite authority. No model, HTTP side effect, or authentication provider."""
import hashlib
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 NOT NULL,
            status TEXT NOT NULL, cursor INTEGER NOT NULL);
          CREATE TABLE IF NOT EXISTS events(task_id TEXT, event_id TEXT, seq INTEGER, digest TEXT,
            PRIMARY KEY(task_id,event_id), UNIQUE(task_id,seq));
          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,
            PRIMARY KEY(task_id,event_id));
        ''')

    def close(self):
        self.db.close()

    def create(self, task_id, tenant):
        if any(type(v) is not str or not v for v in (task_id, tenant)):
            raise ValueError('input_shape')
        with self.db:
            self.db.execute('BEGIN IMMEDIATE')
            self.db.execute("INSERT OR IGNORE INTO tasks VALUES(?,?,'waiting',0)", (task_id, tenant))
            if self.db.execute('SELECT tenant FROM tasks WHERE id=?', (task_id,)).fetchone()[0] != tenant:
                raise ValueError('authorization')

    def apply(self, task_id, tenant, event):
        if (any(type(v) is not str or not v for v in (task_id, tenant))
                or type(event) is not dict or set(event) != {'event_id', 'source', 'seq', 'status'}
                or any(type(event[k]) is not str or not event[k] for k in ['event_id', 'source', 'status'])
                or type(event['seq']) is not int or event['seq'] < 1
                or event['status'] not in ['waiting', 'ready', 'running', 'completed']):
            raise ValueError('input_shape')
        if event['source'] != 'executor':
            raise ValueError('source')
        # The adapter must bind this source and tenant; model strings are not credentials.
        canonical = json.dumps({'task_id': task_id, 'tenant': tenant, 'event': event},
                               sort_keys=True, separators=(',', ':'))
        digest = hashlib.sha256(canonical.encode()).hexdigest()
        with self.db:
            self.db.execute('BEGIN IMMEDIATE')
            row = self.db.execute('SELECT tenant,status,cursor FROM tasks WHERE id=?', (task_id,)).fetchone()
            if row is None or row[0] != tenant:
                raise ValueError('authorization')
            old = self.db.execute('SELECT digest FROM events WHERE task_id=? AND event_id=?',
                                  (task_id, event['event_id'])).fetchone()
            if old:
                if old[0] != digest:
                    raise ValueError('event_conflict')
                receipt = self.db.execute('SELECT body FROM receipts WHERE task_id=? AND event_id=?',
                                          (task_id, event['event_id'])).fetchone()
                return {'status': 'replayed', 'receipt': json.loads(receipt[0])}
            if self.db.execute('SELECT 1 FROM events WHERE task_id=? AND seq=?',
                               (task_id, event['seq'])).fetchone():
                raise ValueError('sequence_conflict')
            if event['seq'] != row[2] + 1:
                raise ValueError('sequence_gap')
            states = ['waiting', 'ready', 'running', 'completed']
            if states.index(event['status']) != states.index(row[1]) + 1:
                raise ValueError('status_transition')
            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'], digest))
            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}
        # A normal block exit commits; an uncaught block exception rolls all four writes back.

    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']})

test_state_replay.py

"""Behavior tests shared by the intentionally broken and repaired local ledger."""
import importlib
import os
import sqlite3
import tempfile
import threading
import unittest
from pathlib import Path

Ledger = importlib.import_module(os.environ.get('STATE_REPLAY_MODULE', 'state_replay')).Ledger


def event(seq=1, status='ready', event_id='e1', **changes):
    return dict({'event_id': event_id, 'source': 'executor', 'seq': seq, 'status': status}, **changes)


class ReplayTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.path = str(Path(self.tmp.name) / 'ledger.sqlite')
        self.ledger = Ledger(self.path)
        self.ledger.create('ticket-1', 'A')

    def tearDown(self):
        self.ledger.close()
        self.tmp.cleanup()

    def test_old_ready_replay_after_reopen_preserves_running(self):
        first = self.ledger.apply('ticket-1', 'A', event())
        self.ledger.apply('ticket-1', 'A', event(2, 'running', 'e2'))
        self.ledger.close()
        self.ledger = Ledger(self.path)
        replay = self.ledger.apply('ticket-1', 'A', event())
        self.assertEqual(replay, {'status': 'replayed', 'receipt': first['receipt']})
        self.assertEqual(self.ledger.snapshot('ticket-1'),
                         {'status': 'running', 'cursor': 2, 'events': 2, 'effects': 2, 'receipts': 2})

    def test_changed_payload_under_same_event_id_is_rejected(self):
        self.ledger.apply('ticket-1', 'A', event())
        with self.assertRaisesRegex(ValueError, '^event_conflict$'):
            self.ledger.apply('ticket-1', 'A', event(status='running'))

    def test_same_sequence_with_another_event_id_is_a_conflict(self):
        self.ledger.apply('ticket-1', 'A', event())
        with self.assertRaisesRegex(ValueError, '^sequence_conflict$'):
            self.ledger.apply('ticket-1', 'A', event(event_id='different-id'))

    def test_gap_is_not_silently_skipped(self):
        with self.assertRaisesRegex(ValueError, '^sequence_gap$'):
            self.ledger.apply('ticket-1', 'A', event(2, 'ready', 'e2'))
        self.assertEqual(self.ledger.snapshot('ticket-1')['effects'], 0)

    def test_new_event_cannot_move_running_back_to_ready(self):
        self.ledger.apply('ticket-1', 'A', event())
        self.ledger.apply('ticket-1', 'A', event(2, 'running', 'e2'))
        with self.assertRaisesRegex(ValueError, '^status_transition$'):
            self.ledger.apply('ticket-1', 'A', event(3, 'ready', 'e3'))

    def test_receipt_failure_rolls_back_state_cursor_event_and_effect(self):
        self.ledger.db.execute("CREATE TRIGGER fail_receipt BEFORE INSERT ON receipts "
                               "BEGIN SELECT RAISE(ABORT, 'injected_receipt_failure'); END")
        with self.assertRaisesRegex(sqlite3.IntegrityError, 'injected_receipt_failure'):
            self.ledger.apply('ticket-1', 'A', event())
        self.assertEqual(self.ledger.snapshot('ticket-1'),
                         {'status': 'waiting', 'cursor': 0, 'events': 0, 'effects': 0, 'receipts': 0})
        self.ledger.db.execute('DROP TRIGGER fail_receipt')
        self.assertEqual(self.ledger.apply('ticket-1', 'A', event())['status'], 'committed')

    def compete(self, inputs):
        barrier = threading.Barrier(2)
        outcomes, failures = [], []
        def worker(item):
            ledger = Ledger(self.path)
            try:
                barrier.wait(timeout=5)
                try:
                    outcomes.append(ledger.apply('ticket-1', 'A', item)['status'])
                except ValueError as exc:
                    outcomes.append(str(exc))
            except BaseException as exc:
                failures.append(repr(exc))
            finally:
                ledger.close()
        threads = [threading.Thread(target=worker, args=(item,)) for item in inputs]
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join(timeout=10)
        self.assertFalse(any(thread.is_alive() for thread in threads), 'worker did not stop')
        self.assertEqual(failures, [])
        return sorted(outcomes)

    def test_two_connections_same_event_commit_one_local_effect(self):
        self.assertEqual(self.compete([event(), event()]), ['committed', 'replayed'])
        self.assertEqual(self.ledger.snapshot('ticket-1')['effects'], 1)

    def test_two_connections_different_intents_cannot_share_sequence(self):
        self.assertEqual(self.compete([event(), event(event_id='other')]),
                         ['committed', 'sequence_conflict'])
        self.assertEqual(self.ledger.snapshot('ticket-1')['effects'], 1)

    def test_unauthorized_tenant_cannot_replay_receipt(self):
        self.ledger.apply('ticket-1', 'A', event())
        with self.assertRaisesRegex(ValueError, '^authorization$'):
            self.ledger.apply('ticket-1', 'B', event())

    def test_untrusted_source_and_boolean_sequence_are_rejected(self):
        for item, reason in [(event(source='retriever'), 'source'),
                             (event(seq=True), 'input_shape')]:
            with self.subTest(reason=reason), self.assertRaisesRegex(ValueError, '^' + reason + '$'):
                self.ledger.apply('ticket-1', 'A', item)


if __name__ == '__main__':
    unittest.main(verbosity=2)

Observe without mistaking a receipt for current state

Save and run this optional snippet in the same folder:

import tempfile
from pathlib import Path
from state_replay import Ledger
with tempfile.TemporaryDirectory() as tmp:
    path = str(Path(tmp) / 'ledger.sqlite')
    ledger = Ledger(path)
    ledger.create('ticket-1', 'A')
    ready = {'event_id':'e1','source':'executor','seq':1,'status':'ready'}
    ledger.apply('ticket-1', 'A', ready)
    ledger.apply('ticket-1', 'A', dict(ready, event_id='e2', seq=2, status='running'))
    ledger.close()
    ledger = Ledger(path)
    print(ledger.apply('ticket-1', 'A', ready)['status'])
    print(ledger.snapshot('ticket-1'))
    ledger.close()

The observed protocol is replayed, then running/cursor2 with events2/effects2/receipts2. Return order between racing threads is not specified; the sorted outcomes are committed + replayed with one local effect. This is a tested schedule, not a throughput or multi-host guarantee.

Supplement: keep the pure function exercise separate

The existing function-only package still provides lab_runner.py and cases/agent-state-reducers.json. Its documented reduce_state(payload) merges notes and checks batch-local writers, sequences and transitions. Scaffold and implement it independently if needed. Its batch protocol allows its own documented operations; it has no durable processed-event cursor and is not this Ledger protocol. Passing its public cases does not prove the persistent behavior above.

Worked trace: old ready after durable running

Visual guide · Same e1 receipt; different current task state

Same e1 receipt; different current task state

Observed local SQLite replay after close/reopen. Both modules start at running/cursor=2; only baseline overwrites with old ready. Counts are events/effects/receipts. Select the figure to open it at full size.

Read the figure as two objects with different lifetimes: snapshot('ticket-1') is current task state; receipt is the durable result of one event. Start at {status: waiting, cursor: 0, events: 0, effects: 0, receipts: 0}. Apply {event_id: e1, source: executor, seq: 1, status: ready}: commit ticket-1:e1, set ready/cursor1 and counts1/1/1. Apply e2/seq2/running: the task advances to running/cursor2 with counts2/2/2. Close and reopen the database. The observed before_replay remains running/cursor2, so persistence loss cannot explain a later regression.

Redeliver exactly e1. In the repaired code, validation and tenant binding precede the lookup; BEGIN IMMEDIATE then protects the read/check/write boundary. The stored (task_id,event_id) and identical canonical digest select the old receipt before any new transition check. The return is {status: replayed, receipt: {receipt_id: ticket-1:e1, event_id: e1, seq: 1, status: ready}}; current tasks.status stays running and cursor stays 2. events, effects and receipts all stay 2. There is no new local effect. Here source=executor and tenant A are authored adapter inputs; strings alone do not authenticate a caller.

Concrete counterexample: treating the returned receipt.status=ready as a current-state snapshot would paint a regression in a UI even though SQLite still says running. The broken baseline really does regress because it repeats UPDATE/INSERT: after replay it is ready/cursor1 with counts3/3/3. Conversely, changing e1's payload is not a replay: the same ID with a different digest raises event_conflict. A fresh e3/seq3/ready is also rejected with status_transition; deduplication must not make new backward transitions legal.

Observed red/green results, same source runner, unchanged tests. Run the four Python files together with python3 -B run_experiment.py ./evidence. This is authored local SQLite execution, not model output or a production incident.

Continue in one runnable project: replay before recovery

Harness Journey attaches durable transition identity to the same return whose merchant response is lost. Open the queue/event walkthrough, then run python3 -B journey.py scenario --name replay_conflict --work /tmp/journey-replay. Distinguish an identical old delivery from a changed payload under the same identity and from a new backward transition. An old receipt acknowledges an earlier commit without replacing the current snapshot.

Follow the event cursor across the crash and workflow upgrade into completion; then compare the independent merchant receipt. The reducer transaction protects local workflow/event/receipt consistency. It cannot roll back the HTTP merchant effect, so the business operation key remains a separate identity. Download the complete source instead of combining unrelated labs with colliding module names.

Continue the connected project article and inspect the executable entrypoint.

code example

Authorization still applies to receipt replay

After A commits e1, applying the same event as tenant B raises authorization before returning any saved receipt. The fixture binds A/B directly; it has no login provider and does not claim to authenticate a real user.

Acceptance task for this level

Save the two complete files, run all tests and preserve the output. Independently predict replay versus a fresh backward event, then run those inputs. Identify the transaction boundaries and the identity check that precedes a new transition.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Why does one transaction include the receipt rather than writing it after the state update?

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.