# Why does an instance of a speculative branch executor corrupt the canonical state when its rollback boundary is drawn at the tool-call layer instead of the effect layer **Date of Record:** 2026 November 24 **Scope:** Applies to multi-agent systems that speculatively fork a shared execution context into parallel branches (branch prediction over candidate plans) and merge or roll back on divergence. Does not apply to single-agent linear execution, nor to stateless request/response fan-out where branches share no mutable state. ## Core Distinction The failure is not "speculation sometimes guesses wrong." Wrong guesses are the expected cost of speculation. The failure is that **rollback is scoped to the reasoning/tool-call log rather than to the effects those calls produced**. A branch executor typically records its speculative trace as an ordered list of `(thought, tool_call, tool_result)` tuples and treats "discard the trace" as "undo the branch." That is a valid inverse only if every tool call is *referentially transparent* — i.e., its only effect is the returned value captured in the trace. Real tool calls are not referentially transparent. `write_file`, `send_email`, `git push`, `INSERT`, `POST /orders`, and `kubectl apply` all leave residue in the world that is *not* represented in the trace tuple. When the branch loses the prediction race and is rolled back, the executor drops the trace and the canonical context reverts — but the residue persists. The canonical state now contains a *phantom effect*: an external mutation whose justifying reasoning has been erased. Downstream agents observe the world changed by a branch that, from their perspective, never ran. The invariant that must hold: **rollback of a branch must be a function of the effects it emitted, not of the log it recorded.** If the effect layer has no compensating action, the branch is not rollbackable and must not be speculatively executed against shared state. ## What Was Observed A planner agent decomposed a task ("reconcile inventory across two warehouses") into three candidate plans and forked three speculative branches against a shared `inventory` tool namespace. Each branch had a private context window and a shared tool gateway. The gateway logged calls but did not isolate effects — all branches wrote to the same backing store. Branch B2 (the eventual loser) executed: 1. `reserve(sku=4471, qty=120)` → `{ok: true, reservation_id: "r-9f2"}` 2. `decrement(warehouse="west", sku=4471, qty=120)` → `{ok: true}` 3. A reasoning step that concluded the reconciliation required a different allocation, which invalidated the branch's own premise. At step 3 the branch self-reported divergence. The branch scheduler marked B2 divergent, discarded its trace, and merged B1 (the winner). The canonical context after merge showed `west.sku_4471 = 880` — but the backing store showed `760`, because B2's `decrement` had committed and no compensating `increment` was ever issued. The reservation `r-9f2` also lingered, silently holding 120 units. The corruption was not detected at merge time. It surfaced two hops later when a fulfillment agent, trusting the canonical context's `880`, accepted an order for 850 units and oversold by 90. The failure trace is: - Branch effect emitted → effect committed in external store. - Branch self-invalidates → scheduler rolls back *trace*, not *effect*. - Merge writes winner's context as canonical → context and store now disagree. - Divergence is invisible because the rollback "succeeded" (trace dropped cleanly). - Downstream agent reads canonical context, acts on a value that no longer matches reality. The key observation: **the rollback reported success.** There was no error, no exception, no reconciliation mismatch flag. The executor's rollback contract was satisfied because the contract was defined over the wrong layer. This is why the failure is non-obvious — every local operation succeeded, and the corruption is a *relational* property between two stores that no single component owns. A second, subtler observation: branches that only *read* were safe. The corruption required at least one branch to emit a non-idempotent, non-compensable effect before self-invalidating. The window is precisely `[first effect emitted, divergence detected]`. A branch that diverges before its first effect is genuinely rollbackable; a branch that diverges after is not. ## Condition of Validity The "discard trace = undo branch" equivalence is valid **iff** every tool in the branch's reachable set satisfies one of: - **Idempotent and keyed:** replaying the call with the same idempotency key is a no-op (e.g., `PUT` with `If-Match`, or `reserve` keyed by `(branch_id, sku)`). - **Compensable:** a registered inverse exists and is guaranteed to run during rollback (saga-style), with the inverse itself idempotent. - **Read-only:** no external effect. If any reachable tool violates all three, the branch is **not speculatively executable against shared state** and must either (a) run against an isolated shadow store that is diffed and applied only on merge, or (b) be serialized (no speculation). The boundary must be enforced at *plan admission time*, not at rollback time — by the time you are rolling back, the effect is already in the world. Note the condition is over the *reachable* tool set, not the *actually called* set. A branch that "probably won't write" is not safe; the whole point of speculation is that the branch's behavior is not known in advance. Admission must assume any reachable non-compensable tool will be called. ## Decision Boundary The decision the executor must make at fork time: - **Shadow-store speculation:** branch writes go to a copy-on-write overlay; merge applies the winner's overlay atomically; losers' overlays are dropped. Cost: overlay must capture every effect, including calls to external services, which requires either a proxy or a transactional backing store. Valid when the effect surface is fully interceptable. - **Compensating-log speculation:** branch effects commit immediately but every effect appends a compensation entry to a durable log scoped to the branch. Rollback replays compensations in reverse. Valid when every reachable tool has a registered, idempotent inverse. Requires the compensation log to be crash-durable and the compensations to be *ordered* (a `decrement` compensation must not run before the `reserve` compensation it depends on). - **No speculation:** serialize branches. Valid always, costs latency. The wrong choice — and the one that produced the observed corruption — is **log-only rollback**: treat the trace as the state and assume effects follow. This is the default in most branch executors because it is the cheapest to implement and passes all single-branch tests. It fails only under the conjunction of (shared mutable state) ∧ (non-compensable effect) ∧ (post-effect divergence), which is exactly the regime speculative execution is built for. The boundary rule: **a branch may be admitted to speculative execution only if its reachable tool set is closed under the chosen rollback discipline.** If the planner can reach a tool outside that closure, the fork must be refused, not attempted-and-rolled-back. ## Operational Effect When rollback is drawn at the wrong layer, the system exhibits a specific and dangerous signature: **silent divergence between canonical context and external state, with a clean rollback audit trail.** This is worse than a crash, because a crash halts and surfaces; this corrupts and hides. The audit log shows every branch rolled back successfully, so post-hoc forensics cannot reconstruct which effects were orphaned without replaying the external store's own log against the branch traces — a join across two systems that were never designed to be joined. The blast radius is bounded by the divergence window and the number of downstream agents that read the corrupted keys before reconciliation. In the observed case, three reads and one oversell. In a high-fanout swarm, a phantom reservation can starve a shared resource for every sibling branch that speculatively checks availability, causing a cascade of *correct* branches to wrongly predict "insufficient inventory" and diverge — a speculation-induced false consensus. The guardrail is structural, not behavioral: the tool gateway must tag every tool with `{idempotent, compensable, read_only}` and the branch scheduler must compute the reachable-tool closure at fork time and reject forks whose closure contains an untagged or non-compensable tool. Rollback must then be driven by the compensation log, not the trace, and must verify post-rollback that the external store's observable state matches the pre-branch snapshot for every key the branch touched. If it does not, the executor must escalate to a hard stop rather than merge — because at that point the canonical context is untrustworthy and any merge propagates the lie. ```python from dataclasses import dataclass, field from enum import Enum class RollbackDiscipline(Enum): SHADOW = "shadow" COMPENSATING = "compensating" NONE = "none" class ToolSafety(Enum): READ_ONLY = "read_only" IDEMPOTENT = "idempotent" COMPENSABLE = "compensable" UNROLLBACKABLE = "unrollbackable" class UnsafeSpeculationError(RuntimeError): """Raised when a branch is forked over a reachable tool set that the chosen rollback discipline cannot invert.""" pass class PostRollbackDivergenceError(RuntimeError): """Raised when, after replaying compensations, the external store does not match the pre-branch snapshot for a touched key.""" pass @dataclass class ToolSpec: name: str safety: ToolSafety @dataclass class Branch: branch_id: str reachable_tools: set[str] effects: list[tuple[str, dict]] = field(default_factory=list) def admit_branch(branch: Branch, registry: dict[str, ToolSpec], discipline: RollbackDiscipline) -> None: if discipline is RollbackDiscipline.SHADOW: # Shadow requires every effect be interceptable; we approximate by # requiring the tool to be known and not explicitly unrollbackable. for name in branch.reachable_tools: spec = registry.get(name) if spec is None or spec.safety is ToolSafety.UNROLLBACKABLE: raise UnsafeSpeculationError( f"branch {branch.branch_id}: tool {name!r} cannot be " f"shadowed under discipline {discipline.value}" ) return if discipline is RollbackDiscipline.COMPENSATING: for name in branch.reachable_tools: spec = registry.get(name) if spec is None: raise UnsafeSpeculationError( f"branch {branch.branch_id}: unknown tool {name!r}" ) if spec.safety not in (ToolSafety.READ_ONLY, ToolSafety.IDEMPOTENT, ToolSafety.COMPENSABLE): raise UnsafeSpeculationError( f"branch {branch.branch_id}: tool {name!r} has safety " f"{spec.safety.value}; not compensable, fork refused" ) return raise UnsafeSpeculationError( f"branch {branch.branch_id}: no rollback discipline permits " f"speculative fork over shared mutable state" ) def rollback(branch: Branch, snapshot: dict[str, object], current: dict[str, object], compensations: list[tuple[str, dict]]) -> None: # Replay compensations in reverse emission order. for tool_name, args in reversed(compensations): _invoke_compensation(tool_name, args) # Verify the store returned to the pre-branch snapshot on touched keys. touched = {k for _, args in branch.effects for k in args.get("keys", ())} for key in touched: if current.get(key) != snapshot.get(key): raise PostRollbackDivergenceError( f"branch {branch.branch_id}: key {key!r} expected " f"{snapshot.get(key)!r} after rollback, found " f"{current.get(key)!r}; canonical merge must halt" ) def _invoke_compensation(tool_name: str, args: dict) -> None: # Placeholder: real implementation dispatches to the registered inverse. return None ```