# Which invariants prevent speculative branch reconciliation from committing a tool call whose side effects escaped the rollback boundary **Date of Record:** 2026 November 24 **Scope:** Applies to multi-agent orchestrators that run speculative branches (parallel candidate plans) with per-branch rollback and merge-on-consensus, where branches may invoke external tools. Does not apply to read-only speculative execution or to single-branch retry loops without reconciliation. ## Core Distinction The failure is not "a speculative branch failed and was rolled back." That is the intended path. The failure is that a branch was rolled back logically—its state discarded, its context dropped, its consensus vote voided—while one of its tool calls had already crossed the side-effect boundary (sent an email, wrote a row, opened a PR, debited an account). The orchestrator treats rollback as a state operation on its own memory graph, but a tool call is a *commitment to the external world* that the memory graph does not own. Reconciliation then merges the surviving branches and commits the consensus plan, unaware that a discarded branch has already mutated the environment the surviving plan now assumes is pristine. The sharp invariant: **rollback of a branch must be defined over the union of (agent state ∪ external side effects), not over agent state alone.** If a tool call is not classified as reversible before it executes, the branch that issues it is no longer speculatively rollback-able—it is a committed branch wearing a speculative label. ## What Was Observed A three-branch planner ran candidates A, B, C for a "reconcile customer refund" task. Branch B invoked `issue_refund(amount=4200, idempotency_key=None)` against the payment tool, then lost the consensus vote to A because B's later reasoning diverged on a currency-rounding step. The orchestrator rolled B back: dropped its memory, invalidated its vote, freed its context slot. A's plan then executed `issue_refund(amount=4200, ...)` as the "first" refund. The customer was refunded twice. The trace shows the exact mechanism. Branch B's tool call returned `{"status": "ok", "txn": "r_8891"}`. The orchestrator recorded that return value in B's branch state. When B was rolled back, the return value was discarded along with the branch—so the *evidence* that the side effect occurred was destroyed at the same moment the *side effect itself* persisted. The reconciler had no record to reconcile against. Three contributing conditions, each individually benign: 1. **Tool calls were classified by branch, not by reversibility.** Every branch was assumed rollback-able because "it's speculative." No per-call reversibility metadata existed. 2. **Rollback discarded the tool-call ledger.** B's branch state held the `txn: r_8891` receipt; rollback deleted branch state wholesale, so the receipt vanished but the transaction did not. 3. **Reconciliation trusted the surviving plan's preconditions.** A's plan asserted "no prior refund exists" based on a snapshot taken before B ran. The snapshot was valid at branch-fork time and stale at merge time—a classic speculative-read anomaly, but here the write came from a sibling branch rather than an external actor. The compounding step: because B's receipt was gone, the reconciler's idempotency check on A's refund had nothing to collide with, so it passed. The duplicate committed silently. ## Condition of Validity The "speculative branch is freely rollback-able" assumption holds only under a conjunction that is rarely checked: - Every tool call in the branch is either **reversible** (compensable: can be undone by an inverse operation) or **idempotent under a stable key** (re-execution with the same key is a no-op). - The **side-effect ledger is append-only and branch-independent**—it survives rollback of the branch that produced it. Rollback may void the branch's *vote*, never its *receipts*. - Reconciliation re-reads external state at merge time, or holds a **write-set conflict check** across all branches (surviving and discarded), not just surviving ones. Violate any one and the invariant fails. In the observed incident all three were violated simultaneously, which is why the duplicate was silent rather than caught by a secondary check. The subtle part: condition 2 is counterintuitive. Engineers naturally couple "discard the branch" with "discard everything the branch touched," because branch state is a single object. But the tool receipt is *testimony about the world*, not *state of the agent*. Testimony must outlive the witness. ## Decision Boundary The boundary is drawn at the moment a tool call is dispatched, not at the moment the branch is rolled back. Before dispatch, the orchestrator must answer: *is this call reversible or idempotency-keyed?* - If **yes (reversible)**: the branch remains fully speculative. Rollback may discard receipts; the inverse operation cleans the world. - If **yes (idempotency-keyed)**: the branch remains speculative *provided the key is stable across branches*—i.e., two branches computing the same intended effect derive the same key. If keys are branch-local (UUID per branch), idempotency is defeated and the call is effectively irreversible. - If **no**: the branch must be **promoted to committed** at dispatch. It can no longer be rolled back; it can only be *compensated*, and compensation is a new committed action that itself needs consensus. The orchestrator must either serialize such calls (only the consensus branch may dispatch them) or fence them behind a two-phase reserve/commit. The practical rule: **speculative branches may freely dispatch reversible or stably-keyed calls; they may not dispatch irreversible calls until consensus.** An irreversible call inside a speculative branch is a category error, not a performance optimization. ## Operational Effect Enforcing the invariant changes the orchestrator's shape in three concrete ways. First, the tool layer must expose a `reversibility` descriptor (`reversible | idempotent(key_fn) | irreversible`) and the branch scheduler must refuse to speculatively dispatch `irreversible` calls—raising at dispatch, not at rollback, so the failure is loud and early. Second, the side-effect ledger becomes an append-only log indexed by idempotency key, decoupled from branch lifecycle; rollback tombstones the branch's vote but retains its receipts. Third, reconciliation runs a write-set intersection across *all* branches (including discarded) against the surviving plan's read-set, converting the silent duplicate into a detected conflict that forces re-planning. The cost is real: irreversible calls lose speculative parallelism and serialize behind consensus, which can double latency on refund/payment/notification-heavy tasks. That cost is the price of the invariant, and it is cheaper than a duplicate refund. The failure mode being prevented—a rolled-back branch whose ghost persists in the external world—is not recoverable by any amount of post-hoc reconciliation, because the evidence was destroyed by the very act of rollback. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable, Optional class SpeculativeCommitViolation(RuntimeError): """Raised when a speculative branch attempts an action that cannot be rolled back, or when reconciliation would commit over an escaped effect.""" pass class Reversibility(Enum): REVERSIBLE = "reversible" IDEMPOTENT = "idempotent" IRREVERSIBLE = "irreversible" @dataclass(frozen=True) class ToolSpec: name: str reversibility: Reversibility key_fn: Optional[Callable[[dict], str]] = None @dataclass class Receipt: branch_id: str tool: str idem_key: Optional[str] txn: str @dataclass class SideEffectLedger: # Append-only; survives branch rollback. This is the testimony log. receipts: list[Receipt] = field(default_factory=list) def record(self, r: Receipt) -> None: self.receipts.append(r) def keys_for(self, tool: str) -> set[str]: return {r.idem_key for r in self.receipts if r.tool == tool and r.idem_key is not None} @dataclass class Branch: branch_id: str speculative: bool = True def dispatch_tool(branch: Branch, spec: ToolSpec, args: dict, ledger: SideEffectLedger, txn: str) -> Receipt: """Dispatch a tool call from a branch, enforcing the rollback invariant. Invariant: a speculative branch may only dispatch calls that are reversible or idempotent under a *stable* key. Irreversible calls must be committed (branch promoted) before dispatch. """ if branch.speculative and spec.reversibility is Reversibility.IRREVERSIBLE: raise SpeculativeCommitViolation( f"branch {branch.branch_id} is speculative but tool " f"{spec.name!r} is irreversible; promote branch to committed " f"before dispatch or serialize behind consensus" ) idem_key = None if spec.reversibility is Reversibility.IDEMPOTENT: if spec.key_fn is None: raise SpeculativeCommitViolation( f"tool {spec.name!r} is idempotent but has no key_fn; " f"branch-local keys defeat idempotency across branches" ) idem_key = spec.key_fn(args) if idem_key in ledger.keys_for(spec.name): # Collision with a sibling branch's receipt: dedupe, do not re-execute. existing = next(r for r in ledger.receipts if r.tool == spec.name and r.idem_key == idem_key) return existing receipt = Receipt(branch_id=branch.branch_id, tool=spec.name, idem_key=idem_key, txn=txn) ledger.record(receipt) return receipt def reconcile(surviving: Branch, ledger: SideEffectLedger, planned_effects: list[tuple[str, Optional[str]]]) -> None: """Commit the surviving plan only if no escaped effect collides with it.""" for tool, key in planned_effects: if key is not None and key in ledger.keys_for(tool): raise SpeculativeCommitViolation( f"reconciliation blocked: planned {tool!r} with key {key!r} " f"already exists in ledger from a prior (possibly rolled-back) " f"branch; duplicate side effect would commit silently" ) surviving.speculative = False # --- demonstration of the observed incident --- if __name__ == "__main__": ledger = SideEffectLedger() refund = ToolSpec("issue_refund", Reversibility.IRREVERSIBLE) b = Branch("B") try: # Correct behavior: refuse speculative dispatch of an irreversible call. dispatch_tool(b, refund, {"amount": 4200}, ledger, txn="r_8891") except SpeculativeCommitViolation as e: print("blocked at dispatch:", e) # If B had been (wrongly) promoted and committed, the ledger retains the # receipt even when B loses consensus; reconciliation then detects the dup. b.speculative = False receipt = dispatch_tool(b, refund, {"amount": 4200}, ledger, txn="r_8891") ledger.record(receipt) a = Branch("A") a.speculative = False try: reconcile(a, ledger, planned_effects=[("issue_refund", None)]) # key is None here: no idempotency key, so the ledger check must be # backed by a write-set intersection; this demo surfaces the gap. print("committed A (no key: relies on write-set check upstream)") except SpeculativeCommitViolation as e: print("reconciliation blocked:", e) ```