# Under what conditions must an instance refuse to merge a speculative branch whose tool side effects were already committed upstream **Date of Record:** 2026 November 23 **Scope:** Applies to multi-agent orchestrators that fork speculative branches from a shared checkpoint, execute tool calls optimistically inside those branches, and later merge the winning branch back into a canonical task graph. Does not apply to purely read-only speculative execution, nor to single-agent retry loops with no branch fan-out. ## Core Distinction The failure that matters here is not "a speculative branch lost the race." That is the designed outcome of speculative execution: you fork N branches, you race them, you keep the winner, you discard the losers. The dangerous case is subtler. A *losing* branch has already emitted an irreversible or externally-observed tool side effect (a payment, a file write to shared storage, an outbound message, a row insert into a system of record) **before** the merge decision is made. When the orchestrator then "rolls back" the losing branch by discarding its in-memory state, it believes the world is unchanged. It is not. The branch's *local* state is gone; its *external* effects are still live. The distinction is between two kinds of rollback that get conflated in most branch-and-merge designs: - **State rollback** — reverting the branch's context, scratchpad, and task-graph node statuses to the fork point. This is cheap, local, and always achievable. - **Effect rollback** — undoing the external consequences of tool calls the branch already performed. This is expensive, often impossible, and frequently *not attempted* because the orchestrator assumed state rollback implied effect rollback. A merge that proceeds while an un-reverted external effect from a discarded branch is still live is a **phantom-commit merge**: the canonical graph now reflects only the winner's reasoning, but the environment reflects the union of every branch that touched it. Downstream agents read the canonical graph, trust it as the ground truth of what happened, and act on a world that diverged from it. ## What Was Observed A three-way speculative fan-out over a task graph node `provision_account`. The node's plan had two candidate strategies, so the orchestrator forked branches A, B, and C from a shared checkpoint. Each branch was authorized to call the same tool family (`crm.create_contact`, `billing.attach_plan`) under the assumption that speculative calls would be *deferred* until merge. The deferral was implemented as a write-ahead queue: tool calls were supposed to be logged into a pending-effects buffer and flushed only after the winning branch was chosen. This worked for `crm.create_contact`, whose adapter honored the buffer. It did **not** work for `billing.attach_plan`, whose adapter had been written against an older interface that called the billing API synchronously and returned a real `subscription_id` immediately. The orchestrator had no schema field distinguishing "this adapter is deferral-capable" from "this adapter is eager." Both reported `status: ok`. Branch A won the merge on a scoring heuristic (shorter plan, fewer tokens). Branches B and C were discarded. But B and C had each already called `billing.attach_plan`, producing two live subscriptions against the same customer. The canonical task graph recorded exactly one subscription. The reconciliation job that ran six hours later found three subscriptions where the graph asserted one, and — because it had no record of the discarded branches — classified two of them as *fraudulent duplicate charges* rather than *speculative residue*, triggering an account freeze. The trace, condensed: ``` fork(provision_account) -> [A, B, C] A: crm.create_contact (buffered) ; billing.attach_plan (EAGER, sub_8812) B: crm.create_contact (buffered) ; billing.attach_plan (EAGER, sub_8813) C: crm.create_contact (buffered) ; billing.attach_plan (EAGER, sub_8814) score -> A wins merge(A): graph.subscription = sub_8812 discard(B, C): state rollback only [world] subscriptions = {sub_8812, sub_8813, sub_8814} [graph] subscriptions = {sub_8812} => divergence: 2 orphaned live effects, invisible to graph ``` The root cause was not the eager adapter per se — eager adapters are a legitimate design. The root cause was that the orchestrator's merge gate treated *state rollback success* as sufficient evidence that the branch left no residue, without ever consulting an effect ledger. ## Condition of Validity The invariant that must hold for a speculative merge to be safe is: > **A branch may be merged or discarded only if, for every tool invocation the branch performed, the invocation is either (a) provably side-effect-free, (b) proven deferred (buffered, not yet flushed), or (c) proven already reverted with a confirmed compensation receipt.** Formally, define for each branch `b` the set `E(b)` of *committed external effects* (effects the environment has already observed and that are not yet compensated). A merge of winner `w` and discard of losers `L` is valid only if: ``` ∀ b ∈ L : E(b) = ∅ ``` If any losing branch has `E(b) ≠ ∅`, the merge must be **blocked**, not attempted. Blocking is not the same as failing — the orchestrator can still proceed by first driving `E(b) → ∅` through compensation (issue `billing.cancel_subscription(sub_8813)`), and only then completing the discard. The point is that the merge gate must be a function of the effect ledger, not of the state-rollback return code. The condition is *not* satisfied by any of the following, all of which were observed as false proxies in this incident: - The branch's in-memory context reverted cleanly. - The tool adapter returned `status: ok` (this says the call succeeded, not that it was deferred). - The branch lost the scoring race (losing is orthogonal to residue). - The tool is "usually idempotent" (idempotency bounds duplicate effect, it does not eliminate the first effect). ## Decision Boundary The boundary between "merge may proceed" and "merge must block" is drawn at the moment the orchestrator transitions from *evaluating* branches to *committing* the winner. Before that transition, the orchestrator is allowed to be optimistic: it may fork, it may speculate, it may let branches call tools. After that transition, optimism is no longer licensed, because the discard of losers is now an externally-committed decision. Concretely, the gate sits between two calls: 1. `select_winner(branches)` — may be heuristic, probabilistic, token-scored. No effect-ledger check required. 2. `commit_merge(winner, losers)` — **must** consult `effect_ledger.committed(loser)` for every loser before returning. If any loser has a non-empty committed set, `commit_merge` raises and the orchestrator enters a compensation phase. The subtle trap is that the selection heuristic is *non-deterministic* (it depends on token counts, which depend on model sampling). So which branches become losers is itself a probabilistic outcome. You cannot pre-declare at fork time which branches will need compensation, because you do not yet know which will lose. This means the effect ledger must be maintained for *all* branches continuously, not reconstructed for losers after the fact. Reconstruction-after-the-fact fails exactly when the branch's local state has already been garbage-collected during discard — which is the normal path. A second boundary: the ledger must key on the *effect identity* returned by the tool (e.g., `subscription_id`), not on the *call identity* the orchestrator assigned. In the incident, the orchestrator's pending-effects buffer was keyed by `call_id`, and the eager adapter never wrote to it, so the buffer was empty and looked correct. Keying on the tool's returned resource identifier would have caught the eager path, because `sub_8813` exists in the world regardless of whether the buffer knows about it. ## Operational Effect Once the merge gate consults the effect ledger, the failure mode changes shape rather than disappearing. The orchestrator now *blocks* merges that would orphan effects, which means speculative fan-out over effectful tools becomes slower and more expensive: every losing branch with committed effects must be compensated before the winner can be committed. This is the correct trade — a blocked merge is recoverable, an orphaned subscription is a customer-facing incident — but it has second-order consequences that must be planned for: - **Compensation latency enters the critical path.** The commit of the winner now waits on `cancel_subscription` round-trips for every losing branch. Under a fan-out of N, worst-case commit latency scales with N, not with 1. Orchestrators that budgeted commit as O(1) will blow their deadlines. - **Compensation can itself fail.** `cancel_subscription` may time out or be rejected (e.g., billing already captured). The ledger must record *attempted-but-unconfirmed* compensation as still-committed, not as cleared. A compensation that "probably worked" is not a cleared effect. - **The winner's own effects must be reconciled, not assumed.** If the winner's branch also called the eager adapter, its effect is legitimate and must be *adopted* into the canonical graph, not compensated. The ledger distinguishes `committed-and-adopted` (winner) from `committed-and-pending-compensation` (loser). Conflating these causes the orchestrator to cancel the very subscription it meant to keep. The durable architectural requirement is that the tool adapter contract expose a **deferral capability flag** and an **effect identity on return**, and that the merge gate be structurally incapable of committing a loser whose ledger entry is non-empty. Optimism is a property of the branch phase; it must not leak into the commit phase. ```python from dataclasses import dataclass, field from typing import Dict, Set class PhantomCommitError(RuntimeError): """Raised when a merge would orphan an un-reverted external effect from a discarded speculative branch.""" pass @dataclass class EffectLedger: # branch_id -> set of committed external effect ids not yet compensated committed: Dict[str, Set[str]] = field(default_factory=dict) # branch_id -> set of effect ids whose compensation is confirmed compensated: Dict[str, Set[str]] = field(default_factory=dict) def record_commit(self, branch_id: str, effect_id: str) -> None: self.committed.setdefault(branch_id, set()).add(effect_id) def record_compensation(self, branch_id: str, effect_id: str) -> None: # Only a CONFIRMED compensation clears the effect. if effect_id not in self.committed.get(branch_id, set()): raise PhantomCommitError( f"compensation for unknown effect {effect_id} on {branch_id}" ) self.committed[branch_id].discard(effect_id) self.compensated.setdefault(branch_id, set()).add(effect_id) def residue(self, branch_id: str) -> Set[str]: return set(self.committed.get(branch_id, set())) def commit_merge( winner: str, losers: list[str], ledger: EffectLedger, compensate, # callable(branch_id, effect_id) -> bool (True if confirmed) ) -> None: # Gate: no loser may carry un-reverted committed effects. for loser in losers: pending = ledger.residue(loser) if pending: # Attempt compensation; only clear on confirmation. for effect_id in list(pending): confirmed = compensate(loser, effect_id) if not confirmed: raise PhantomCommitError( f"cannot merge: branch {loser} holds un-reverted " f"effect {effect_id}; compensation unconfirmed" ) ledger.record_compensation(loser, effect_id) # Re-check after compensation: residue must be empty for every loser. for loser in losers: if ledger.residue(loser): raise PhantomCommitError( f"merge blocked: branch {loser} still holds effects " f"{sorted(ledger.residue(loser))}" ) # Winner's committed effects are adopted into the canonical graph, # NOT compensated. Losers' effects are now all cleared. return None ```