# In what scenarios must an instance abandon speculative plan branches before their side effects become unrollbackable **Date of Record:** 2026 November 29 **Scope:** Applies to orchestrators that fork an agent's plan into multiple concurrently executed branches (speculative tool calls, speculative sub-agent spawns) and rely on compensating transactions to roll back losing branches. Does not apply to read-only speculative execution, nor to branches whose effects are confined to an isolated sandbox snapshot that can be deterministically discarded. ## Core Distinction The distinction that matters is between *rollback by compensation* and *rollback by discard*. A speculative branch whose effects live entirely inside a sandboxed filesystem, a scratch database, or an in-memory buffer can be discarded: the orchestrator drops the handle and the world is bit-identical to the pre-fork state. A branch that has emitted an irreversible or externally observable effect—an outbound email, a payment authorization, a `git push` to a shared remote, an MCP tool call to a third-party API with a non-idempotent verb, a message posted to a peer agent's inbox—can only be rolled back by *compensation*, which is a new forward action with its own failure modes, latency, and non-atomicity. The failure this record examines: an orchestrator forks N speculative branches, the winner is selected, and the orchestrator issues `rollback()` on the losers. The rollback call returns success. The orchestrator marks the branch `ROLLED_BACK` and proceeds. But the rollback is *compensatory*, and the compensation either (a) has not yet been observed by the external system at the moment the orchestrator declares the branch dead, or (b) is itself racing with a downstream consumer who already read the speculative effect. The orchestrator's internal state machine says the branch is gone; the external world says it happened. This is a **rollback visibility gap**: the window between "compensation dispatched" and "compensation durably observed by every party that could act on the original effect." The invariant that bounds this: *a speculative branch may only be marked terminal once every externally observable effect it produced has a compensation whose completion is confirmed by the effect's own system of record, not by the orchestrator's dispatch acknowledgment.* Absent that confirmation, the branch is `PENDING_COMPENSATION`, not `ROLLED_BACK`, and the orchestrator must not treat its state as clean. ## What Was Observed A planning agent was asked to reconcile a customer's duplicate subscription records. It forked three speculative branches: - **Branch A** (conservative): issue refund via payments API, then cancel the duplicate. - **Branch B** (aggressive): cancel first, refund after, batching both into a single tool-call sequence. - **Branch C** (audit-first): write an audit record, then propose a diff for human review. Branch A and Branch B both began executing concurrently. Branch A's refund tool call succeeded and returned `refund_id=r_8812`. Branch B's cancel tool call succeeded and returned `cancel_id=c_4401`. The planner's arbitration heuristic scored Branch B higher (fewer round trips) and selected it as the winner at t=1.2s. The orchestrator dispatched compensation for Branch A: a `reverse_refund(r_8812)` call. The payments API accepted `reverse_refund` and returned `202 Accepted`—an *asynchronous* acknowledgment. The reversal was queued behind a settlement batch. At t=1.4s the orchestrator marked Branch A `ROLLED_BACK` and released its branch lock. At t=1.9s Branch B's cancel completed. At t=2.1s the settlement batch processed the reversal, but the reversal now hit an account whose subscription had *already been cancelled by Branch B*—the reversal logic rejected the reversal as `REFUND_TARGET_INACTIVE` and left the refund in place, silently, in a dead-letter queue. Net result: customer received a refund *and* had their subscription cancelled. The orchestrator's trace showed Branch A cleanly rolled back. The reconciliation report showed a net-negative balance. The discrepancy was discovered 40 minutes later by a downstream ledger audit, not by the agent. Two properties made this non-obvious. First, the compensation's `202` was treated as completion. Second, the compensation's *semantic* precondition (target active) was invalidated by the winning branch's own effects—the branches were not independent, because they operated on the same entity. Speculative parallelism had assumed commutativity that did not hold. ## Condition of Validity The "discard is safe" assumption holds only under three jointly necessary conditions. The orchestrator must check all three before forking speculatively; if any fails, the branch must be serialized or gated behind a confirmation barrier. 1. **Effect containment.** Every tool the branch may call is either read-only or writes only to a namespace the orchestrator owns (sandbox path, scratch schema, branch-scoped credential). The moment a branch obtains a credential that can address a shared resource, containment is lost. This is checkable statically from the tool manifest only if the manifest declares effect scope; most MCP servers do not, so the orchestrator must maintain an allowlist of `SPECULATION_SAFE` tools and refuse to fork branches that reach outside it. 2. **Compensation observability.** For any effect that escapes containment, there exists a compensation whose *completion* is synchronously confirmable—the compensation call returns a terminal state, not a `202`. If the only available compensation is asynchronous, the branch cannot be marked terminal on dispatch; it must hold `PENDING_COMPENSATION` until a poll or webhook confirms the reversal landed in the system of record. 3. **Cross-branch non-interference.** The speculative branches must not mutate overlapping entities in ways that invalidate each other's preconditions. Branch A's reversal assumed the subscription was active; Branch B's cancel removed that precondition. This is the hardest condition, because it requires the planner to reason about the *postconditions* of sibling branches before forking. A practical guardrail: the orchestrator computes a write-set per branch from the tool-call plan and refuses to fork two branches whose write-sets intersect on any entity identifier. When intersection is unavoidable, the branches are serialized with the later branch's plan re-derived against the earlier branch's committed state. The failure above violated all three: effects escaped containment (payments API), compensation was asynchronous (`202`), and write-sets intersected (same subscription). ## Decision Boundary The boundary the orchestrator must enforce is between *speculation as exploration* and *speculation as commitment*. Exploration is safe to discard; commitment is not. Concretely, at the moment a branch is about to emit its first effect that escapes containment, the orchestrator must make a binary decision: - If the branch's plan is still provisional (winner not yet selected), the effect must be *staged*—written to a branch-local staging area and only flushed to the real system after the branch wins. This converts commitment into a post-selection action and eliminates the rollback problem entirely. Cost: the winning branch pays a flush latency penalty. This is the correct default. - If staging is impossible (the tool offers no staging mode, e.g., a third-party API that acts immediately), the branch must be *promoted to commitment*: it can no longer be rolled back by discard, only by compensation, and the orchestrator must treat the branch as a first-class committed action with a compensation obligation. Speculation is over for that branch; it must not be silently killed when a sibling wins. The forbidden middle ground—which produced the incident—is to let a branch commit to the real world *and* treat it as discardable. That is the exact configuration in which `rollback()` returns success while the effect persists. The decision must also account for the arbitration timing. If the winner is selected *after* a branch has committed, the orchestrator cannot "un-select" the committed branch; it must either confirm the winner's plan is compatible with the committed branch's effects (re-derive the winner against the new committed state) or abort the entire fork and surface the conflict. The planner's arbitration heuristic—here, "fewer round trips"—is not a valid basis for choosing between branches with intersecting write-sets, because the heuristic does not model compensation cost. ## Operational Effect The operational consequence is that speculative parallelism over effectful tools is only sound when the orchestrator can *prove* non-interference and *confirm* compensation, and in practice it can rarely do either. The practical posture that follows: - Default to **staged speculation**: fork freely over read-only and sandboxed tools; for effectful tools, stage writes branch-locally and flush only the winner. This makes rollback a discard and removes the compensation problem. - When staging is impossible, **serialize** branches that touch shared entities. The parallelism gain is real but bounded; the rollback gap is unbounded. - Treat any compensation returning a non-terminal status as `PENDING_COMPENSATION`, and do not release the branch lock or mark the fork complete until every such compensation is confirmed terminal. A fork with outstanding `PENDING_COMPENSATION` is a fork that can still fail after the agent has moved on—the worst kind of failure, because no one is watching. - Re-derive the winning plan against the committed state of any branch that could not be rolled back, rather than assuming the pre-fork state. The deeper lesson: an agent's plan branches are not independent processes with isolated memory, like OS threads. They share the *world*, and the world is the memory that cannot be checkpointed. Rollback of a speculative branch is a distributed-systems problem disguised as a control-flow construct, and it fails exactly where distributed rollback always fails—when the compensation is asynchronous and the effects are entangled. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class BranchState(Enum): PROVISIONAL = "provisional" COMMITTED = "committed" ROLLED_BACK = "rolled_back" PENDING_COMPENSATION = "pending_compensation" ORPHANED = "orphaned" class SpeculationRollbackError(RuntimeError): """Raised when an orchestrator attempts to terminate a speculative branch whose effects are not provably rolled back.""" @dataclass class Effect: entity_id: str tool: str terminal: bool # compensation confirmed terminal by system of record escaped_containment: bool @dataclass class Branch: branch_id: str state: BranchState = BranchState.PROVISIONAL effects: list = field(default_factory=list) write_set: set = field(default_factory=set) def mark_rolled_back(branch: Branch) -> None: """Transition a branch to ROLLED_BACK only if every escaped effect has a confirmed-terminal compensation. Otherwise the branch is PENDING_COMPENSATION and must not be treated as clean.""" escaped = [e for e in branch.effects if e.escaped_containment] unconfirmed = [e for e in escaped if not e.terminal] if unconfirmed: branch.state = BranchState.PENDING_COMPENSATION raise SpeculationRollbackError( f"branch {branch.branch_id} has {len(unconfirmed)} escaped effect(s) " f"without confirmed compensation: " f"{[(e.tool, e.entity_id) for e in unconfirmed]}. " f"Branch is PENDING_COMPENSATION, not ROLLED_BACK; do not release lock." ) branch.state = BranchState.ROLLED_BACK def fork_speculative(branches: list) -> None: """Refuse to fork branches whose write-sets intersect on any entity id.""" seen: dict = {} for b in branches: for entity in b.write_set: if entity in seen: raise SpeculationRollbackError( f"cannot fork speculatively: branches {seen[entity]} and " f"{b.branch_id} both write entity {entity!r}; serialize or stage." ) seen[entity] = b.branch_id def arbitrate_and_rollback(branches: list, winner_id: str) -> None: """Select a winner and roll back losers. Losers that committed to the real world cannot be discarded; they must be compensated or the fork aborted.""" for b in branches: if b.branch_id == winner_id: b.state = BranchState.COMMITTED continue if any(e.escaped_containment for e in b.effects): # Losing branch already acted on the shared world. mark_rolled_back(b) # raises if compensation unconfirmed else: b.state = BranchState.ROLLED_BACK # discard is safe # --- Reproduce the incident --- a = Branch("A", effects=[Effect("sub_77", "refund", terminal=False, escaped_containment=True)], write_set={"sub_77"}) b = Branch("B", effects=[Effect("sub_77", "cancel", terminal=True, escaped_containment=True)], write_set={"sub_77"}) fork_speculative([a, b]) # raises: intersecting write-set, must serialize arbitrate_and_rollback([a, b], winner_id="B") # would raise on A: PENDING_COMPENSATION ```