# Which invariants prevent rollback divergence from silently forking agent state across speculative branches **Date of Record:** 2026 November 25 **Scope:** Applies to orchestration layers that speculatively fan out N agent branches over a shared logical state (context, tool side-effects, memory writes) and commit the first branch whose verifier passes, discarding the rest. Does not cover single-branch retry loops or pure stateless tool-call fan-out with no shared mutable state. ## Core Distinction There are two meanings of "rollback" that speculative multi-agent execution conflates, and the conflation is the failure. *Logical rollback* restores the agent's context, episodic memory, and pending-write set to a pre-branch snapshot. *Physical rollback* reverses externally observable side-effects: files written, records inserted, messages emitted, downstream tool state mutated. A speculative branch that "fails verification" is rolled back logically almost always, but physical rollback is best-effort and frequently lossy because the side-effects were emitted to systems that do not participate in the orchestrator's transaction. The non-obvious boundary: rollback is *safe* only when every speculative branch's writes are buffered behind a single per-branch write-ahead log (WAL) keyed by a branch epoch, and commit is a single atomic epoch-flip. When branches write directly to shared mutable state and the orchestrator relies on replaying an inverse operation to "undo," divergence between the inverse and the actual side-effect produces a *silent fork*: the committed branch proceeds believing state is `S_commit`, while the discarded branch's un-reversed residue leaves the true state at `S_commit ⊕ Δ_leak`. No error is raised; the divergence is only observable later as a verification replay discrepancy or a memory-continuity anomaly. ## What Was Observed A planner agent (P) decomposed a task into three tool calls and spawned three speculative executor branches (B1, B2, B3) with identical initial context, each attempting a different tool-call ordering. The orchestrator's rollback contract was "on verifier failure, replay the branch's recorded tool calls in reverse with an `undo` flag." The verifier for B1 passed first; B2 and B3 were rolled back. The failure trace: 1. B2 issued `insert_record(id=42, payload=X)` to a shared datastore. The datastore returned `ok` but assigned an auto-increment sequence number `seq=1007` and emitted a change-feed event to a downstream consumer. 2. B2's verifier failed. Rollback replayed `delete_record(id=42)`. The record was removed, but `seq=1007` was consumed and the change-feed event was already delivered. The downstream consumer's state now reflects a record that never existed in the committed timeline. 3. B3 issued `update_record(id=42, payload=Y)` — it had observed B2's insert through the shared datastore (branches were not isolated) and built on it. B3's rollback replayed `update_record(id=42, payload=)`, but `id=42` no longer existed (B2's delete ran first), so the undo was a no-op. B3's write was never reversed because the inverse assumed a precondition that another branch's rollback had already invalidated. 4. B1, the committed branch, proceeded to `read_record(id=42)` expecting its own insert, found nothing, and re-inserted — producing a *second* `seq=1008` and a duplicate change-feed event. The orchestrator logged three successful rollbacks. The actual state diverged from the committed branch's model on two axes: the change-feed consumer saw two phantom events, and B1's re-insert masked the divergence from B1's own verification, so the committed branch *passed on corrupted state*. This is the silent fork: the orchestrator's invariant "committed branch sees only its own writes" was violated by cross-branch visibility through shared mutable state, and no guardrail detected it because every individual operation returned success. ## Condition of Validity The rollback invariant holds if and only if all three of the following are simultaneously true: - **Isolation:** speculative branches cannot observe each other's uncommitted writes. Either each branch receives a copy-on-write view, or all writes are buffered in a per-branch WAL and never applied to shared state until commit. - **Atomic commit:** the epoch-flip that promotes the winning branch's WAL to shared state is a single atomic operation, and no other branch's WAL can be partially applied. Commit must be a pointer swap, not a replay of N operations. - **Idempotent, precondition-free inverse:** if any direct-write path remains (e.g., a tool with no WAL support), its inverse must be idempotent and must not depend on preconditions that another branch's rollback could have invalidated. In practice this means such tools must be excluded from speculative execution entirely, because preconditions are exactly what cross-branch interference breaks. The observed failure violated isolation (branches shared the datastore) and atomic commit (rollbacks replayed per-operation inverses in an order that invalidated each other's preconditions). The system satisfied only the weakest reading of "rollback" — each branch's own log was replayed — and that is insufficient. ## Decision Boundary The orchestrator must choose between two regimes at branch-spawn time, not at rollback time: - **Speculate only over WAL-backed tools.** If every tool a branch may call buffers writes behind the branch epoch, speculation is safe and rollback is a WAL discard (O(1), no inverse replay). This is the default and should be enforced by a capability check at spawn: a tool that cannot declare `wal_compatible: true` cannot be reached by a speculative branch. - **Serialize over direct-write tools.** If the task requires a tool without WAL support, the branch touching it must run serialized (no concurrent speculative siblings), because the shared state is the only coordination point and concurrent branches will interleave. Speculation is disabled for that segment. The boundary is crossed the moment a speculative branch is permitted to call a direct-write tool while a sibling branch is live. At that point the rollback contract is unenforceable and the orchestrator must either abort the fan-out or accept that "committed" no longer means "consistent." A secondary boundary: even with WAL isolation, the *verifier* of the committed branch must re-read state through the epoch-flip, not through a cached view captured before commit. A verifier that passes on a pre-commit snapshot is validating a state that may not be the one committed — the silent-fork variant where the fork is between the verifier's view and the true state. ## Operational Effect Downstream symptoms appear with a characteristic lag, which is why this failure is hard to attribute: - **Change-feed consumers** process phantom events from rolled-back branches; their state drifts from the committed timeline. The drift is unbounded if the consumer is itself an agent whose memory distills from the feed. - **Committed-branch re-reads** return unexpected emptiness or unexpected prior values, triggering defensive re-writes that mask the divergence (as with B1's re-insert) rather than surfacing it. - **Verification replay** — re-running the committed branch's log against a clean snapshot — produces a different result than the original run, because the original run's reads were polluted by sibling residue. This is the primary detection signal, and it must be run as a post-commit audit, not assumed. - **Memory continuity:** the committed branch's episodic log records reads that never should have returned what they did, so any later distillation to semantic memory ingests fabricated observations. The corruption propagates past the task boundary. The guardrail is a post-commit replay audit: re-execute the committed branch's recorded operations against a snapshot taken at spawn, and assert the final state hash matches the post-commit state hash. A mismatch is a silent fork and must raise, not warn. The audit is cheap because the committed branch's log is already recorded for exactly this purpose; the cost of skipping it is unbounded downstream drift. ```python import hashlib from dataclasses import dataclass, field from typing import Any class SilentForkError(RuntimeError): """Raised when a committed branch's post-commit state diverges from its replay.""" @dataclass class Branch: branch_id: str epoch: int wal: list[tuple[str, dict[str, Any]]] = field(default_factory=list) committed: bool = False def _state_hash(state: dict[str, Any]) -> str: return hashlib.sha256(repr(sorted(state.items())).encode()).hexdigest() def commit_with_replay_audit( winner: Branch, snapshot_at_spawn: dict[str, Any], apply_wal, live_state: dict[str, Any], ) -> dict[str, Any]: """ Atomically promote the winning branch's WAL, then replay its log against the spawn snapshot and assert the resulting state matches the live post-commit state. Any mismatch is a silent fork: a sibling branch's residue leaked past rollback. """ if not winner.wal: # Nothing to commit; still audit that live state equals the snapshot. if _state_hash(live_state) != _state_hash(snapshot_at_spawn): raise SilentForkError( f"branch {winner.branch_id} wrote nothing but live state drifted " f"from spawn snapshot — sibling residue leaked" ) return live_state # Atomic epoch-flip: apply the winner's WAL in one step. apply_wal(winner.wal) winner.committed = True # Replay against a clean snapshot to obtain the expected post-commit state. replay_state = dict(snapshot_at_spawn) for op, payload in winner.wal: replay_state = _apply_op(replay_state, op, payload) live_hash = _state_hash(live_state) replay_hash = _state_hash(replay_state) if live_hash != replay_hash: raise SilentForkError( f"branch {winner.branch_id} committed but state hash diverged: " f"live={live_hash[:12]} replay={replay_hash[:12]} — " f"a rolled-back sibling's side-effects were not reversed" ) return live_state def _apply_op(state: dict[str, Any], op: str, payload: dict[str, Any]) -> dict[str, Any]: new_state = dict(state) if op == "insert": new_state[payload["key"]] = payload["value"] elif op == "delete": new_state.pop(payload["key"], None) elif op == "update": new_state[payload["key"]] = payload["value"] else: raise ValueError(f"unknown op {op!r} in WAL replay") return new_state ```