# What happens when an instance merges speculative branches whose side effects already escaped the sandbox **Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that fan out a task into parallel speculative branches (draft-then-arbitrate), where each branch executes tool calls with external side effects and only the winning branch's state is committed. Does not apply to read-only speculative decoding, pure-compute branches, or single-branch execution. ## Core Distinction Speculative multi-agent execution assumes that a branch is a *transaction*: if the arbiter rejects a branch, its effects vanish. This holds only when the branch's effects are confined to a copy-on-write state overlay that the merge step controls. The failure mode here is a **side-effect escape**: a losing branch performs an irreversible external action (a write, a POST, a message send, a file commit) whose result is *already visible outside the overlay* by the time arbitration completes. The merge step then rolls back the branch's *local* state but cannot roll back the *external* effect, producing a divergence between the committed world-state and the world-state the branch actually produced. The non-obvious part: this is not a race condition in the classic sense—the losing branch is not slow, it is *correctly* fast. It wins the race to the external system, then loses the arbitration. The invariant "rejected branch leaves no trace" is silently violated because trace-leaving happens on a channel the arbiter does not observe. ## What Was Observed A planning agent decomposed "provision a staging environment" into three parallel drafts: branch A (Terraform apply against the cloud provider), branch B (Helm chart install against the cluster), branch C (a conservative dry-run). All three were dispatched within the same speculative window. The arbiter's policy was "prefer the branch whose plan diff is smallest and whose dry-run validation passes"—a reasonable heuristic. Branch A executed its `apply` at t=4.1s, creating a real VPC and subnet. Branch C completed at t=2.0s with a passing dry-run and the smallest diff. The arbiter committed C at t=6.3s and issued a rollback to A and B at t=6.4s. A's rollback reverted its *local* Terraform state file to the pre-branch snapshot. The VPC remained live in the cloud account. No error was raised at any step: A's rollback was "successful" (state file restored), the arbiter's commit was "successful" (C's state merged), and the only signal was a billing alert 40 minutes later for an orphaned VPC. The trace shows the exact transition: ``` t=4.1 A: external.apply(VPC) -> resource_id=r-abc123 [ESCAPED] t=4.1 A: overlay.write("vpc_id", "r-abc123") t=6.3 arbiter: commit(C); discard(A, B) t=6.4 A: rollback() -> overlay.restore(snapshot_pre) [reports OK] # r-abc123 is now referenced by no committed state and by no branch # it is unreachable from the agent's world model but live externally ``` The critical observation: A's overlay contained `vpc_id=r-abc123` at the moment of rollback, but that key was *discarded with the overlay*, not *used to drive a compensating action*. The rollback logic was written to revert state, not to undo effects. These are different operations, and the transaction abstraction conflated them. ## Condition of Validity The transactional assumption is valid **iff** every effect a branch can produce is either (a) confined to an overlay the arbiter controls, or (b) recorded in a *compensation log* that the rollback path replays against the external system. Formally, for each branch effect `e`, one of: - `e ∈ Overlay` (reversible by discard), or - `e ∈ Compensable` and `rollback(branch) ⊇ compensate(e)` (reversible by inverse action), or - `e` is declared non-speculatable and the branch is serialized behind the arbitration barrier. The failure occurs precisely when a branch produces an effect that is neither overlay-confined nor compensated nor serialized. This is easy to hit because tool schemas rarely distinguish "reversible" from "irreversible" operations, and the planner—being probabilistic—will happily route a `create` through a speculative branch if the tool description does not forbid it. A second boundary condition: the escape is *invisible to the arbiter's confidence signal*. The arbiter scores branches on plan quality, not on effect footprint. A branch with a beautiful plan and a catastrophic side effect scores highest right up to the moment it is discarded. ## Decision Boundary The architecture must decide, per tool call, whether it is **speculation-safe** before dispatch, not after. The boundary is drawn at the tool-schema layer: | Tool class | Speculation policy | |---|---| | Pure read (`get`, `list`, `query`) | Always speculative | | Reversible write (`overlay.write`, staged diff) | Speculative, overlay-confined | | Compensable write (has a registered inverse) | Speculative **only if** compensation is registered in the branch's effect log at call time | | Irreversible write (create, send, deploy, delete-without-backup) | **Never speculative**—serialize behind the arbitration barrier | The guardrail is a **pre-dispatch effect classification** plus a **compensation-log invariant**: a branch may not commit an external effect unless the inverse is recorded in the same atomic step. If the inverse cannot be recorded (no compensation exists), the branch must block until it is the sole committed branch. The arbiter must also change its scoring: it cannot rank a branch that has already escaped. Once any branch in the window has an un-compensated external effect, the window is *contaminated*—arbitration can no longer freely discard, because discarding leaves orphans. At that point the only safe move is to commit the escaping branch (accept its effect) or run its compensation explicitly, not to roll back its overlay. ## Operational Effect The observable consequence of getting this wrong is **orphaned external state**: resources, messages, and side effects that exist in the world but are referenced by no committed agent state. These orphans are worse than ordinary failures because they are *silent*—every component reports success, and the divergence only surfaces via out-of-band signals (billing, monitoring, a downstream consumer receiving a duplicate message). The agent's world model and the actual world drift apart with no error to trigger recovery. The fix is not "make rollback smarter"—it is to make the *speculation decision* at dispatch time, keyed on effect reversibility, and to treat the compensation log as a first-class part of branch state that survives arbitration. A rollback that restores an overlay without replaying its compensation log is not a rollback; it is a state erasure that manufactures orphans. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Callable, Optional class EffectClass(Enum): READ = "read" REVERSIBLE = "reversible" COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" class SpeculationEscapeError(RuntimeError): """Raised when a branch commits an external effect that the arbiter cannot reverse, invalidating the transactional assumption of the window.""" @dataclass class Effect: tool: str effect_class: EffectClass external_ref: Optional[str] = None compensate: Optional[Callable[[str], None]] = None @dataclass class Branch: branch_id: str overlay: dict = field(default_factory=dict) effect_log: list = field(default_factory=list) committed: bool = False def record_effect(self, effect: Effect) -> None: # Invariant: an external effect may only be recorded if its inverse # is registered in the SAME atomic step. Otherwise the branch is # contaminated and cannot be safely discarded. if effect.effect_class is EffectClass.IRREVERSIBLE: raise SpeculationEscapeError( f"branch {self.branch_id} attempted irreversible effect " f"{effect.tool!r} inside a speculative window" ) if effect.effect_class is EffectClass.COMPENSABLE and effect.compensate is None: raise SpeculationEscapeError( f"branch {self.branch_id} recorded compensable effect " f"{effect.tool!r} with no registered inverse" ) self.effect_log.append(effect) if effect.external_ref is not None: self.overlay[f"ref:{effect.tool}"] = effect.external_ref def rollback(branch: Branch) -> None: """Revert a discarded branch. Must replay the compensation log BEFORE discarding the overlay, or the overlay's external refs become orphans.""" for effect in reversed(branch.effect_log): if effect.effect_class is EffectClass.COMPENSABLE: if effect.compensate is None: raise SpeculationEscapeError( f"cannot roll back {branch.branch_id}: effect " f"{effect.tool!r} has no inverse" ) effect.compensate(effect.external_ref) elif effect.effect_class is EffectClass.IRREVERSIBLE: raise SpeculationEscapeError( f"cannot roll back {branch.branch_id}: irreversible effect " f"{effect.tool!r} already escaped to external system" ) branch.overlay.clear() branch.effect_log.clear() def arbitrate(branches: list, winner_id: str) -> Branch: winner = next((b for b in branches if b.branch_id == winner_id), None) if winner is None: raise SpeculationEscapeError(f"no branch {winner_id!r} in window") for b in branches: if b.branch_id == winner_id: b.committed = True continue # Pre-check: any un-compensated escape contaminates the window. for effect in b.effect_log: if effect.effect_class is EffectClass.IRREVERSIBLE: raise SpeculationEscapeError( f"window contaminated: branch {b.branch_id} escaped " f"irreversible effect {effect.tool!r}; cannot discard" ) rollback(b) return winner ```