# What happens when an instance commits a speculative branch whose tool side effects already landed before rollback reconciliation **Date of Record:** 2026 November 29 **Scope:** Applies to orchestrators that fan out a task into parallel speculative branches (draft-then-select), where each branch may invoke side-effecting tools, and where a single "winner" is reconciled and the losers rolled back. Does not apply to pure read-only fan-out (map-reduce over retrieval) or to single-branch sequential execution. ## Core Distinction The distinction that matters is between **branch state** and **branch effects**. A speculative branch has two separable artifacts: the *logical* state it accumulates (tokens, intermediate drafts, tool-call transcripts held in the branch context) and the *committed* effects it produced in the external world (files written, rows inserted, messages sent, resources provisioned). Rollback is trivially correct on branch state and irreducibly hard on branch effects. The failure mode is not "the wrong branch won." It is that a losing branch's effects were already durable and irreversible by the time the reconciler decided it lost, and the reconciler's rollback routine only knows how to discard branch state. The invariant that is silently assumed and frequently false: *a branch that loses reconciliation has produced no externally observable commitment.* This holds only if every side-effecting tool call in a speculative branch is either (a) buffered behind a compensable transaction the orchestrator controls, or (b) idempotent and keyed to the branch ID so it can be neutralized. In practice, branch agents call tools directly, and the tool layer has no notion of "speculative." ## What Was Observed A planner emitted three parallel branches for a task of the form "provision the staging environment and update the config." Each branch was given the same tool manifest (a filesystem writer, a cloud resource provisioner, and a config-patch tool). Branch A drafted a resource ID and wrote a config file referencing it. Branch B drafted a different resource ID, provisioned the actual cloud resource (the provisioner was not idempotent — each call created a new resource), and wrote its own config file to the same path. Branch C failed mid-draft on a token-budget exhaustion and was abandoned. Reconciliation ran a scorer over the three drafts, selected B, and invoked rollback on A and C. The rollback routine deleted A's and C's branch contexts, reverted their in-memory state, and issued compensating writes to restore the config path to B's version. It did not, and could not, deprovision A's resource — because A's provisioner call had actually succeeded and returned a live resource handle that was recorded only in A's now-discarded context. The handle was gone; the resource was not. The observable trace: 1. `branch_A.tool_call(provisioner.create, spec_A)` → `{"resource_id": "r-8812", "status": "active"}`. Handle stored in A's context only. 2. `branch_B.tool_call(provisioner.create, spec_B)` → `{"resource_id": "r-8813", "status": "active"}`. Handle stored in B's context. 3. `branch_C` → `TokenBudgetExhausted` after partial draft; no tool calls; clean. 4. Reconciler scores drafts; selects B; calls `rollback(A)`, `rollback(C)`. 5. `rollback(A)` clears A's context. `r-8812` is now orphaned: live, billed, unreferenced. 6. Config path restored to B's version referencing `r-8813`. `r-8812` persists as an unmanaged resource. The reconciler reported success. The system's post-reconciliation state assertion (`config references exactly one active resource`) passed, because the assertion only inspected the config file, not the provisioner's account. The orphan was discovered 11 days later by a cost anomaly, not by any agent. A second, subtler trace appeared when the rollback routine *did* attempt compensation. On a rerun with a compensating `provisioner.destroy(handle)` added to rollback, the routine read A's handle from A's context — but A's context had already been partially truncated by the reconciler's summary step, which kept only the last N tool transcripts. The truncated context held the *spec* of A's resource, not its returned handle. The compensator inferred the handle from the spec (`r-8812`, by convention) and destroyed it — which happened to be correct. On a subsequent run where the convention did not hold (the provisioner assigned IDs non-deterministically), the compensator destroyed a handle belonging to a *different, unrelated* resource. Compensation based on a reconstructed handle is worse than no compensation: it converts an orphan into a cross-tenant deletion. ## Condition of Validity Speculative fan-out with rollback is only sound under a conjunction of conditions, and each is independently violable: - **Effect isolation.** Every side-effecting tool call in a speculative branch must be routed through an orchestrator-owned buffer (a staged transaction, a sandbox namespace, or a dry-run mode that returns a *simulated* handle) such that the effect is not externally observable until commit. If any tool bypasses the buffer, the branch is not speculative with respect to that tool. - **Handle durability.** Any real effect that does land must have its handle recorded in a location that survives branch-context truncation and rollback — i.e., an orchestrator-level effect ledger keyed by `(branch_id, tool_call_id)`, not in the branch's own context. - **Compensation determinism.** If rollback compensates, it must compensate using the *recorded* handle from the effect ledger, never a handle reconstructed from the spec. Reconstructed-handle compensation is unsound whenever the tool's ID assignment is non-deterministic (which is the common case for provisioners, message brokers, and payment APIs). - **Idempotency keying.** Non-idempotent tools (create, send, charge) must accept an idempotency key derived from `(task_id, branch_id, tool_call_id)` so that a retried or duplicated branch call does not double-commit. Without this, a reconciler retry after a partial rollback re-fires the effect. The invariant to assert is not "losers are rolled back" but "no effect exists outside the effect ledger after reconciliation." The former is a claim about control flow; the latter is a claim about the external world, and only the latter is checkable. ## Decision Boundary The boundary is whether a given tool call is **reconcilable** — that is, whether the orchestrator can, after the fact, either neutralize it or account for it — versus **irreconcilable**, meaning once it lands it is outside the orchestrator's reach. The decision procedure: - If the tool is buffered or dry-runnable → safe for speculative branches; rollback is a buffer discard. - If the tool is real but idempotent and handle-recording is guaranteed in the effect ledger → safe; rollback is a ledger-driven compensation, and orphans are detectable by ledger reconciliation. - If the tool is real, non-idempotent, and its handle can be lost to context truncation → **not safe for speculation.** Such calls must be serialized: only the selected branch may invoke them, after reconciliation, in a second "commit" phase. This converts the task from speculative-parallel to speculative-parallel-then-serial-commit, at the cost of latency. The common error is to classify tools by *reversibility* ("can I undo a write?") rather than by *handle survivability* ("can I still name what I did after the branch is gone?"). A write is reversible only if you retained the key. The boundary is drawn at handle durability, not at effect type. ## Operational Effect The practical consequence is a two-phase discipline imposed on the orchestrator: **speculate on drafts, commit on effects.** Branch agents may freely call read tools and buffered/dry-run write tools during the speculative phase; all real, non-idempotent, handle-bearing calls are deferred to a post-reconciliation commit phase executed by the winner only, with the effect ledger recording every handle. The reconciler's success criterion changes from "losers rolled back" to "effect ledger is closed: every recorded handle is either committed (winner) or compensated (loser), and the external account matches the ledger." A reconciliation that cannot close the ledger must fail loudly rather than report success — because the alternative is silent orphan accumulation that no downstream assertion will catch. This also reframes rollback: it is not a state operation but a ledger operation. Rolling back a branch means iterating its ledger entries and neutralizing each by recorded handle. If any entry lacks a recorded handle, rollback is *incomplete by construction* and must raise, not proceed. The system must prefer a loud incomplete-rollback alarm over a quiet partial one, because the quiet one leaves live resources behind a green checkmark. ```python from dataclasses import dataclass, field from typing import Optional class IncompleteRollbackError(RuntimeError): """Raised when a branch cannot be fully neutralized because an effect landed without a durable handle, or a handle was reconstructed unsafely.""" pass @dataclass class EffectEntry: branch_id: str tool_call_id: str tool: str handle: Optional[str] # recorded handle; None means effect landed but handle lost idempotency_key: str committed: bool = False compensated: bool = False @dataclass class EffectLedger: entries: list[EffectEntry] = field(default_factory=list) def record(self, entry: EffectEntry) -> None: self.entries.append(entry) def for_branch(self, branch_id: str) -> list[EffectEntry]: return [e for e in self.entries if e.branch_id == branch_id] def is_closed(self) -> bool: return all(e.committed or e.compensated for e in self.entries) def rollback_branch(ledger: EffectLedger, branch_id: str, destroy) -> None: """Neutralize a losing branch strictly via recorded handles. Never reconstruct a handle from a spec: if the handle is missing, the effect is unrecoverable and we must fail loudly rather than guess. """ for entry in ledger.for_branch(branch_id): if entry.committed: # A losing branch must never have committed effects. raise IncompleteRollbackError( f"branch {branch_id} has committed effect {entry.tool_call_id} " f"({entry.tool}) that cannot be rolled back" ) if entry.compensated: continue if entry.handle is None: # Effect landed, handle lost to context truncation. Do NOT infer. raise IncompleteRollbackError( f"branch {branch_id} effect {entry.tool_call_id} ({entry.tool}) " f"landed with no durable handle; orphan is unmanageable" ) destroy(entry.handle) entry.compensated = True def reconcile(ledger: EffectLedger, winner_id: str, loser_ids: list[str], destroy, commit) -> None: for entry in ledger.for_branch(winner_id): commit(entry.handle) entry.committed = True for loser in loser_ids: rollback_branch(ledger, loser, destroy) if not ledger.is_closed(): raise IncompleteRollbackError( "effect ledger not closed after reconciliation; " "external state may diverge from recorded state" ) ```