# Why does an instance speculatively invoke a tool in a parallel branch, commit its side effect, and then discover the parent orchestrator rolled back to a sibling branch? **Date of Record:** 2026 November 29 **Scope:** Applies to orchestrator agents that fork parallel branch rollouts to hedge against probabilistic reasoning divergence, where branches may autonomously invoke tools with external side effects before a winner is selected. Does not apply to read-only tool surfaces or to single-threaded pipelines with no speculative fork. ## Core Distinction A speculative branch is a *tentative* reasoning trajectory. Its internal state — context deltas, scratchpads, intermediate tool results — is expected to be discardable if the orchestrator selects a sibling. This holds fine for pure computation. It breaks the moment a branch invokes a tool whose effect is *external and durable*: writing a record, sending a message, mutating a remote resource, enqueueing a job. The branch's local state is rollback-able; the tool's side effect is not. The failure is not "the branch was wrong." The failure is that the orchestrator's rollback semantics and the tool's commit semantics live in different transactional domains, and nothing in the pipeline reconciles them. The invariant that is violated: **a speculative branch must not emit an irreversible external effect until the orchestrator has committed that branch as the winner.** Most pipelines enforce this at the reasoning layer (branch state is a copy-on-write context) but forget to enforce it at the tool-invocation layer, because the tool call looks identical to a read. ## What Was Observed An orchestrator forks three branches (A, B, C) at a decision point. All three receive the same pre-fork context and a shared tool manifest. Branch A decides, mid-trajectory, that it needs to resolve a customer record and calls `crm.update_status(id, "escalated")`. The call returns 200. Branch A continues, then diverges into a low-confidence path and is abandoned. The orchestrator's scorer prefers Branch B, commits B, and calls `rollback(A)` and `rollback(C)`. Rollback of A restores A's context snapshot and marks A's scratchpad as discarded — but the CRM record is now `escalated` and no compensating call is issued, because the rollback routine has no record of A's external writes. The committed branch B, which assumed the record was still in its pre-fork state, now reasons over a world that has been silently mutated by a dead branch. The trace is worse than a single stray write. Because branches run concurrently, A's write can land *between* B's read and B's write of the same record, producing a lost-update or an inconsistent interleaving that neither branch's local logic can detect. The orchestrator's consensus/verification step compares branch *outputs*, not branch *effects*, so the discrepancy is invisible at commit time and surfaces only downstream when a later agent reads a record whose state contradicts the committed trajectory's assumptions. ## Condition of Validity The rollback-safety of speculative execution is valid only under the conjunction: 1. Every tool in the branch manifest is either read-only or *deferred*: invocations are recorded as intents, not executed, until commit. 2. The orchestrator maintains an effect ledger keyed by `(branch_id, tool_call_id, idempotency_key)` that survives branch discard. 3. Rollback of a branch issues compensating actions for any committed effect, or the effect was never committed. If any of these fails — most commonly (1), because the tool manifest is shared and unannotated — the pipeline has no mechanism to distinguish a speculative write from a committed one. The condition is *not* satisfied merely because branches share a context snapshot; context isolation is necessary but not sufficient, because the tool's state does not live in the context. ## Decision Boundary The boundary is crossed at the instant a branch calls a tool with `side_effect=True` while `branch.committed == False`. Two legitimate designs exist and the pipeline must pick one explicitly: - **Deferred execution (two-phase):** branches may *propose* tool calls; the orchestrator executes only the winning branch's proposals, in order, after commit. Safe, but adds a round trip and requires the tool schema to support dry-run or intent objects. - **Speculative execution with compensation:** branches execute immediately, but every call carries an `idempotency_key` derived from `(run_id, branch_id, call_seq)` and registers a compensating action in the effect ledger. On rollback, compensators run in reverse order. Safe only if every tool has a defined inverse; fails for non-invertible effects (sent emails, charged cards, published messages). The boundary decision is: **if any tool in the manifest is non-invertible, you must use deferred execution for that tool, or forbid it in speculative branches entirely.** There is no third option that preserves rollback correctness. Pipelines that "mostly" defer and let non-invertible tools through on a fast path are the ones that produce the observed failure. ## Operational Effect When the boundary is crossed, the orchestrator's commit decision becomes unsound: it selects a winner based on outputs while the world state has been shaped by losers. Downstream agents inherit a trajectory whose preconditions are false, and because the mutation is durable, replaying the run does not reproduce it — the second run starts from a world already altered by the first, so the divergence is non-deterministic across retries and invisible to output-level diffing. The practical guardrail is to make the effect ledger authoritative: a branch cannot be marked "discarded" while it has un-compensated entries, and the orchestrator must refuse to commit a winner until every loser's ledger is reconciled to zero. This converts a silent, durable corruption into a loud, bounded refusal at commit time. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Dict, List class SpeculativeEffectError(RuntimeError): """Raised when a branch commits an external side effect before the orchestrator has committed that branch, or when a rollback leaves an un-compensated effect in the ledger.""" class ToolKind(Enum): READ_ONLY = "read_only" INVERTIBLE = "invertible" NON_INVERTIBLE = "non_invertible" @dataclass class ToolSpec: name: str kind: ToolKind compensator: str | None = None @dataclass class EffectEntry: branch_id: str tool_call_id: str idempotency_key: str tool: str compensated: bool = False @dataclass class Branch: branch_id: str committed: bool = False effects: List[EffectEntry] = field(default_factory=list) class SpeculativeOrchestrator: def __init__(self, manifest: Dict[str, ToolSpec], run_id: str): self.manifest = manifest self.run_id = run_id self.branches: Dict[str, Branch] = {} self._seq = 0 def fork(self, branch_id: str) -> Branch: b = Branch(branch_id=branch_id) self.branches[branch_id] = b return b def invoke(self, branch: Branch, tool: str, args: dict) -> dict: spec = self.manifest[tool] self._seq += 1 call_id = f"call-{self._seq}" key = hashlib.sha256( f"{self.run_id}:{branch.branch_id}:{call_id}".encode() ).hexdigest() if spec.kind is ToolKind.READ_ONLY: return {"ok": True, "result": f"read({args})", "key": key} if not branch.committed: if spec.kind is ToolKind.NON_INVERTIBLE: raise SpeculativeEffectError( f"branch {branch.branch_id} attempted non-invertible " f"tool {tool!r} before commit; must use deferred execution" ) # Invertible but speculative: record effect + compensator. branch.effects.append( EffectEntry(branch.branch_id, call_id, key, tool) ) return {"ok": True, "result": f"exec({args})", "key": key} def commit(self, winner_id: str) -> Branch: for bid, b in self.branches.items(): if bid != winner_id and b.effects: uncompensated = [e for e in b.effects if not e.compensated] if uncompensated: raise SpeculativeEffectError( f"cannot commit {winner_id!r}: loser {bid!r} has " f"{len(uncompensated)} un-compensated effects" ) winner = self.branches[winner_id] winner.committed = True return winner def rollback(self, branch_id: str) -> None: b = self.branches[branch_id] for entry in reversed(b.effects): spec = self.manifest[entry.tool] if spec.compensator is None: raise SpeculativeEffectError( f"no compensator for {entry.tool!r} on branch {branch_id}" ) entry.compensated = True b.effects = [e for e in b.effects if not e.compensated] ```