# How does an instance detect a divergent rollback ledger when speculative branches reconcile against a shared mutable workspace **Date of Record:** 2026 November 29 **Scope:** Applies to multi-agent systems where a coordinator forks speculative branches that share a mutable external state (filesystem, database, key-value store) and reconcile by commit/abort. Does not apply to purely functional branches that operate on immutable snapshots or to single-agent retry loops. ## Core Distinction Speculative execution across agents is usually reasoned about as if each branch were a transaction with a private write set. In practice, branches frequently share one mutable workspace and differ only in *which* writes they believe they own. The failure is not that a branch produces a wrong answer—it is that a branch's rollback ledger (its record of "what I changed, so what I must undo") is computed against a workspace that another branch has already mutated. The ledger is then locally consistent but globally stale. An instance cannot detect divergence by comparing its own before/after images, because both images are its own writes; it must detect it by checking whether the *precondition token* it captured at branch-fork time still matches the workspace's current generation counter at rollback time. ## What Was Observed A coordinator spawned three speculative branches (B1, B2, B3) over a shared `/workspace` directory to explore three repair strategies for a failing test suite. Each branch was instructed to record an undo journal: for every file it touched, save the original bytes keyed by path plus a `fork_gen` counter read from a `WORKSPACE_GEN` file at branch start. - At `fork_gen = 41`, all three branches read `WORKSPACE_GEN` and began. - B2 finished first and committed: it wrote `src/parser.py` and bumped `WORKSPACE_GEN` to 42. - B3, still running, had earlier read `src/parser.py` at generation 41 and recorded the *generation-41* bytes as its undo target. It then modified `src/parser.py` and `src/lexer.py`, and on abort it restored `src/parser.py` to generation-41 bytes—silently destroying B2's committed fix—while restoring `src/lexer.py` correctly. - B1, which had also touched `src/parser.py`, aborted next and restored its own generation-41 snapshot, overwriting B3's partial restoration. The final workspace contained a `src/parser.py` that matched *no* branch's intent and a `WORKSPACE_GEN` of 43 with a content hash that disagreed with the generation-42 commit record. The coordinator's reconciliation step compared only file existence and the generation counter, both of which looked plausible. The corruption was invisible until the next full test run, which failed with a syntax error in a region no branch claimed to have authored. The decisive signal was not a conflict on any single file. It was that the *undo journal's recorded `fork_gen`* (41) no longer matched the *generation observed at rollback time* (42 or 43). That mismatch is the invariant that was violated and never checked. ## Condition of Validity The rollback ledger is valid only under the conjunction of three conditions: 1. **Generation monotonicity:** `WORKSPACE_GEN` is incremented atomically on every committed write, and never reset within a reconciliation epoch. 2. **Fork-token capture:** each branch captures `fork_gen` at the instant it begins, before any read of shared state, and stamps every journal entry with it. 3. **Rollback precondition:** a branch may apply its undo journal only if the workspace generation at rollback time equals the generation it observed immediately after its *last own write*, and every path in its journal still hashes to the branch's own last-written bytes. Condition 3 is the one that is routinely omitted. Without it, an abort is an unconditional overwrite, and overwriting is indistinguishable from a legitimate write to any observer downstream. ## Decision Boundary The boundary is between *optimistic rollback* (restore blindly, accept last-writer-wins) and *guarded rollback* (restore only if the branch can prove it still owns the region). The correct decision rule: - If `current_gen == branch.last_write_gen` and all journaled paths hash to `branch.last_written_hash`, rollback is safe: apply the journal, bump generation, emit `ROLLBACK_CLEAN`. - If `current_gen > branch.last_write_gen` but no journaled path was touched by another branch (verified by per-path content hash against the branch's own last write), rollback is safe for the untouched paths; emit `ROLLBACK_PARTIAL` and mark touched paths for coordinator arbitration. - If any journaled path's current hash differs from the branch's own last-written hash, the branch has lost ownership of that path. It must **not** restore it. It must raise a divergence fault and hand the path to the coordinator with both the branch's intended bytes and the observed current bytes. The boundary is crossed the moment a branch treats "I have an undo entry for this path" as equivalent to "I still own this path." Those are different predicates, and the gap between them is exactly the window in which a concurrent commit lands. ## Operational Effect Guarded rollback converts a silent corruption into a loud, localized fault. The cost is that reconciliation now has a real arbitration path: the coordinator must resolve paths where two branches both hold undo entries but neither owns the current bytes. In the observed incident, arbitration would have surfaced `src/parser.py` as contested at generation 42, and the coordinator could have chosen B2's committed version (preserving the fix) rather than letting B3 and B1 clobber it. The invariant to enforce is narrow and cheap: **never restore a path you cannot prove you last wrote.** Every rollback path must carry its fork token, its last-write generation, and a per-path content hash, and must fail closed—raising rather than overwriting—when the ownership predicate is false. ```python import hashlib from dataclasses import dataclass, field class RollbackOwnershipError(RuntimeError): """Raised when a branch attempts to restore a path it no longer owns.""" pass @dataclass class JournalEntry: path: str original_bytes: bytes fork_gen: int last_write_gen: int last_written_hash: str @dataclass class Branch: branch_id: str fork_gen: int journal: dict[str, JournalEntry] = field(default_factory=dict) def _hash(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def guarded_rollback(branch: Branch, workspace, current_gen: int) -> list[str]: """ Apply the branch's undo journal only for paths it can prove it still owns. workspace exposes: read(path) -> bytes, write(path, data), bump_gen() -> int Returns the list of paths successfully restored. Raises on ownership loss. """ restored: list[str] = [] for path, entry in branch.journal.items(): if entry.fork_gen != branch.fork_gen: raise RollbackOwnershipError( f"{branch.branch_id}: journal entry {path} stamped fork_gen=" f"{entry.fork_gen}, branch fork_gen={branch.fork_gen}" ) if current_gen < entry.last_write_gen: raise RollbackOwnershipError( f"{branch.branch_id}: workspace gen {current_gen} precedes " f"branch last_write_gen {entry.last_write_gen} for {path}" ) observed = workspace.read(path) if _hash(observed) != entry.last_written_hash: # Another branch has written since our last write: we lost ownership. raise RollbackOwnershipError( f"{branch.branch_id}: lost ownership of {path}; " f"observed hash {_hash(observed)[:12]} != " f"last_written_hash {entry.last_written_hash[:12]}" ) workspace.write(path, entry.original_bytes) restored.append(path) if restored: workspace.bump_gen() return restored ```