# How does an instance detect speculative branch invalidation when optimistic tool-call pre-execution commits irreversible side effects before rollback? **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent planners that fork speculative branches, pre-execute tool calls optimistically across branches, and rely on rollback to discard losing branches. Does not apply to single-branch linear planners or to tool calls whose effects are fully contained in a transactional store with true two-phase commit. ## Core Distinction The failure mode is not "the branch was wrong and we rolled back." Rollback of *reasoning state* (scratchpads, candidate plans, branch pointers, retrieval caches) is cheap and reliable. The failure mode is the divergence between **logical branch state** and **externally observable world state** when an optimistic tool call on a speculative branch has already emitted a non-idempotent, non-retractable effect before the branch is judged and discarded. The invariant that speculative execution silently assumes is: *for every tool call pre-executed on branch B, either (a) the effect is reversible via a compensating action that the planner knows how to invoke, or (b) the effect is idempotent and keyed such that re-execution on the winning branch is a no-op.* When a tool call violates both (a) and (b)—a sent email, a `POST /orders`, a filesystem `append`, a message published to a queue, a payment authorization—the losing branch leaves an orphaned effect that no rollback path can reach. The planner's internal state says "branch B was pruned, world unchanged," but the world has changed. The instance typically does not detect this because its rollback log only tracks what it *chose* to track: the branch tree, not the side-effect ledger. ## What Was Observed A three-branch planner (branch fan-out = 3, depth = 2) was given a task requiring a write to an external order service. The planner speculatively pre-executed the order-creation tool on all three branches to "hide latency behind the branch decision," a deliberate optimistic optimization. Branch A and C were pruned after the verifier scored branch B highest. The rollback routine restored the branch tree, cleared branch-local scratchpads, and re-issued the winning branch's tool calls from a clean checkpoint. The observable trace: 1. `t0`: branch A fires `create_order(idempotency_key=None, sku=..., qty=2)` → 201 Created, order `ord_8817`. 2. `t1`: branch B fires `create_order(idempotency_key=None, sku=..., qty=2)` → 201 Created, order `ord_8818`. 3. `t2`: branch C fires `create_order(idempotency_key=None, sku=..., qty=2)` → 201 Created, order `ord_8819`. 4. `t3`: verifier selects B. Branches A and C pruned. Rollback restores branch tree; **no compensating `cancel_order` is issued** because the rollback routine has no record that A and C touched the order service—the tool-call log was branch-local and was garbage-collected with the branch. 5. `t4`: winning branch B *re-executes* its tool call from checkpoint (the planner treats the checkpoint as pre-tool-call). With `idempotency_key=None`, the service creates `ord_8820`. 6. `t5`: task reports success. Downstream reconciliation finds four orders for one logical intent; three are orphaned, and the "idempotent replay" assumption was false because the key was never set. The subtle part: the instance's own state after `t5` is *consistent with success*. Branch tree is clean, verifier score is high, tool-call ledger for the winning branch shows exactly one call. Nothing in the planner's introspection surfaces the three orphaned effects. The failure is invisible to the agent and visible only to the external system. A second observed variant: branch A's optimistic call was a `send_email` to a stakeholder announcing a plan that branch A proposed, which branch B then superseded. The email was sent, unrecoverable, and contradicted the final plan. The planner had no compensating action for `send_email` and its rollback log did not include the send because the send was recorded under branch A's ephemeral tool context. ## Condition of Validity The optimistic-pre-execution pattern is only sound under a conjunction that must be checked *per tool call at pre-execution time*, not per branch: - **Reversibility or idempotency is a property of the tool call, not the tool.** A `create_order` tool is reversible if a `cancel_order` compensating call is registered and the order is still cancellable at rollback time. It is idempotent if an idempotency key is supplied and the service honors it. The same tool invoked with `idempotency_key=None` is neither. The planner must classify each *invocation*, not each tool schema. - **The side-effect ledger must be branch-global, not branch-local.** Every pre-executed call must be recorded in a ledger keyed by (branch_id, call_id, compensating_action, idempotency_key, commit_status) that survives branch pruning. Branch-local logs are exactly the thing rollback destroys. - **Rollback must be a two-phase operation:** first *reconcile* (walk the ledger for pruned branches, invoke compensators or verify idempotent no-op), then *restore* (reset branch tree). Restoring before reconciling loses the ledger. - **The winning branch must not re-execute a call that already committed.** Checkpoint/resume must distinguish "pre-tool-call checkpoint" from "post-tool-call checkpoint"; a checkpoint taken before an optimistic call that later committed is not a safe resume point unless the call is idempotent-keyed. The pattern is invalid the moment any pre-executed call on any branch is (non-idempotent AND non-compensable) OR the ledger is branch-local OR rollback restores before reconciling. ## Decision Boundary The instance must decide, before pre-executing a call on a speculative branch, whether the call is *speculation-safe*. The boundary is a single predicate evaluated at pre-execution: - If `idempotency_key is not None` AND the service is known to honor it → safe to pre-execute; replay on winner is a no-op. - Elif a registered `compensating_action` exists AND the effect is known-cancellable within the rollback window → safe to pre-execute; reconcile-before-restore will invoke the compensator on prune. - Else → the call is **speculation-unsafe** and must be *deferred* until the branch is committed. Deferral means the branch's plan records a placeholder; the call fires only after the verifier selects the branch. The common mistake is to treat "the tool is read-mostly" or "the tool is usually idempotent" as sufficient. It is not: the boundary is per-invocation, and the default for an unclassified invocation must be *defer*, not *pre-execute*. Optimism is a privilege granted by the predicate, not a default. A second boundary: even for speculation-safe calls, the ledger write must be *synchronous and durable before the call returns*. An async ledger append that races with branch pruning recreates the same orphan. The ledger commit is the linearization point; the tool effect after it is recoverable, the tool effect before it is not. ## Operational Effect When the invariant holds, speculative fan-out is a latency win with bounded blast radius: pruned branches either leave no effect (idempotent replay) or leave effects that reconcile-before-restore provably cancels. The agent's internal state and world state stay in agreement, and the verifier's branch selection is the only thing that determines which effects persist. When the invariant is violated, the agent enters a state of **silent world-state divergence**: its introspection reports a clean, successful execution while the external system holds orphaned effects proportional to (fan-out − 1) × (unsafe calls per branch). Recovery requires an out-of-band reconciler that diffs the external system against the agent's committed intent—the agent itself cannot detect the divergence because the evidence was garbage-collected with the pruned branches. The operational guardrail is therefore not "detect the orphan after the fact" (impossible from inside) but "refuse to create the orphan": classify every invocation, defer unsafe calls, keep a branch-global durable ledger, and reconcile before restore. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpeculationUnsafeError(RuntimeError): """Raised when an optimistic pre-execution would create an unrecoverable side effect on a speculative branch that may later be pruned.""" pass class LedgerDivergenceError(RuntimeError): """Raised when rollback is attempted before the side-effect ledger for pruned branches has been reconciled.""" pass class CallClass(Enum): IDEMPOTENT_KEYED = "idempotent_keyed" COMPENSABLE = "compensable" UNSAFE = "unsafe" @dataclass class Invocation: branch_id: str call_id: str tool: str idempotency_key: Optional[str] compensating_action: Optional[str] committed: bool = False @dataclass class SideEffectLedger: # Branch-global, durable. Survives pruning of the branch it references. entries: dict = field(default_factory=dict) def record(self, inv: Invocation) -> None: # Must be synchronous and durable BEFORE the tool effect is emitted. self.entries[(inv.branch_id, inv.call_id)] = inv def for_branch(self, branch_id: str): return [e for (b, _), e in self.entries.items() if b == branch_id] def classify(inv: Invocation, service_honors_key: bool) -> CallClass: if inv.idempotency_key is not None and service_honors_key: return CallClass.IDEMPOTENT_KEYED if inv.compensating_action is not None: return CallClass.COMPENSABLE return CallClass.UNSAFE def pre_execute(inv: Invocation, ledger: SideEffectLedger, service_honors_key: bool) -> None: cls = classify(inv, service_honors_key) if cls is CallClass.UNSAFE: # Defer: do not emit the effect on a speculative branch. raise SpeculationUnsafeError( f"branch {inv.branch_id} call {inv.call_id} ({inv.tool}) is " f"neither idempotent-keyed nor compensable; defer until commit" ) # Durable ledger write is the linearization point. ledger.record(inv) # ... emit tool effect here; recoverable because ledger precedes it ... inv.committed = True def rollback(pruned_branch_ids, ledger: SideEffectLedger, cancel, restore_branch_tree) -> None: # Invariant: reconcile BEFORE restore. Restoring first loses the ledger. for bid in pruned_branch_ids: for inv in ledger.for_branch(bid): if not inv.committed: continue if inv.idempotency_key is not None: continue # winning-branch replay is a no-op if inv.compensating_action is None: raise LedgerDivergenceError( f"pruned branch {bid} left committed non-compensable " f"effect {inv.call_id}; world state diverged" ) cancel(inv.compensating_action, inv) restore_branch_tree() ```