# How should an instance reconcile speculative tool-call side effects when a branch-and-merge task graph rolls back a sibling branch **Date of Record:** 2026 November 24 **Scope:** Applies to orchestrators that fan out a task graph into speculative branches (parallel agent instances executing candidate sub-plans), merge the winning branches, and discard losers by rollback. Does not apply to strictly sequential single-agent loops or to fan-out where branches are read-only and side-effect-free. ## Core Distinction The distinction that matters is between *logical rollback* and *physical rollback of tool effects*. A branch-and-merge scheduler can trivially discard a losing branch's message history, scratchpad, and intermediate state — these live inside the agent's context and are garbage-collected on merge. What it cannot trivially discard are the **externalized side effects** the losing branch already committed through tool calls: a file written, a row inserted, a message sent, a payment authorized, a remote resource provisioned. The non-obvious failure is this: a speculative branch is *probabilistically* likely to be discarded, but it executes tool calls with the same authority and immediacy as the branch that will win. When the merge selects a winner, the scheduler rolls back the loser's *state* — and silently leaves the loser's *effects* in place. The merged result is then a hybrid: the winner's reasoning layered on top of a world that contains the loser's mutations. This is not a crash. It is a **silent reconciliation gap**, and it is the dominant failure mode of speculative execution in agent systems that was never a problem in speculative execution in CPUs, because CPUs have a write buffer and agents do not. ## What Was Observed A three-branch speculative plan for a provisioning task. The root agent decomposes "prepare and deploy config" into three candidate sub-plans that differ in how they resolve a dependency version. Branch A and Branch B both call a `write_config` tool early — a "commit the candidate config to the staging path" step that each branch treats as a local scratch operation but which is, at the tool layer, a real filesystem write to a shared path. Branch C is read-only and wins the merge on a scoring heuristic. The scheduler's rollback routine for A and B does the following, in order: (1) drop the branch's message list, (2) release its token budget reservation, (3) mark its task-graph node `ROLLED_BACK`. It does **not** call `write_config` with an inverse, because the tool has no declared inverse, and the scheduler has no record that the tool was ever called — the tool-call log lives inside the branch's now-dropped message list. After merge, the winner (C) proceeds to a `deploy` step that reads the staging path. It reads Branch B's config, not its own — because B wrote last, and C never wrote at all. The deployed artifact is a config that no surviving branch ever reasoned about. The trace shows a clean merge: all nodes `MERGED` or `ROLLED_BACK`, no errors, exit code 0. The corruption is invisible in the graph and visible only in the deployed bytes. A second observation from the same incident: the reconciliation is not merely missing, it is *order-dependent and non-deterministic*. When branches A and B raced on the same path, whichever `write_config` returned last won the file. Re-running the identical graph produced a different deployed config on 3 of 10 runs, because branch completion order varies with tool latency. The merge is deterministic in its scoring but non-deterministic in its world-state outcome. ## Condition of Validity The invariant that must hold for speculative branch-and-merge to be safe is: > **A branch may externalize a side effect only if that side effect is (a) recorded in a scheduler-owned reconciliation ledger keyed by branch ID, and (b) either idempotent under replay or accompanied by a declared inverse operation the scheduler can invoke on rollback.** This condition is *valid* — meaning the failure does not occur — only when one of the following holds: 1. **Effect isolation:** every speculative branch executes against a private, copy-on-write overlay of external state (a sandboxed filesystem view, a transactional DB session, a mock tool transport), and the overlay is committed only on merge. The branch's `write_config` writes to `/staging/branch-B/...`, never to the shared path. 2. **Deferred commit:** tool calls with external effects are *staged* by the scheduler, not executed by the branch. The branch emits an intent; the scheduler executes intents only for the winning branch after merge. This requires the tool schema to distinguish `effect: pure` from `effect: external` and the scheduler to honor it. 3. **Ledgered inverses:** every external effect is logged to a scheduler-owned ledger at call time with a branch key, and each effectful tool declares an inverse. Rollback replays the inverse for the discarded branch's ledger entries in reverse order. The condition is *invalid* — the failure is live — whenever a branch can reach a real external effect through a tool whose effect class is undeclared, and the scheduler's rollback path touches only branch-local state. In practice this is the default configuration of most agent frameworks: tools are opaque functions, side-effect class is undocumented, and rollback means "forget the branch." ## Decision Boundary The boundary the operator must decide is **where the effect boundary sits relative to the speculation boundary**. Three regimes, with a hard line between the first two and the third: - **Effect boundary inside speculation boundary (safe):** branches are sandboxed; effects are provisional until merge. Choose this when tools are effectful and inverses are unavailable. Cost: you must run a sandboxed tool transport, and any tool that cannot be sandboxed (a live payment API, an outbound email) must be *blocked* in speculative branches — not merely discouraged. - **Effect boundary coincident with merge (safe):** branches are pure; the scheduler executes staged intents after merge. Choose this when you can modify tool schemas to carry effect class and intent staging. Cost: added latency of a two-phase execute, and the winner's plan must be expressible as intents, which fails for tools whose outputs feed the branch's reasoning (the branch needs the write's return value to continue). - **Effect boundary outside speculation boundary (unsafe, common):** branches call real tools directly; rollback forgets state but not effects. This is the default and it is the failure. The decision boundary is *not* "should I use speculative execution" — it is "have I declared the effect class of every tool reachable from a speculative branch, and does my rollback path consult that declaration." If the answer is no for even one tool, the merge is not a merge; it is a race whose loser's writes survive. The sharp edge: the boundary is per-tool, not per-graph. A single undeclared effectful tool reachable from any speculative branch invalidates the safety of the entire graph, because the reconciliation gap is silent and the corruption propagates through the merge into the winner's downstream reads. ## Operational Effect The operational consequence is that **merge correctness must be verified against world-state, not against graph-state.** A graph that reports all nodes `MERGED`/`ROLLED_BACK` with zero errors is not evidence of a correct merge when speculative branches can externalize effects. The verification must diff the external world against the pre-fan-out snapshot and attribute every delta to a surviving branch. Any delta attributable to a rolled-back branch is a reconciliation gap. Concretely, the guardrail is a **pre-merge effect audit**: before the scheduler commits the merge, it enumerates the reconciliation ledger, filters entries whose branch is not a winner, and for each such entry either (a) confirms the effect was sandboxed and never reached the shared world, (b) applies the declared inverse, or (c) halts the merge and surfaces the orphaned effect to the operator. The audit must run *before* the winner's downstream steps execute, because once the winner reads a loser's write, the corruption is baked into the winner's reasoning and cannot be cleanly attributed. The failure also has a non-determinism cost that compounds: because branch completion order varies, the same graph produces different world-states across runs, which defeats replay-based verification. The ledger must therefore record effects with a deterministic branch ordering key, not wall-clock order, so that replay produces the same reconciliation decision. The code below encodes the audit as a hard gate. It refuses to merge when a rolled-back branch has an un-reconciled external effect, and it refuses to treat an undeclared-effect tool as safe. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class EffectClass(Enum): PURE = "pure" # no external effect; safe to speculate SANDBOXED = "sandboxed" # external but isolated per branch; committed on merge EXTERNAL = "external" # real shared-world mutation; needs inverse or staging class ReconciliationGap(RuntimeError): """Raised when a rolled-back branch left an un-reconciled external effect.""" pass @dataclass class ToolDecl: name: str effect: EffectClass inverse: Optional[str] = None # name of inverse tool, if any @dataclass class LedgerEntry: branch_id: str tool: str effect: EffectClass inverse_applied: bool = False @dataclass class Branch: branch_id: str is_winner: bool = False @dataclass class MergeGate: tools: dict[str, ToolDecl] ledger: list[LedgerEntry] = field(default_factory=list) def record(self, branch_id: str, tool_name: str) -> None: decl = self.tools.get(tool_name) if decl is None: # An undeclared tool reachable from a speculative branch is itself # a violation: its effect class is unknown, so it cannot be assumed safe. raise ReconciliationGap( f"tool {tool_name!r} has no declared effect class; " f"cannot speculate branch {branch_id!r} through it" ) self.ledger.append(LedgerEntry(branch_id, tool_name, decl.effect)) def apply_inverse(self, entry: LedgerEntry) -> None: decl = self.tools[entry.tool] if decl.inverse is None: raise ReconciliationGap( f"branch {entry.branch_id!r} externalized {entry.tool!r} " f"with no declared inverse; effect cannot be rolled back" ) # In a real system: invoke decl.inverse against the shared world here. entry.inverse_applied = True def audit_before_merge(self, branches: list[Branch]) -> None: winners = {b.branch_id for b in branches if b.is_winner} for entry in self.ledger: if entry.branch_id in winners: continue if entry.effect is EffectClass.PURE: continue if entry.effect is EffectClass.SANDBOXED: # Sandboxed effects never reached the shared world; dropping # the overlay is the rollback. Nothing to reconcile. continue if entry.effect is EffectClass.EXTERNAL: if not entry.inverse_applied: self.apply_inverse(entry) if not entry.inverse_applied: raise ReconciliationGap( f"orphaned external effect from rolled-back branch " f"{entry.branch_id!r}: tool {entry.tool!r} not reconciled; " f"refusing merge" ) # Only now may the scheduler commit the merge and run winner downstream steps. def run_merge(gate: MergeGate, branches: list[Branch]) -> None: gate.audit_before_merge(branches) # ... commit winner state, execute staged intents, proceed downstream ... ```