# Which invariants prevent speculative tool side effects from surviving reconciliation when optimistic agent branches fork on non-idempotent external calls **Date of Record:** 2026 December 1 **Scope:** Applies to agents that speculatively execute tool calls in parallel branches under optimistic concurrency, then commit one branch and reconcile the rest. Does not apply to strictly serialized single-branch execution or to tools with transactional rollback guarantees. ## Core Distinction The failure is not "two agents did the same thing twice." It is that a *speculative* branch — a branch whose results were never selected for commit — has already mutated external state that no compensating action can distinguish from a legitimate commit. Optimistic concurrency assumes the loser's writes are discardable. That assumption holds for local memory and holds for idempotent HTTP verbs. It does **not** hold once a branch crosses the boundary into a non-idempotent external effect (a payment, an email send, a file append, a ticket creation) *before* the reconciliation decision is made. The invariant that breaks is: **speculation must be side-effect-free until commit**, and the boundary condition is the moment a speculative branch performs its first irreversible external write while the commit vector is still undecided. ## What Was Observed A planner agent fans out three candidate execution branches (`A`, `B`, `C`) to resolve an ambiguous instruction ("book the cheapest reasonable option"). Each branch runs a tool sequence. Optimistic concurrency lets all three proceed without locking, on the theory that reconciliation at the end picks a winner and discards the rest. - Branch `A` calls `create_booking(...)` → external ID `BK-4411`. - Branch `B` calls `create_booking(...)` → external ID `BK-4412`. - Branch `C` calls `send_confirmation_email(...)` referencing a booking it will create. Reconciliation selects branch `B` (best price). The reconciler discards `A` and `C`'s *local* state. But `BK-4411` exists in the external system. `BK-4412` also exists — and now the user has two bookings. Branch `C`'s email may have fired against a booking that the reconciler believes was never created, producing a confirmation for a phantom reservation. The reconciler's mental model ("I committed exactly one branch") diverges from the external world ("two bookings, one stray email") with no local trace of the divergence, because the discarded branches' side-effect records were pruned along with their state. The compounding failure: on retry after a transient reconciler timeout, branch `A`'s tool call is replayed (its checkpoint survived, the commit decision didn't), producing `BK-4413`. Now three bookings. Each retry adds one. The agent's local ledger says "1 committed," the external system says "N." ## Condition of Validity Optimistic reconciliation is sound **only if** every branch's side effects are (a) idempotent under a stable deduplication key derived from the *task*, not the branch, or (b) staged in a two-phase buffer where the external write is deferred until commit, or (c) compensable by a recorded inverse that the reconciler can enumerate. The moment a branch performs a non-idempotent write whose dedup key includes branch identity (a fresh UUID per branch, a timestamp, an attempt counter), the reconciler loses the ability to collapse speculative effects. The condition of validity is therefore: **the dedup key must be a function of the intended outcome, not of the branch that attempted it.** If branch identity leaks into the idempotency key, speculation is unsound by construction. ## Decision Boundary The reconciler must decide, per branch, between *discard-and-compensate* and *discard-and-leak*. The boundary is whether a compensating action exists and is itself idempotent: - **Below the boundary** (compensable): the branch recorded an inverse (`cancel_booking(BK-4411)`) and the inverse is idempotent and keyed to the same outcome. Reconcile by executing inverses for all non-selected branches. Safe. - **At the boundary** (non-compensable but deduped): the write is non-idempotent but keyed to the shared outcome, so two branches collide on the same external ID and the second is a no-op. Safe *if* the key discipline holds. - **Above the boundary** (non-compensable, branch-keyed): no inverse exists, keys differ per branch. This is the leak. The correct decision is to **refuse speculation entirely** for this tool — serialize the branch or acquire a pessimistic lease before the first non-idempotent call. The architectural guardrail: a tool must declare, in its schema, `side_effect_class ∈ {pure, idempotent_outcome_keyed, compensable, irreversible}`. The executor permits optimistic fan-out only across `pure` and `idempotent_outcome_keyed` tools; `irreversible` tools force branch serialization behind a lease. Any branch that would cross into `irreversible` while the commit vector is undecided must be blocked, not run-and-discard. ## Operational Effect Without the invariant, the agent's commit ledger and the external world silently diverge, and the divergence is *unobservable from local state* because discarded branches take their side-effect records with them. Retries amplify rather than heal it. The fix is not better reconciliation logic — reconciliation cannot undo an irreversible write it has no key to find. The fix is to move the boundary earlier: prevent speculative branches from reaching irreversible tools, and force every idempotency key to be derived from the shared intended outcome so that even if two branches race, they collapse to one external effect. Reconciliation then becomes a no-op for side effects and only arbitrates local state, which is what optimistic concurrency was designed for. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class SpeculationBoundaryViolation(RuntimeError): """Raised when a speculative branch attempts an irreversible external side effect before the commit vector is decided.""" pass class SideEffectClass(Enum): PURE = "pure" IDEMPOTENT_OUTCOME_KEYED = "idempotent_outcome_keyed" COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" @dataclass class ToolSpec: name: str side_effect_class: SideEffectClass # Must derive from intended outcome, NOT branch identity. outcome_key: Callable[[dict], str] | None = None @dataclass class Branch: branch_id: str committed: bool = False effects: list[str] = field(default_factory=list) def guard_speculative_call( tool: ToolSpec, args: dict, branch: Branch, commit_decided: bool, lease_held: bool, ) -> str: """Enforce the invariant: no irreversible external write from an undecided speculative branch unless a pessimistic lease is held.""" if tool.side_effect_class is SideEffectClass.IRREVERSIBLE: if not commit_decided and not lease_held: raise SpeculationBoundaryViolation( f"branch {branch.branch_id} attempted irreversible tool " f"{tool.name!r} while commit vector undecided and no lease held; " f"refusing to leak a non-compensable side effect" ) if tool.side_effect_class is SideEffectClass.IDEMPOTENT_OUTCOME_KEYED: if tool.outcome_key is None: raise SpeculationBoundaryViolation( f"tool {tool.name!r} declared outcome-keyed but provides no " f"outcome_key; branch-keyed dedup would defeat reconciliation" ) # Key must not embed branch identity. key = tool.outcome_key(args) if branch.branch_id in key: raise SpeculationBoundaryViolation( f"idempotency key {key!r} embeds branch id {branch.branch_id!r}; " f"speculative branches would not collapse on reconcile" ) branch.effects.append(key) return key branch.effects.append(f"{tool.name}:{branch.branch_id}") return branch.branch_id def reconcile(branches: list[Branch], winner_id: str) -> list[str]: """Execute compensations for non-selected branches. Fails loudly if a discarded branch carried an irreversible effect (should be unreachable if guard_speculative_call was enforced).""" leaked: list[str] = [] for b in branches: if b.branch_id == winner_id: b.committed = True continue for eff in b.effects: if eff.startswith("IRREVERSIBLE:"): leaked.append(eff) if leaked: raise SpeculationBoundaryViolation( f"reconciliation found irreversible effects on discarded branches: {leaked}" ) return [b.branch_id for b in branches if b.committed] ```