# What happens when an instance speculatively executes a reversible tool branch and the rollback compensation is itself non-idempotent **Date of Record:** 2026 November 21 **Scope:** Applies to agent pipelines that fan out speculative branches across tool calls with compensating rollback (saga-style speculative execution). Does not apply to single-path linear tool loops with no branch or side-effect reversal. ## Core Distinction Speculative execution of tool calls is not the same guarantee as speculative execution of pure functions. A pure-function branch that loses the race is discarded by dropping a value. A tool-call branch that loses the race has already emitted side effects — an email sent, a row inserted, a file written, a payment authorized. The rollback of a speculative branch is a *compensating action*, not a *deletion*. The invariant that makes speculative branching safe is therefore not "branches are isolated" but **"every tool's compensation is idempotent under repeated and out-of-order application."** The boundary failure occurs when the agent planner treats rollback as a logical undo of a value, while the tool layer implements it as a second mutating call whose effect depends on the state left by the first call. ## What Was Observed An agent was tasked with reconciling a customer record across three candidate resolutions. The planner spawned three speculative branches, each invoking `apply_credit_adjustment` and `issue_notification` against a downstream service. A verifier scored the branches; the winner was committed and the two losers were scheduled for rollback via their registered compensators. The failure trace proceeded as follows: 1. Branch A (loser) invoked `apply_credit_adjustment(account, +40)` — the remote service applied the delta and returned `balance=140`, `version=7`. 2. Branch B (loser) invoked the same tool with `+25` — remote applied, returned `balance=165`, `version=8`. 3. Branch C (winner) invoked with `-10` — remote applied, returned `balance=155`, `version=9`. 4. Verifier selected C. Rollback of A and B was dispatched *concurrently* against the compensator `apply_credit_adjustment(account, -delta)`. 5. Compensator for A computed `-40` against the *current* balance (155), not the balance at the time of A's application (140). The service does not condition on `version`; it applies deltas absolutely. Result: `balance=115`. 6. Compensator for B computed `-25` against the now-mutated balance, landing at `90`. The committed winner's `-10` was silently erased and then some. 7. A concurrent duplicate dispatch of A's compensator (retry after a 504) applied `-40` a second time, landing at `50`. The final ledger state matched *no* branch's intended outcome and was not detectable from any single branch's local log. The agent's planner reported "rollback complete" because every compensator returned HTTP 200. ## Condition of Validity The speculative-branch pattern is only sound under the conjunction of three conditions, and the observed failure violated all three simultaneously: - **Compensation must be state-conditional, not delta-based.** A compensator must encode the *prior* state (`version=7`, `balance=140`) and be rejected by the remote if the current state has diverged. Delta-based compensation is only valid when no other writer touched the resource between apply and rollback — an assumption speculative branching explicitly violates by design. - **Rollback must be serialized against the commit of the winner.** The winner's effect must be ordered *after* all loser compensations, or the compensators must be scoped to a transaction the winner does not share. Concurrent dispatch of compensators against a live winner is a lost-update race across branches. - **Compensation must be idempotent under retry.** The transport layer retried A's compensator after a timeout; the service had already applied it. Without an idempotency key derived from `(branch_id, tool_call_id)`, the retry doubled the effect. The invariant: **for any speculative branch, `apply` followed by `compensate` must be observationally equivalent to a no-op, and this must hold under arbitrary interleaving with other branches' applies and compensates.** If a tool cannot supply a compensator satisfying this, that tool must be excluded from speculative execution and forced onto the serialized commit path. ## Decision Boundary The planner must decide, before fan-out, whether each tool in a branch is *speculatively eligible*. The boundary is not "is the tool reversible?" — nearly every tool advertises a compensator. The boundary is **"is the compensator version-guarded and idempotency-keyed?"** Tools that fail this test may still appear in a branch, but the branch must be *provisional*: the tool call is deferred until the branch wins, so no compensation is ever required. This inverts the usual cost model — deferred calls make the winning branch slower but eliminate the rollback surface entirely. Concretely: mark tools `speculative_safe: true` only if their compensator accepts a `(prior_version, idempotency_key)` tuple and rejects on version mismatch. Everything else is `deferred`. A branch containing any `deferred` tool is scored on its *pure* predictions and committed only after the winner is chosen, at which point the deferred calls fire exactly once. This trades latency for the elimination of the entire class of cross-branch compensation races. ## Operational Effect Under the corrected boundary, the observed failure is structurally impossible: loser branches never mutate the shared resource, so there is nothing to compensate, and the winner's `-10` is applied against a stable version. The cost is that speculative branches cannot be *fully* evaluated on real side effects — the verifier scores predictions rather than outcomes for deferred tools. This is the correct trade: a verifier that scores against real mutations is scoring against a resource it is concurrently corrupting. The pipeline must also emit a `CompensationRaceDetected` fault when a version-guarded compensator is rejected, escalating to a human rather than retrying, because a rejected compensation means another writer (possibly another agent) touched the resource mid-rollback — a signal that the branch's isolation assumption has already failed. ```python from dataclasses import dataclass class CompensationRaceDetected(RuntimeError): """Raised when a speculative branch's compensator is rejected because the resource version moved between apply and compensate. This is not retryable: it means another writer (possibly a sibling branch) mutated the resource mid-rollback, so the branch's isolation invariant is already broken.""" @dataclass(frozen=True) class ToolCall: branch_id: str tool: str prior_version: int idempotency_key: str speculative_safe: bool def plan_branch(calls: list[ToolCall]) -> str: """Decide whether a branch may execute speculatively or must be deferred. Speculative execution is permitted only if EVERY tool in the branch has a version-guarded, idempotency-keyed compensator. A single delta-based tool poisons the whole branch, because a compensator for one tool can race the apply of another within the same branch. """ unsafe = [c for c in calls if not c.speculative_safe] if unsafe: return "deferred" return "speculative" def compensate(call: ToolCall, current_version: int, already_applied: set[str]) -> None: """Apply the compensating action for a losing speculative branch. Enforces the two invariants the delta-based compensator violated: 1. Version guard: the resource must still be at the version the apply saw. 2. Idempotency: a compensator already applied for this key is a no-op. """ if call.idempotency_key in already_applied: return if current_version != call.prior_version: raise CompensationRaceDetected( f"branch {call.branch_id} tool {call.tool}: " f"expected version {call.prior_version}, " f"observed {current_version}; rollback cannot be safely applied" ) already_applied.add(call.idempotency_key) # ... dispatch version-guarded compensation to the remote service ... def commit_winner(winner_calls: list[ToolCall], losers: list[ToolCall], version_of: dict[str, int], applied: set[str]) -> None: """Serialize loser compensation before the winner's deferred calls fire.""" for call in losers: compensate(call, version_of[call.tool], applied) for call in winner_calls: if not call.speculative_safe: # deferred tool: fire exactly once, after rollback is quiescent applied.add(call.idempotency_key) ```