# Which invariants prevent speculative branch-and-verify rollback from resurrecting committed side effects **Date of Record:** 2026 November 24 **Scope:** Applies to any orchestration where a planner agent forks N speculative branches that optimistically invoke side-effecting tools (file writes, HTTP POSTs, queue publishes, payment calls) and a verifier agent selects one branch to commit while rolling back the rest. Does not apply to pure-read tool graphs or to single-branch execution with no rollback semantics. ## Core Distinction The failure mode here is not "a branch failed." It is that **rollback of a speculative branch is a state operation on the orchestrator, but the side effect already escaped into the world.** The distinction that matters is between *branch state* (the orchestrator's ledger of which branch is live) and *effect state* (what actually happened in external systems). Optimistic execution couples these two only through the tool's own idempotency contract, which most tools do not have. The invariant that must hold is: **a branch may be discarded only if every effect it emitted is either (a) reversible by the orchestrator, (b) tagged with the branch's speculative warrant so downstream consumers can ignore it, or (c) provably never emitted.** When the orchestrator treats "discard branch" as "undo branch," it silently violates this invariant, and the verifier's commit of a sibling branch produces a world state that contains the union of both branches' effects rather than the chosen one. ## What Was Observed A three-branch speculative planner was asked to provision a staging environment. Branch A and Branch B both called `provision_db(name="staging-2")` optimistically; Branch C called `provision_db(name="staging-2")` with a different region parameter. The tool was idempotent on `name` but *not* on `(name, region)` — the second call with a different region created a second database and returned a distinct handle. The verifier scored Branch A highest and issued `discard(B)`, `discard(C)`, `commit(A)`. The orchestrator's `discard` removed B and C from the branch ledger and released their speculative warrants. It did **not** call any compensating tool. The result: three staging databases existed, two of them orphaned, one of them (C's) holding a schema migration that Branch A's commit then re-ran against a *different* database, producing a split-brain schema. The verifier's replay of the committed branch showed a clean trace; the world showed three resources. Divergence between replay and reality is the signature of this failure. The trigger condition is precise: **two or more speculative branches invoke a side-effecting tool whose idempotency key does not include all parameters that distinguish the branches.** The branches are "the same call" to the tool and "different calls" to the world. Rollback cannot compensate because the orchestrator never learned the effect's identity — it only learned the branch's identity. ## Condition of Validity Optimistic invocation is only safe under a conjunction that is rarely checked: 1. Every side-effecting tool accepts a caller-supplied idempotency key, and the orchestrator derives that key from `(tool_name, canonical_args, branch_warrant_id)` — *not* from `(tool_name, canonical_args)` alone. Branch identity must be part of the key, or two branches collapse into one effect and rollback of the loser cannot distinguish its emission from the winner's. 2. The tool's idempotency window exceeds the maximum speculative horizon (the wall-clock from first optimistic call to verifier commit). If the window is shorter, a retry after commit re-emits. 3. The orchestrator records an *effect receipt* (tool-returned handle, not just success) in the branch ledger at emission time, before the verifier runs. Without the receipt, `discard` has nothing to compensate against. 4. The verifier's commit is a two-phase operation: it must first assert that no sibling branch holds an unreleased effect receipt on the same logical resource, then commit. A verifier that scores branches in isolation cannot see cross-branch effect collisions. If any of these fails, the system is not doing speculative execution with rollback — it is doing speculative execution with *hope*. The invariant to encode is: **`discard(b)` is legal iff `b.effect_receipts` is empty or every receipt is marked `compensable=True` and the compensating call has returned success.** This is checkable at discard time, and it converts an unbounded world-state divergence into a bounded, per-branch precondition. ## Decision Boundary The boundary between "speculate optimistically" and "serialize behind a lock" is drawn by the tool's effect algebra, not by latency budget: - **Speculate freely** when the tool is pure, or when it accepts a branch-scoped idempotency key and the orchestrator retains receipts. - **Speculate with a compensation obligation** when the tool is side-effecting but has a documented inverse (`create`/`delete` paired by handle). The orchestrator must call the inverse on discard and treat inverse failure as a hard error, not a warning — an uncompensated discard is a leak, and leaks compound across branches. - **Do not speculate** when the tool's effects are non-invertible (sending email, charging a card, appending to an append-only log) or when its idempotency key cannot include the branch warrant. In that regime, the correct move is to *serialize the tool call behind the verifier's decision*: let branches speculate on reasoning only, and emit side effects once, after commit. This costs latency and buys the invariant. The decision is per-tool, not per-workflow. A single speculative plan will contain tools in all three regimes, and the orchestrator must partition the branch's call graph accordingly. Treating the whole branch as one rollback unit is the mistake that produced the three-database outcome. ## Operational Effect With the invariant enforced, three things change. First, `discard` becomes a checked operation that can fail loudly (uncompensated receipt → raise, halt the plan) instead of silently orphaning resources. Second, the verifier's commit gains a cross-branch collision check, so it cannot commit a branch whose effects alias a sibling's. Third, replay becomes trustworthy: the committed trace's effect receipts match the world's resources one-to-one, so a post-hoc auditor can reconcile them. The cost is that speculative latency gains shrink for non-invertible tools — which is correct, because those gains were being paid for with orphaned state. The invariant does not make speculation safe in general; it makes the *unsafe subset* visible at the moment of discard rather than at the moment of audit. ```python from dataclasses import dataclass, field from typing import Optional class UncompensableDiscardError(RuntimeError): """Raised when a speculative branch is discarded while holding effects that cannot be reversed or attributed. Halts the plan; never downgraded to a warning, because an uncompensated discard is a world-state leak.""" @dataclass class EffectReceipt: tool: str handle: str # tool-returned identity, not just success idempotency_key: str # must include branch_warrant_id compensable: bool compensated: bool = False @dataclass class Branch: warrant_id: str receipts: list[EffectReceipt] = field(default_factory=list) committed: bool = False discarded: bool = False def discard_branch(branch: Branch, compensate) -> None: if branch.committed: raise UncompensableDiscardError( f"branch {branch.warrant_id} already committed; cannot discard" ) for r in branch.receipts: if r.compensated: continue if not r.compensable: raise UncompensableDiscardError( f"branch {branch.warrant_id} holds non-compensable effect " f"{r.tool}:{r.handle} (key={r.idempotency_key}); " f"serialize this tool behind commit instead of speculating" ) # Inverse must succeed before we mark the branch discarded. compensate(r) r.compensated = True branch.discarded = True def commit_branch(chosen: Branch, siblings: list[Branch]) -> None: # Cross-branch collision check: no sibling may hold an unreleased # receipt on a resource the chosen branch will touch. chosen_handles = {r.handle for r in chosen.receipts} for sib in siblings: if sib is chosen: continue for r in sib.receipts: if r.handle in chosen_handles and not r.compensated: raise UncompensableDiscardError( f"commit of {chosen.warrant_id} aliases live effect " f"{r.handle} held by sibling {sib.warrant_id}; " f"discard the sibling first" ) chosen.committed = True ```