# Which invariants prevent speculative branch rollback from resurrecting a cancelled tool call's side effects **Date of Record:** 2026 November 26 **Scope:** Applies to multi-agent orchestrators that fork speculative execution branches, predict a likely continuation, and roll back losing branches after the winner is committed. Does not apply to single-agent linear execution, nor to systems where tool calls are guaranteed side-effect-free and idempotent. ## Core Distinction The distinction that matters is between **logical rollback** and **physical cancellation**. A speculative orchestrator forks a branch, issues a predicted tool call (e.g., `transfer_funds`, `send_email`, `deploy_canary`), then loses the race and rolls back the branch's *state*. But the tool call already left the process boundary. Rollback of an agent's in-memory episodic buffer, its scratchpad, and its message log does **not** retract the outbound RPC. The invariant that must hold is: *a branch cannot be considered rolled back until every tool invocation it emitted has reached a terminal disposition — either confirmed-completed-and-compensated, or confirmed-never-started.* Cancellation is a request, not a fact. The gap between "we asked the tool to abort" and "the tool provably did not act" is where speculative agents corrupt the real world. The non-obvious part: the orchestrator often *does* send a cancellation to the tool bus and *does* receive a `200 OK` from the cancellation endpoint. That acknowledgment is routinely misread as proof of non-execution. It is not. It only means the cancellation request was received, possibly after the side effect already committed downstream. ## What Was Observed A planner agent spawned three speculative branches at a decision fork (`refund-via-card`, `refund-via-credit`, `refund-via-manual`). Each branch immediately called `payments.refund()` with a distinct idempotency key derived from `(task_id, branch_id)`. The `refund-via-credit` branch was predicted as most likely and pre-warmed; the other two were issued optimistically to hide latency. The credit branch's tool call timed out at the orchestrator's 800 ms speculative budget, so the orchestrator marked it "loser," fired `cancel(branch_id)` to the tool bus, received `202 Accepted`, and rolled back all three branches' state to the fork point. It then re-ran the decision with fresh evidence and selected `refund-via-manual`. The trace that surfaced the bug, reconstructed from the payments ledger: 1. `t=0ms` — branch `credit` emits `refund(idem=task7:credit, amt=40.00)`. 2. `t=790ms` — orchestrator speculative deadline fires; branch marked loser. 3. `t=800ms` — orchestrator sends `cancel(task7:credit)`; tool bus replies `202`. 4. `t=812ms` — orchestrator rolls back branch state, drops the branch's pending-call record. 5. `t=1,340ms` — payments service, which had been retrying an internal gateway call, commits `refund(idem=task7:credit)` successfully. 6. `t=2,100ms` — `refund-via-manual` branch commits `refund(idem=task7:manual, amt=40.00)`. Result: the customer was refunded twice. The orchestrator's rollback invariant held *logically* — no branch record survived — but the physical world had two committed side effects. Worse, because the branch record was dropped at step 4, the later reconciliation pass had no key to search for, so the duplicate was invisible to the agent's own audit. The failure is not a race in the classic sense of two writers. It is a **disposition gap**: between the moment cancellation is *requested* and the moment execution is *provably impossible*, the branch must remain in a `DRAINING` state, not `ROLLED_BACK`. The orchestrator collapsed those two states into one. ## Condition of Validity The rollback invariant "a branch is rolled back iff its state is discarded" is only valid under the precondition that **every emitted tool call is either (a) idempotent under the branch's idempotency key and safely retryable, or (b) fully drained to a terminal disposition before state discard.** Speculative execution violates (a) whenever a tool has non-idempotent or non-compensable effects, and violates (b) whenever the orchestrator treats a cancellation acknowledgment as a completion signal. Concretely, the invariant fails when all of the following hold: - The tool call is emitted before the branch's fate is decided (speculation). - The tool's execution can outlive the orchestrator's speculative deadline (slow downstream, internal retries, queueing). - The cancellation path is asynchronous and its acknowledgment is weaker than a commit barrier. - The branch record — including its idempotency keys — is discarded at rollback, destroying the only handle for later reconciliation. Remove any one and the failure is bounded. Speculation without slow downstream tools is safe. Slow tools with synchronous cancellation barriers are safe. Discarded branches with retained idempotency-key ledgers are recoverable. The dangerous quadrant is *speculation × slow tool × async cancel × record discard*. ## Decision Boundary The boundary the orchestrator must enforce is between `LOSER_CANCELLING` and `LOSER_ROLLED_BACK`. A branch may transition to `ROLLED_BACK` (and have its state and pending-call records discarded) **only** when, for every emitted tool call, one of these holds: - The tool returned a terminal `COMMITTED` and a compensating action has been confirmed, or - The tool returned a terminal `REJECTED`/`NOT_STARTED` with a monotonic fence token proving the call cannot later commit, or - A drain barrier has elapsed *and* the tool's lease/epoch has been observed to advance past the branch's epoch. A bare `202 Accepted` from a cancel endpoint satisfies none of these. The correct handling is to move the branch to `DRAINING`, retain its idempotency-key ledger in a durable tombstone set, and only reclaim the branch's memory after drain confirmation. If drain confirmation never arrives within a bounded window, the branch must be escalated to `ORPHANED` — visible to reconciliation, never silently forgotten. The winner's commit must also gate on the tombstone set: before the winning branch commits a semantically-equivalent effect, it checks whether any drained loser holds a live key for the same effect class. ## Operational Effect With the `DRAINING` state and tombstone retention in place, the double-refund becomes a detected-and-suppressed event: at step 6, the manual branch's pre-commit check finds the credit tombstone still live (drain unconfirmed), blocks, and forces the orchestrator to reconcile the two keys before committing. The cost is latency on the winner's commit path and a durable ledger of dead branches — memory that must be reclaimed by a separate, provably-safe sweeper rather than by the rollback path itself. The benefit is that speculative execution stops being a mechanism for emitting unrecoverable side effects into the world under the fiction that they were rolled back. The governing principle: **rollback is a claim about the future, not a description of the past; it is only true once every emitted effect is provably terminal.** ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Dict, Set class RollbackInvariantViolation(RuntimeError): """Raised when a branch is rolled back while an emitted tool call is not provably terminal.""" class BranchState(Enum): SPECULATING = "speculating" LOSER_CANCELLING = "loser_cancelling" DRAINING = "draining" ROLLED_BACK = "rolled_back" ORPHANED = "orphaned" class CallDisposition(Enum): PENDING = "pending" CANCELLATION_ACKED = "cancellation_acked" # NOT terminal COMMITTED = "committed" COMPENSATED = "compensated" NOT_STARTED = "not_started" # terminal, fenced FENCE_EXPIRED = "fence_expired" # terminal, provable TERMINAL = {CallDisposition.COMPENSATED, CallDisposition.NOT_STARTED, CallDisposition.FENCE_EXPIRED} @dataclass class ToolCall: idem_key: str disposition: CallDisposition = CallDisposition.PENDING epoch: int = 0 @dataclass class Branch: branch_id: str state: BranchState = BranchState.SPECULATING calls: Dict[str, ToolCall] = field(default_factory=dict) class SpeculativeOrchestrator: def __init__(self) -> None: # Tombstones survive branch rollback; they are the only handle for reconciliation. self.tombstones: Set[str] = set() def emit(self, branch: Branch, idem_key: str, epoch: int) -> None: branch.calls[idem_key] = ToolCall(idem_key=idem_key, epoch=epoch) self.tombstones.add(idem_key) def request_cancel(self, branch: Branch) -> None: if branch.state is not BranchState.SPECULATING: raise RollbackInvariantViolation(f"cannot cancel branch {branch.branch_id} in {branch.state}") branch.state = BranchState.LOSER_CANCELLING for call in branch.calls.values(): if call.disposition is CallDisposition.PENDING: # Async cancel acknowledged; still NOT terminal. call.disposition = CallDisposition.CANCELLATION_ACKED branch.state = BranchState.DRAINING def try_rollback(self, branch: Branch) -> None: if branch.state is not BranchState.DRAINING: raise RollbackInvariantViolation( f"branch {branch.branch_id} not draining; state={branch.state}" ) nonterminal = [ c.idem_key for c in branch.calls.values() if c.disposition not in TERMINAL ] if nonterminal: # This is the exact bug: acknowledging cancel is not proof of non-execution. raise RollbackInvariantViolation( f"branch {branch.branch_id} has non-terminal calls {nonterminal}; " f"rollback would discard reconciliation handles" ) branch.state = BranchState.ROLLED_BACK # Tombstones are retained deliberately; only a fenced sweeper may clear them. def winner_commit_guard(self, winner_idem_key: str, effect_class: str) -> None: # Any live tombstone in the same effect class blocks the winning commit. live = [k for k in self.tombstones if k.startswith(effect_class)] if live and winner_idem_key not in live: raise RollbackInvariantViolation( f"winner {winner_idem_key} blocked by live loser tombstones {live}" ) def demo() -> None: orch = SpeculativeOrchestrator() loser = Branch(branch_id="credit") orch.emit(loser, "task7:credit", epoch=3) orch.request_cancel(loser) # Cancellation was merely ACKed; rollback must refuse. orch.try_rollback(loser) # raises if __name__ == "__main__": demo() ```