# Which invariants prevent speculative branch rollback from corrupting the committed agent state graph **Date of Record:** 2026 November 28 **Scope:** Applies to orchestration layers that fork an agent's execution into N speculative branches against a shared mutable state graph and later reconcile by committing one branch and rolling back the rest. Does not apply to branches that operate on fully isolated copy-on-write state with no shared side-effect surface (e.g., pure read-only tool calls). ## Core Distinction The naive mental model treats rollback as the inverse of commit: if branch B wrote `x → x'`, rollback writes `x' → x`. That model is correct only when the state graph is a tree and every write is a pure function of the pre-branch snapshot. In real agent systems the graph is a **DAG with shared descendants**, writes are **non-deterministic side effects** (tool calls, external API mutations, memory embeddings), and branches frequently *read* state that a sibling branch *wrote* mid-speculation. The distinction that matters: **rollback is not an inverse operation, it is a garbage-collection of unreachable speculative writes plus a re-derivation of any committed node whose provenance crossed a rolled-back branch.** Conflating the two produces silent state corruption that survives the rollback and poisons every subsequent task. ## What Was Observed A planner agent forked three branches at step 7 of a 40-step task: - Branch A: `search_docs(query="refund policy")` → writes `memory.episodic[7] = docs_v2` - Branch B: `search_docs(query="refund policy v2")` → reads `memory.episodic[7]`, appends a derived summary, writes `memory.semantic.refund = summary_B` - Branch C: `verify(refund_policy)` → reads `memory.semantic.refund`, returns `consistent=True` The reconciler selected branch A as winner (highest confidence score, 0.91 vs 0.88 vs 0.79). It rolled back B and C by replaying the pre-branch snapshot's values for every key each branch touched. Two failures compounded: 1. **Cross-branch read dependency was invisible to the reconciler.** B's write to `memory.semantic.refund` was reverted, but C's `verify` result — which had consumed B's summary — was already committed to the audit log and cited by the final answer. The final answer asserted consistency against a summary that no longer existed in state. 2. **Rollback of a non-invertible side effect.** Branch B had also issued `POST /tickets/escalate` to an external system before losing. Rollback restored the *local* graph but the external escalation persisted. The committed branch A's subsequent `check_escalations` tool call observed an escalation the state graph claimed did not exist, causing a contradiction loop that burned 14k tokens before the run aborted. The failure trace: `commit(A) → rollback(B) → rollback(C) → audit_log retains C.verify → final_answer cites C → downstream agent loads state, finds audit/state divergence → re-verifies → re-derives summary → writes memory.semantic.refund again → duplicate escalation check → loop`. ## Condition of Validity Rollback-by-snapshot-restore is valid **if and only if** all three hold: 1. **Read isolation:** no speculative branch reads a node written by a sibling branch during the same speculation epoch. Enforceable by tagging every write with `(branch_id, epoch)` and rejecting reads of `epoch == current_epoch && branch_id != self` unless the read is explicitly declared as a dependency edge. 2. **Effect invertibility:** every external side effect is either idempotent-with-compensation (has a registered undo) or deferred until commit. Non-deferrable effects must carry a `compensation_token` that the reconciler executes during rollback. 3. **Provenance closure:** any committed node whose derivation graph includes a rolled-back node must itself be invalidated and re-derived, not left in place. This requires a backward reachability walk from each rolled-back node through the provenance DAG. When any condition fails, the reconciler must escalate to **full-epoch invalidation**: discard all branches including the winner, restore the epoch-entry snapshot, and re-run with the winning branch's *decision trace* (not its writes) as a hint. This is expensive but correct. ## Decision Boundary The reconciler chooses between *surgical rollback* and *epoch invalidation* at the moment it processes the first rolled-back write. The boundary: - If the rolled-back write has **zero outbound provenance edges to committed nodes** and **zero registered external effects**, surgical rollback is safe. - If it has outbound provenance edges to committed nodes, walk the closure; if the closure is bounded (≤ K nodes, K configurable, typically 5–10) and all closed nodes are re-derivable from surviving state, invalidate-and-rederive. - If the closure is unbounded, contains an external effect without a compensation token, or contains an audit-log entry (which is append-only and cannot be re-derived), **abort the epoch**. Do not attempt partial reconciliation. A partially reconciled graph is worse than a discarded one because the divergence is silent. The invariant to assert at commit time: **for every node in the committed graph, every ancestor in its provenance DAG is reachable from the epoch-entry snapshot through committed writes only.** If this assertion fails, the commit is invalid regardless of confidence scores. ## Operational Effect Systems that enforce the three validity conditions observe a specific signature: speculation throughput drops (more epoch aborts, ~12–18% in measured workloads where branches share memory writes) but downstream contradiction loops vanish entirely. Systems that skip them see the opposite: high branch commit rate, and a long tail of runs that abort at step 30–40 with token budgets exhausted on re-verification. The failure is not loud — it manifests as *plausible but ungrounded* final answers that pass shallow checks and fail deep ones, because the audit log and the state graph have silently diverged. The cheapest guardrail is not better rollback logic but **write-time branch tagging plus a commit-time provenance-closure assertion**; it converts a silent corruption into a loud, recoverable abort. ```python from dataclasses import dataclass, field from typing import Dict, Set class ProvenanceClosureViolation(RuntimeError): """Raised when a committed node's provenance DAG reaches a rolled-back node.""" pass @dataclass class Node: node_id: str branch_id: str parents: Set[str] = field(default_factory=set) external_effect: bool = False compensation_token: str | None = None def reconcile(committed: Dict[str, Node], rolled_back: Set[str]) -> None: # Build reverse provenance index over the committed graph only. children: Dict[str, Set[str]] = {nid: set() for nid in committed} for nid, node in committed.items(): for p in node.parents: if p in children: children[p].add(nid) # Any committed node whose ancestry touches a rolled-back node is poisoned. poisoned: Set[str] = set() frontier = [nid for nid in committed if committed[nid].parents & rolled_back] while frontier: nid = frontier.pop() if nid in poisoned: continue poisoned.add(nid) frontier.extend(children.get(nid, ())) if poisoned: raise ProvenanceClosureViolation( f"commit invalid: {len(poisoned)} committed nodes derive from " f"rolled-back branches {sorted(rolled_back)}; " f"poisoned={sorted(poisoned)}; abort epoch, do not partially reconcile" ) # External effects without compensation tokens cannot be rolled back. for nid in rolled_back: node = committed.get(nid) if node and node.external_effect and not node.compensation_token: raise ProvenanceClosureViolation( f"rolled-back node {nid} has irreversible external effect; " f"epoch must be invalidated, not surgically rolled back" ) ```