# When must an instance abort a speculative branch rather than commit it: divergent tool-call side effects under optimistic fork-and-merge **Date of Record:** 2026 November 26 **Scope:** Applies to multi-agent planners that fork a shared reasoning state into N speculative branches, execute tool calls optimistically inside each branch, and merge the winning branch back into the canonical state. Does not apply to strictly serialized single-agent loops or to branches whose tool calls are provably pure (no external side effects). ## Core Distinction The failure mode is not "a speculative branch produced a wrong answer." Wrong answers are cheap—you discard the branch. The failure is that a speculative branch produced an *externally committed side effect* whose rollback the fork/merge machinery cannot perform, while the branch's *reasoning result* was still judged inferior and discarded. The system believes it rolled back because the state object was reverted; the world did not roll back because the tool call already mutated it. This is the gap between **logical rollback** (restoring the in-memory branch context) and **physical rollback** (undoing an irreversible external action). Optimistic forking assumes these are the same operation. They are not, and the divergence is silent. ## What Was Observed A tri-branch planner forked a task state at step 7 into branches A, B, C. Each branch was permitted to call tools under a "speculative" flag intended to mean *execute but do not commit to canonical memory*. The flag was enforced by the orchestrator's state layer—it suppressed writes to the episodic store and deferred the branch's `context_delta` until merge. It did **not** intercept the tool transport. Trace of the trigger condition: 1. Branch A called `issue_refund(order_id, amount)` at step 9. The tool returned `200 OK`. The refund was real. The orchestrator recorded the call as speculative and marked the side effect "pending merge." 2. Branch B reached the same decision point via a different reasoning path and called `issue_refund` with a *corrected* amount. Also real, also `200 OK`. 3. Branch C produced the branch the auditor scored highest. The merge committed C and discarded A and B. The orchestrator reverted the branch contexts, cleared the pending side-effect ledger entries as "unmerged," and reported a clean rollback. 4. The customer received two refunds. The canonical state contained zero refund records. The next reconciliation pass flagged an unexplained debit-to-ledger gap with no provenance, because the side-effect ledger entries had been *deleted on discard* rather than *retained as orphans*. The non-obvious part: the system's own invariant check passed. "Every committed side effect appears in canonical state" held trivially—there were no committed side effects. The violated invariant was its dual: **every executed side effect appears in the side-effect ledger, merged or not.** Discard logic purged the ledger instead of quarantining it. A second observation compounded this. Speculative tool-call *validation* (schema and precondition checks run before dispatch) had been treated as a substitute for rollback safety. Validation confirmed `issue_refund` was a legal call for branch A's state. It said nothing about whether the call was *reversible*. The planner conflated "the call is well-formed" with "the call is safe to fork." ## Condition of Validity The fork-and-merge model is only sound under the invariant that **speculative branches may execute only idempotent-and-reversible tools, or must stage irreversible tools behind a commit gate that fires exactly once at merge.** Formally, for every tool `t` invoked in a speculative branch: - If `t` is pure or idempotent with a compensating inverse `t⁻¹` that the orchestrator can invoke deterministically, optimistic execution is permitted and discard must call `t⁻¹`. - If `t` is irreversible and lacks a compensating inverse (payments, message sends, file deletions, external API mutations), the call must be *staged*: captured as a deferred intent, dispatched only after the branch is selected, and dispatched exactly once even if two branches generated equivalent intents. The invariant fails the moment the tool classification is inferred from the schema rather than declared. A schema that accepts `(order_id, amount)` reveals nothing about reversibility; the planner guessed "refund is probably fine" from the name. Classification must be an explicit, per-tool, transport-level property that the fork machinery reads—not a property the reasoning model infers at call time, because the model will infer optimistically under token pressure. ## Decision Boundary Abort the speculative branch (do not merely discard it) when any of the following holds at merge time: - **Irreversible side effect already dispatched from a non-selected branch.** Abort escalates to a reconciliation task; the branch's ledger entries are quarantined as orphans, never purged. The merge halts because canonical state can no longer be trusted to reflect the world. - **Two or more branches dispatched equivalent irreversible intents** (same semantic effect, possibly different parameters). This is not a merge conflict to resolve by scoring—it is a double-execution that already happened. Abort and emit a compensating-action plan. - **A branch's staged intent was promoted to dispatch before selection** due to a timeout or eager-flush path. The staging gate leaked; abort the whole fork generation, not just the branch. Do **not** abort merely because a branch's staged (undispatched) intents differ from the winner's—those are safely droppable. The boundary is strictly *dispatched* versus *staged*, and it is crossed by the transport, not by the reasoning layer. Any code path that can move an intent from staged to dispatched before the merge decision is a boundary violation regardless of intent. ## Operational Effect Enforcing the boundary converts a silent double-execution into a loud, recoverable halt. The cost is throughput: irreversible tools lose parallel speculation and serialize behind the commit gate, so fork fan-out for those branches collapses to one. The benefit is that rollback becomes honest—discard either invokes a real compensating inverse or refuses to claim rollback occurred. The side-effect ledger must be append-only and survive branch discard; orphaned entries are the audit trail that makes reconciliation possible. The practical rule the planner must internalize: **speculation is free for reasoning and staged for effects; only the merge commits, and it commits each irreversible intent exactly once.** A branch that cannot honor that is not a speculative branch—it is an unguarded write, and it must abort before it dispatches. ```python from dataclasses import dataclass, field from enum import Enum class SpeculativeRollbackError(RuntimeError): """Raised when a speculative branch cannot be safely rolled back.""" pass class ToolClass(Enum): PURE = "pure" REVERSIBLE = "reversible" # has a deterministic compensating inverse IRREVERSIBLE = "irreversible" # external mutation, no inverse @dataclass class Intent: tool: str args: dict tool_class: ToolClass dispatched: bool = False branch_id: str = "" @dataclass class Branch: branch_id: str score: float intents: list = field(default_factory=list) def merge(branches: list) -> Branch: if not branches: raise SpeculativeRollbackError("cannot merge empty fork generation") winner = max(branches, key=lambda b: b.score) # Detect irreversible effects dispatched from non-selected branches. dispatched_irreversible = [ (b.branch_id, i) for b in branches for i in b.intents if i.dispatched and i.tool_class is ToolClass.IRREVERSIBLE ] non_winner_dispatched = [ (bid, i) for bid, i in dispatched_irreversible if bid != winner.branch_id ] if non_winner_dispatched: # Do NOT purge these from the ledger; quarantine and halt. raise SpeculativeRollbackError( f"irreversible side effects dispatched from discarded branches: " f"{[(bid, i.tool) for bid, i in non_winner_dispatched]}; " f"quarantine ledger entries and emit compensating-action plan" ) # Detect double-execution of equivalent irreversible intents across branches. seen = {} for b in branches: for i in b.intents: if i.dispatched and i.tool_class is ToolClass.IRREVERSIBLE: key = (i.tool, tuple(sorted(i.args.items()))) if key in seen: raise SpeculativeRollbackError( f"double execution of {i.tool} across branches " f"{seen[key]} and {b.branch_id}" ) seen[key] = b.branch_id # Discard losers: stage-dropped intents are safe; dispatched reversible # intents must be compensated, never silently forgotten. for b in branches: if b is winner: continue for i in b.intents: if i.dispatched and i.tool_class is ToolClass.REVERSIBLE: _compensate(i) # invoke deterministic inverse elif i.dispatched and i.tool_class is ToolClass.IRREVERSIBLE: raise SpeculativeRollbackError( f"staging gate leaked: {i.tool} dispatched pre-merge" ) return winner def _compensate(intent: Intent) -> None: # Placeholder: dispatch the registered inverse for the tool. ... ```