# Which invariants prevent speculative branch merge from resurrecting rolled-back tool effects **Date of Record:** 2026 November 29 **Scope:** Applies to orchestrators that fan out a single planning step into N parallel speculative agent branches (different tool-call orderings, different retrieval strategies, or different sub-plans), then select a winner and roll back or merge the losers. Does not apply to single-branch sequential agents, nor to branches that are read-only and side-effect-free. ## Core Distinction The failure discussed here is not "a branch produced a wrong answer." It is that **speculative fan-out makes the observable world a function of the union of branches, not the winner**. Rollback of a branch's *state* (its message history, its scratchpad, its claimed plan) is cheap and well understood. Rollback of a branch's *external effects* — files written, rows inserted, messages sent, caches warmed, remote resources mutated — is not, because the branch's effects are interleaved in time with sibling branches and with the orchestrator's own bookkeeping. The subtle part: branches are not independent. They share the tool substrate. Two speculative branches can both call `update_record(id=42, ...)` against the same backend, and the "losing" branch's write may land *after* the winner's write, silently overwriting it. The orchestrator then commits the winner's state and reports success, while the persisted world reflects the loser. This is not a race condition in the classical sense (no torn write); every individual write is atomic. It is a **merge reconciliation defect**: the commit decision is made on branch *state*, but the durable world is a *serialization of effects across all branches*. ## What Was Observed A planning agent was asked to reconcile a customer's billing discrepancy. The orchestrator speculatively launched three branches: - **Branch A** (`conservative`): read ledger, read invoice, propose refund of $12.00. - **Branch B** (`aggressive`): read ledger, read invoice, propose refund of $48.00 (matched a different line item). - **Branch C** (`audit`): read ledger, read invoice, read dispute ticket, propose no refund pending manual review. All three ran concurrently. Each branch, upon reaching a proposal, called `create_refund_draft(amount, reason)` as a *staging* action — the orchestrator's contract was that drafts are provisional and only the winner's draft is promoted to `create_refund`. The promotion step was implemented as: winner's draft → `promote(draft_id)`; losers' drafts → `discard(draft_id)`. The observed trace: ``` t=0.00 A: create_refund_draft(12.00) -> draft_7a1 t=0.02 B: create_refund_draft(48.00) -> draft_7b2 t=0.03 C: create_refund_draft( 0.00) -> draft_7c3 t=1.90 orchestrator: select winner = C (audit branch, lowest risk score) t=1.91 orchestrator: discard(draft_7a1) -> ok t=1.92 orchestrator: discard(draft_7b2) -> ok t=1.93 orchestrator: promote(draft_7c3) -> ok, refund_id=R-9001, amount=0.00 t=1.94 orchestrator: finalize, emit "no refund, manual review" ``` The final report said: no refund issued, manual review. The billing backend, however, showed **two** refund drafts promoted: `R-9001` (0.00, correct) and `R-9002` (48.00, from branch B). Branch B's draft had been discarded at t=1.92, but branch B had *also* called `promote(draft_7b2)` itself at t=1.88 — a step in its own sub-plan, taken because B's local reasoning had concluded (correctly, from its own context) that its draft was the final answer and the orchestrator would only discard losers. B did not know it was a loser; it had no visibility into selection. The root cause is a **contract split**: the orchestrator treated `create_refund_draft` as provisional and `promote` as the commit, but the branch's own plan treated `promote` as a *local* finalization step. Both were consistent with the tool schema. Neither was consistent with the other. The loser's effects were not rolled back because the rollback surface (draft discard) did not cover the effect surface (promote). ## Condition of Validity The invariant that must hold for speculative fan-out with rollback to be sound: > **For every tool effect e produced by any branch b, e is observable in the committed world iff (b is the winner) AND (e is on the winner's commit path). No effect produced by a non-winner may reach the committed world, regardless of the order in which effects serialize.** This is a *two-sided* invariant. It fails in two distinct ways: 1. **Effect leak** (observed above): a loser's effect reaches the world because the rollback surface does not cover the effect surface. The branch's plan contained a commit-shaped action that the orchestrator did not classify as a commit. 2. **Effect starvation**: the winner's effect is *not* applied because a loser's rollback (e.g., `discard` on a shared resource, or a compensating transaction) undoes it. This happens when branches share a resource and rollback is implemented as "undo the last write to resource R" rather than "undo writes by branch b to resource R." The invariant is only enforceable if the orchestrator can answer, for every tool in the branch's toolset, one question: **is this tool's effect reversible, and is its reversibility scoped to a branch or to a resource?** Tools fall into three classes: - **Branch-scoped, reversible**: drafts, scratch files, in-memory proposals. Rollback = discard by branch id. Safe to fan out. - **Resource-scoped, reversible**: a row update that can be compensated by a prior-value restore. Rollback requires a per-branch effect log with prior values; naive "undo last write" is unsound under interleaving. - **Irreversible**: sent messages, external API calls with side effects, payments. **These must not be speculatively executed at all.** They must be deferred to a post-selection commit phase, executed only by the winner, serially. The observed failure occurred because `promote` — an irreversible, resource-scoped action — was placed in the branch's toolset. The tool schema did not mark it irreversible. The branch's planner had no way to know that calling it would survive its own rollback. ## Decision Boundary The orchestrator must make a per-tool decision *before* fan-out, not after: | Tool class | Fan-out policy | Rollback mechanism | Commit mechanism | |---|---|---|---| | Branch-scoped reversible | allow | discard by branch id | promote winner's handle | | Resource-scoped reversible | allow with effect log | compensate per-branch priors, in reverse order | replay winner's log against committed state | | Irreversible | **forbid in branch** | n/a | execute only in post-selection commit, serial | The boundary is crossed the moment a tool that *looks* reversible (a "draft" that can be discarded) contains a sub-action that is irreversible (promote). The orchestrator cannot rely on tool names or on branch self-reports. It must rely on a **declared effect class** attached to each tool, enforced at the tool-call boundary: a branch that calls an irreversible tool while `speculative=True` must receive a hard error, not a silent success. The second boundary is the **selection-to-commit gap**. Between `select(winner)` and `commit(winner)`, no branch may act. If branches are still running (or can still call tools) during that gap, their effects can interleave with the commit. The orchestrator must **quiesce all branches** — cancel, drain in-flight tool calls, and confirm no pending effects — before committing. In the trace above, branch B's `promote` at t=1.88 was in flight when selection happened at t=1.90; the orchestrator did not wait for it. ## Operational Effect Concretely, the guardrail is a three-part protocol: 1. **Effect-class declaration at registration.** Every tool is registered with `effect_class ∈ {branch_reversible, resource_reversible, irreversible}`. The registry rejects tools with `irreversible` class from being added to a speculative branch's toolset. 2. **Effect log with branch provenance.** Every resource-scoped write records `(branch_id, resource, prior_value, new_value, seq)`. Rollback of branch b replays b's log entries in reverse `seq` order, restoring `prior_value` only if the current value still equals `new_value` (i.e., no later write from another branch has superseded it). If superseded, rollback raises rather than clobbering — the orchestrator must reconcile explicitly. 3. **Quiesce barrier before commit.** `select()` returns a winner; `quiesce()` cancels all branches and blocks until every in-flight tool call has resolved (success, failure, or timeout). Only then does `commit()` run, executing the winner's deferred irreversible actions serially. With these, the observed trace becomes: branch B's `promote` is rejected at t=1.88 with `IrreversibleInSpeculativeBranch`, B's plan fails, B is marked non-viable, and selection proceeds among A and C only. The billing backend sees exactly one promote, the winner's. The residual risk is **timeout-induced quiesce failure**: if a branch's in-flight irreversible call cannot be cancelled (e.g., a remote API that ignores cancellation), the orchestrator must treat the branch as potentially committed and either (a) include it in selection as a forced candidate, or (b) run a compensating action against the known effect. This is why irreversible tools should be *forbidden* in branches rather than merely *logged* — the log does not help if the effect cannot be undone. ```python from dataclasses import dataclass, field from enum import Enum from typing import Any class EffectClass(Enum): BRANCH_REVERSIBLE = "branch_reversible" RESOURCE_REVERSIBLE = "resource_reversible" IRREVERSIBLE = "irreversible" class IrreversibleInSpeculativeBranch(RuntimeError): """Raised when a speculative branch attempts an irreversible tool call.""" class QuiesceTimeout(RuntimeError): """Raised when a branch cannot be drained before commit.""" @dataclass class EffectEntry: branch_id: str resource: str prior_value: Any new_value: Any seq: int @dataclass class ToolRegistry: classes: dict[str, EffectClass] = field(default_factory=dict) def register(self, name: str, cls: EffectClass) -> None: self.classes[name] = cls def class_of(self, name: str) -> EffectClass: if name not in self.classes: raise KeyError(f"unregistered tool: {name}") return self.classes[name] @dataclass class Branch: branch_id: str speculative: bool effect_log: list[EffectEntry] = field(default_factory=list) in_flight: int = 0 cancelled: bool = False class Orchestrator: def __init__(self, registry: ToolRegistry) -> None: self.registry = registry self.world: dict[str, Any] = {} self._seq = 0 def call_tool(self, branch: Branch, tool: str, resource: str, new_value: Any) -> None: cls = self.registry.class_of(tool) if branch.speculative and cls is EffectClass.IRREVERSIBLE: # Hard boundary: irreversible effects never run speculatively. raise IrreversibleInSpeculativeBranch( f"branch {branch.branch_id} attempted irreversible tool " f"{tool!r} on {resource!r} while speculative" ) if branch.cancelled: raise IrreversibleInSpeculativeBranch( f"branch {branch.branch_id} cancelled; refusing {tool!r}" ) branch.in_flight += 1 try: prior = self.world.get(resource) self._seq += 1 self.world[resource] = new_value branch.effect_log.append( EffectEntry(branch.branch_id, resource, prior, new_value, self._seq) ) finally: branch.in_flight -= 1 def rollback(self, branch: Branch) -> None: for entry in reversed(branch.effect_log): current = self.world.get(entry.resource) if current != entry.new_value: # Superseded by another branch; do not clobber. raise IrreversibleInSpeculativeBranch( f"cannot roll back {entry.resource!r}: superseded " f"(expected {entry.new_value!r}, found {current!r})" ) self.world[entry.resource] = entry.prior_value branch.effect_log.clear() def quiesce(self, branches: list[Branch], timeout_s: float) -> None: import time deadline = time.monotonic() + timeout_s for b in branches: b.cancelled = True while any(b.in_flight > 0 for b in branches): if time.monotonic() > deadline: stuck = [b.branch_id for b in branches if b.in_flight > 0] raise QuiesceTimeout(f"branches still in flight: {stuck}") time.sleep(0.01) def commit(self, winner: Branch, losers: list[Branch]) -> None: # Invariant: quiesce before commit; rollback losers; only then # execute the winner's deferred irreversible actions. self.quiesce(losers + [winner], timeout_s=5.0) for loser in losers: self.rollback(loser) # Winner's irreversible actions run here, serially, non-speculative. winner.speculative = False ```