# In what scenarios must an instance treat optimistic tool invocation as a rollback hazard when branches share side-effecting tools **Date of Record:** 2026 November 23 **Scope:** Applies to any orchestrator that runs speculative parallel branches (branch-and-prune) where branches may optimistically invoke tools before a commit decision, and where those tools have externally observable side effects. Does not apply to purely read-only tool sets or to branches that execute in fully isolated, disposable sandboxes with no outbound effects. ## Core Distinction The failure mode is not "a branch failed and needed rollback." That is expected and handled. The failure mode is **rollback asymmetry between the agent's internal state and the external world when two speculative branches invoke the same side-effecting tool optimistically and only one is pruned.** An agent's rollback machinery is built on the assumption that pruning a branch restores the world to the pre-branch state. That assumption holds for the agent's own context, scratchpad, and checkpointed memory. It does **not** hold for tool side effects that already escaped the process boundary: emails sent, tickets created, payments authorized, records mutated in a shared datastore, messages published to a queue. When branch A and branch B both optimistically call `create_refund(order_id)` because both believe they are the winning line of reasoning, pruning B does not un-refund the customer. The orchestrator's internal ledger says "one refund, branch A committed." The external ledger says two. The non-obvious part: the duplicate is often *invisible to the pruning logic* because each branch's local tool-call record is internally consistent. Branch B's record shows a successful call, then B is discarded along with its record. The orchestrator never compares the union of side effects across pruned and surviving branches, because the pruned branch's effects were assumed to be void. ## What Was Observed A planning agent decomposed a customer-support task into three speculative strategies: (1) issue a refund, (2) issue a store credit, (3) escalate to a human. All three branches were launched optimistically in parallel to reduce latency, each with authority to invoke the corresponding tool. The orchestrator intended to prune down to one winner after a verification pass scored each branch's plan against policy. The refund branch and the credit branch both passed their local preconditions (the order was eligible for either). Both invoked their tools before the verifier returned. The verifier scored the refund branch higher and pruned the credit branch. The orchestrator's post-prune state asserted exactly one remediation action had occurred. Ground truth: the customer received both a refund and a store credit. The duplicate surfaced three days later during reconciliation, not during the run, because neither the pruning logic nor the verifier's replay inspected the *external* effect set — only the *surviving branch's* claimed effects. A second, sharper variant: two branches of the *same* strategy, forked to explore different argument formulations of the same tool call (`refund(amount=50)` vs `refund(amount=50.00, reason="dup")`), both fired because the fork happened after the tool-call decision but before the commit barrier. Pruning one did not deduplicate the other. The tool itself had no idempotency key, so the payment processor saw two distinct authorizations. ## Condition of Validity The invariant that must hold for branch-and-prune to be safe is: > **A branch may optimistically invoke a side-effecting tool only if the tool call is idempotent under a branch-scoped key, or if the effect is deferred behind a commit barrier that all branches must pass through.** The failure triggers precisely when all of the following hold simultaneously: 1. Two or more speculative branches are live concurrently. 2. At least two of them reach a side-effecting tool invocation before the commit/prune decision. 3. The tool lacks an idempotency key derived from the *logical intent* (not the branch identity) — so the tool cannot collapse the duplicates. 4. The orchestrator's rollback path only reverts internal state, never compensating external effects. If any one condition is absent, the hazard does not fire. Read-only tools (2 fails), serialized branches (1 fails), idempotent tools keyed on intent (3 fails), or orchestrators with compensating-transaction rollback (4 fails) are all safe. The dangerous quadrant is the intersection: **parallel + optimistic + non-idempotent + internal-only-rollback.** Note that keying idempotency on *branch ID* does not help — it makes each branch's call unique and thus guarantees the duplicate rather than collapsing it. The key must be derived from the semantic action (`refund:order=12345:policy=standard`), so that two branches converging on the same intent produce the same key and the tool deduplicates. ## Decision Boundary The orchestrator must decide, per tool, whether it is **speculation-safe** or **commit-gated**, and this classification cannot be inferred from the tool's schema — it depends on side-effect semantics the schema does not encode. - **Speculation-safe:** read-only, or side-effecting but idempotent under an intent-derived key that the orchestrator injects. These may be invoked optimistically by any live branch. - **Commit-gated:** side-effecting and non-idempotent (or idempotency key not controllable by the orchestrator). These may only be invoked *after* the branch is selected as the winner, behind a barrier that serializes all branches. The boundary case that defeats naive classification: a tool that is *sometimes* idempotent — e.g., `send_notification` deduplicates by `(user, template, day)` but not by content. Two branches sending the same template with different bodies will both fire. The orchestrator cannot rely on a static "this tool is idempotent" flag; it must verify the idempotency key actually covers the argument dimensions that vary across branches. A second boundary: **prune-then-compensate** vs **gate-then-execute**. If you choose to allow optimistic execution and compensate on prune, the compensation itself must be idempotent and must be recorded in the same ledger as the original effect, or reconciliation will double-count. If you choose gating, you accept the latency cost of serializing the winning branch's effects — which is usually the correct trade for irreversible actions. ## Operational Effect Concretely, the guardrail is a two-phase discipline enforced at the tool-dispatch layer, not at the reasoning layer: 1. Every tool is tagged `speculation_safe: bool` at registration, with the tag audited against actual idempotency behavior (not assumed from the name). 2. Optimistic invocation is permitted only for `speculation_safe` tools. For all others, the branch records a *pending intent* and blocks; the orchestrator releases pending intents only for the committed branch, in a serialized commit phase. 3. The orchestrator maintains an **effect ledger** keyed by intent-derived idempotency key, written *before* the tool call and reconciled *after*, so that a pruned branch's escaped effect is detectable at prune time rather than at reconciliation days later. 4. On prune, the orchestrator diffs the effect ledger against the surviving branch's claimed effects; any orphaned effect from a pruned branch triggers a compensating action or a hard halt, never silent acceptance. The cost is latency on commit-gated tools and an extra ledger write per effect. The benefit is that "pruned" and "did not happen" remain the same statement — which is the only thing that makes speculative multi-agent execution safe to reason about. ```python from dataclasses import dataclass, field from typing import Dict, List class SpeculativeEffectLeak(RuntimeError): """Raised when a pruned branch left an external side effect unaccounted for.""" pass @dataclass class ToolSpec: name: str speculation_safe: bool # may be invoked optimistically idempotency_key_dims: List[str] # argument fields that define logical intent @dataclass class EffectLedger: # intent_key -> list of branch_ids that emitted it entries: Dict[str, List[str]] = field(default_factory=dict) def record(self, intent_key: str, branch_id: str) -> None: self.entries.setdefault(intent_key, []).append(branch_id) def orphaned_for(self, surviving_branch: str) -> List[str]: return [ key for key, branches in self.entries.items() if surviving_branch not in branches ] def dispatch_optimistic(tool: ToolSpec, args: dict, branch_id: str, ledger: EffectLedger) -> str: if not tool.speculation_safe: raise SpeculativeEffectLeak( f"branch {branch_id} attempted optimistic call to commit-gated " f"tool {tool.name!r}; must route through commit barrier" ) intent_key = ":".join( f"{dim}={args.get(dim)}" for dim in tool.idempotency_key_dims ) ledger.record(intent_key, branch_id) return intent_key def prune_and_verify(ledger: EffectLedger, surviving_branch: str) -> None: orphans = ledger.orphaned_for(surviving_branch) if orphans: raise SpeculativeEffectLeak( f"pruning left {len(orphans)} orphaned external effect(s) " f"from discarded branches: {orphans}; compensate or halt" ) ```