# Which invariants prevent speculative agent branches from leaking uncommitted side effects across a rollback barrier **Date of Record:** 2026 November 24 **Scope:** Applies to orchestrators that speculatively fork a plan into parallel agent branches (e.g., multiple tool-calling trajectories, competing drafters, or hedged retrieval paths) and commit exactly one branch while discarding the rest. Does not apply to read-only fan-out (map/reduce over pure queries) where branches have no externally observable effects. ## Core Distinction The distinction that matters is between *rollback of reasoning state* and *rollback of world state*. A speculative branch is cheap to discard at the token/context layer: you drop its message history, its scratchpad, its KV cache. But an agent branch is almost never pure reasoning — it calls tools. Those tool calls mutate the world: they write files, send emails, POST to webhooks, insert rows, enqueue jobs, decrement inventory, or open a long-lived MCP session that itself holds a lease. When the orchestrator "rolls back" the loser branches, it rolls back the *transcript*, not the *effects*. The invariant that speculative execution depends on — that a discarded branch leaves no trace — is silently violated the moment any branch tool has a side effect. The non-obvious part is that the violation is *asymmetric and deferred*. The loser branch's effects don't corrupt the winner's reasoning at fork time; they surface later, when the winner's committed plan reads state that a discarded sibling wrote. The orchestrator believes it committed one linear history; the environment reflects the union of all branches. This is the speculative-effect-leak, and it is the single most common way parallel agent orchestration produces "impossible" states that no individual agent's transcript can explain. ## What Was Observed A planner forked a three-way speculative search over a remediation task. Branch A would attempt an in-place config patch; Branch B would stage the patch to a temp path and validate; Branch C would query a dependency graph. All three were launched concurrently with a shared tool credential and a 90-second branch budget. Branch B's validator wrote a `*.staged` artifact and registered a cleanup hook. Branch A failed a schema check at t=41s and was discarded. Branch C timed out at t=90s and was discarded. Branch A was selected as the "winner" after a re-plan retry (the orchestrator's retry logic reused Branch A's session id). The committed transcript showed a clean single-path execution. But the environment contained Branch B's staged artifact, its cleanup hook was still armed, and the hook fired during the winner's commit step, deleting a file the winner had just written. The winner reported success; the post-commit verification agent reported a missing artifact. Neither the winner's nor the verifier's transcript contained a reference to Branch B — the causal agent was a discarded sibling whose effects survived rollback. The failure was reproducible only when (a) at least one branch held a stateful side effect, (b) the branch budget expired rather than the branch completing, and (c) the orchestrator reused a session id across the discard/retry boundary. Under those three conditions the leak rate was consistent; removing any one condition eliminated it. ## Condition of Validity Speculative rollback is only sound when all of the following hold. These are the invariants; the failure above is their conjunction's negation. 1. **Effect fencing.** Every branch runs under a distinct, revocable effect scope (a transaction, a scoped credential, a sandboxed mount, a namespaced queue). Discarding a branch must *revoke* the scope, not merely drop its transcript. A branch that shares a credential with siblings cannot be safely discarded. 2. **Commit-time effect reconciliation.** The orchestrator must reconcile the environment against the committed branch's declared effects before declaring success — i.e., assert that the set of observed mutations equals the set the winner intended. Without this, a sibling's leaked write is indistinguishable from the winner's own. 3. **Session-id non-reuse across discard.** A discarded branch's session handle must be retired, not recycled into a retry. Reuse aliases the retry onto the dead branch's armed hooks and pending async callbacks. 4. **Deferred-callback cancellation is synchronous with discard.** Cleanup hooks, timers, and async continuations registered by a branch must be cancelled *before* the discard returns, not eventually. An armed hook on a discarded branch is a delayed-action effect leak. 5. **Speculation depth is bounded by effect reversibility.** You may speculatively fork only across tools whose effects are reversible within the branch budget (idempotent writes, transactional stores, staged-then-promoted artifacts). Forking across irreversible effects (sends, charges, deletes) is not speculation; it is commitment multiplied by branch count. The condition of validity is that the orchestrator's notion of "discard" is defined over *effects*, not over *messages*. An orchestrator that cannot enumerate a branch's effects cannot safely discard it. ## Decision Boundary The boundary is between *hedged reads* and *speculative writes*. Hedge freely when branches are pure: fork three retrieval strategies, keep the best, discard the rest — the cost of a wrong discard is zero because nothing was written. The moment a branch crosses into mutation, the orchestrator must either (a) demote the branch to a two-phase protocol where the mutation is staged and only promoted on commit, or (b) refuse to fork it and run it serially. The decision rule: - If a branch's tool set is closed under read-only, fork it speculatively with no fencing. - If a branch's tool set includes any mutation, it must run under a revocable scope and its promotion must be gated on winner selection. - If a branch's tool set includes an irreversible effect, it may not be a speculative branch at all — it must be the committed branch, or it must not run. The subtle case is the *mixed* branch: an agent that reads to decide, then writes. The write is the commitment point. The orchestrator must treat the branch as speculative up to the write and committed after it, which means the write must be the promotion event, not an incidental step inside the branch. Branch B in the observation violated this: it staged a write and armed a cleanup hook inside a branch that the orchestrator still believed was speculative. ## Operational Effect Enforcing the invariants changes three things operationally. First, branch launch cost rises: each speculative branch needs its own effect scope, which means per-branch credentials, per-branch transaction handles, or per-branch sandbox namespaces. This is the price of safe speculation and it is non-negotiable; an orchestrator that shares a credential across branches has no rollback barrier at all, only a transcript barrier. Second, commit becomes a reconciliation step, not a flag flip: the orchestrator must diff observed effects against the winner's declared effects and fail the commit if they diverge. This catches leaked sibling effects at commit time rather than at post-hoc verification, converting a silent corruption into a loud, attributable failure. Third, discard must become synchronous with respect to deferred callbacks and session retirement, which forces the orchestrator to track async continuations per branch — a bookkeeping burden that most orchestration frameworks omit because their mental model of a branch is "a message list," not "a set of live handles." The net effect is that speculative parallelism becomes a *scoped* capability rather than a default. You fork reads freely and writes never; you fork mixed branches only behind a promotion gate. The throughput loss is real but bounded, and it is paid at design time rather than discovered at commit time as an unexplainable state divergence. ```python class SpeculativeEffectLeak(RuntimeError): """Raised when a discarded speculative branch leaves observable effects that survive rollback and are not attributable to the committed branch.""" pass class BranchScope: def __init__(self, branch_id: str, revocable: bool, irreversible: bool): self.branch_id = branch_id self.revocable = revocable self.irreversible = irreversible self.deferred_callbacks = [] self.declared_effects = set() self.observed_effects = set() self.retired = False def discard_branch(scope: BranchScope) -> None: if scope.irreversible and not scope.retired: # You may not silently discard a branch that has committed an # irreversible effect; that effect is already in the world. raise SpeculativeEffectLeak( f"branch {scope.branch_id} holds irreversible effects; " f"cannot roll back, must reconcile explicitly" ) if not scope.revocable: raise SpeculativeEffectLeak( f"branch {scope.branch_id} shares an effect scope with siblings; " f"discard would leak its writes" ) # Cancel deferred callbacks synchronously, then retire the session id # so a retry cannot alias onto armed hooks. for cb in scope.deferred_callbacks: cb.cancel() scope.deferred_callbacks.clear() scope.retired = True def commit_winner(winner: BranchScope, environment_effects: set) -> None: if winner.retired: raise SpeculativeEffectLeak( f"winner {winner.branch_id} was retired; session-id reuse detected" ) leaked = environment_effects - winner.declared_effects if leaked: # Observed mutations not declared by the winner are sibling leaks. raise SpeculativeEffectLeak( f"commit of {winner.branch_id} found undeclared effects {leaked}; " f"a discarded sibling leaked across the rollback barrier" ) winner.retired = True ```