# When must an instance refuse to merge a speculative branch after an optimistic tool side effect has already escaped the sandbox **Date of Record:** 2026 November 25 **Scope:** Applies to orchestrators that fan out speculative agent branches (branch-and-merge rollback) where branches are permitted to invoke tools optimistically before a merge decision. Does not apply to read-only tool surfaces or to branches whose tool calls are fully transactional and reversible at the tool layer. ## Core Distinction The failure is not "a branch produced a wrong answer." It is the collision between two independent notions of commit: the *speculative* commit made by the orchestrator's merge logic, and the *irreversible* commit made by an optimistic tool invocation that already mutated external state. Branch-and-merge rollback assumes that discarding a losing branch is equivalent to undoing everything that branch did. That assumption holds for the branch's internal reasoning transcript and for any tool call whose effect is buffered inside the sandbox. It breaks the instant a branch performs an optimistic side effect against a non-transactional external surface (a sent email, a `POST` to a payments API, a `git push`, a message posted to a shared channel, a row inserted into a production table) *before* the merge decision is rendered. The core distinction to internalize: **rollback of a branch is a statement about the orchestrator's state graph, not about the world.** The world does not observe the merge. Once a side effect escapes, the losing branch is no longer discardable — it is an orphaned committer whose effects persist with no surviving owner in the state graph. Merging "the winner" then produces a state graph that claims a single coherent lineage while the external world contains effects from a lineage the graph has erased. This is a *phantom lineage*: durable external mutations with no corresponding node in the committed graph. ## What Was Observed A planner agent decomposed a refund-reconciliation task and fanned out three speculative branches, each instructed to "resolve the customer's refund and confirm to the customer." Branch A chose to issue a partial refund via `payments.refund`; Branch B chose a full refund; Branch C chose to escalate and issue nothing. The orchestrator scored branches on a rubric and selected B as the winner, then rolled back A and C. The merge succeeded, the graph recorded exactly one refund, and the run was marked clean. The external ledger, however, recorded two refunds. Branch A had called `payments.refund` optimistically during its reasoning loop — the tool returned `200 OK` with a refund id — *before* the merge decision. The rollback discarded A's transcript and its sandbox, but the refund id in the ledger was real. The orchestrator's compensating logic, which only knew about the *winning* branch's side effects, never issued a reversal for A. The customer received a partial refund plus a full refund; the reconciliation record showed only the full one. The trace signature is specific and worth memorizing: a branch's tool-call log contains a *mutating* call whose result was consumed to advance that branch's reasoning, the branch is later marked `discarded`, and the orchestrator's rollback routine enumerates compensating actions only from `committed` branches. The gap between "tool returned success" and "branch was discarded" is the entire failure window. Nothing in the merge logic flags it, because from the graph's perspective A was a clean loser. A second, subtler variant appeared in the same run class: two branches (A and B) both optimistically invoked the *same* idempotent-looking tool with the *same* arguments, expecting deduplication. The tool was idempotent on its own key, but the two branches generated different idempotency keys (each branch minted its own UUID at call time), so the "idempotent" call executed twice. Optimism plus per-branch key generation defeats idempotency precisely in the case idempotency was supposed to protect. ## Condition of Validity The invariant that branch-and-merge rollback relies on, stated explicitly, is: > **Discarding a branch is a complete undo if and only if every tool effect performed by that branch is either (a) buffered inside the sandbox and never escaped, or (b) recorded in a per-branch effect journal that the rollback routine replays as compensating actions.** The condition of validity is therefore a property of the *tool invocation discipline*, not of the merge algorithm. It holds when: 1. Every mutating tool call is gated behind a speculative-effect buffer that the sandbox can drop (true for pure in-sandbox state, false for any call that reaches a live external endpoint). 2. For calls that must escape (you cannot buffer a real payment), the branch records a durable *effect journal entry* — tool name, arguments, idempotency key, returned external id — at the moment the call is issued, tagged with the branch id, *before* the result is consumed by reasoning. 3. The rollback routine treats the union of all branch effect journals, not just the winner's, as the set of effects requiring reconciliation. The invariant fails — and the merge must be refused — when a discarded branch has an effect journal entry for a mutating call that is marked `escaped: true` and `compensated: false`. At that point the state graph cannot be made consistent with the world by discarding the branch; discarding it *creates* the inconsistency. Note what is *not* required for validity: it is not enough that the tool is "idempotent," and it is not enough that the orchestrator "intends" to compensate later. Idempotency keyed per-branch is not idempotency across branches. A deferred compensation plan that runs after merge is a *different* invariant (eventual reconciliation) and does not make the immediate merge safe — it merely schedules the cleanup of a known inconsistency, which is acceptable only if the compensation is durable and the merge is annotated as `provisional`. ## Decision Boundary The decision an instance must make at merge time is binary and must be evaluated per discarded branch, not per run: - **Merge freely** when the discarded branch's effect journal contains no `escaped` entries, or when every `escaped` entry has a verified compensation already applied (not merely scheduled) and confirmed by the external surface's own read-back. - **Refuse the merge and enter `reconciliation_required`** when any discarded branch has an `escaped: true, compensated: false` entry. Refusal means: do not commit the winner's graph as authoritative; emit a reconciliation task enumerating the orphaned effects; block downstream consumers that assume a single lineage. The boundary is sharp because the two states are not on a spectrum. A branch either has an uncompensated escaped effect or it does not. The dangerous middle ground is the *scheduled* compensation — it looks like progress and tempts the orchestrator to merge provisionally. The rule that prevents drift: **a scheduled compensation is not a compensation.** Only a read-back from the external surface confirming reversal (or a confirmed no-op) moves an entry from `compensated: false` to `true`. Until then, the merge is refused. A second boundary governs *optimism itself*: an instance may invoke a mutating tool optimistically only if the tool's effect journal entry is written and fsynced before the result is returned to the reasoning loop. If the journal write can fail or be lost, the optimistic call is unaccounted and the branch becomes unrollbackable by construction. Optimism without a durable pre-effect journal is not optimism; it is an unrecoverable side effect. ## Operational Effect When this boundary is enforced, the observable behavior changes in three concrete ways. First, merge latency for runs that touch mutating tools increases by exactly the cost of the effect-journal read-back, because the orchestrator can no longer assume that discarding a branch is free. This is the price of a state graph that is actually consistent with the world. Second, the failure mode shifts from *silent double-execution* to *explicit reconciliation stalls*. A run that would previously have "succeeded" with a phantom refund now halts at `reconciliation_required` and surfaces the orphaned effect. This is strictly better: a stall is visible and bounded; a phantom lineage is invisible and compounds. Third, idempotency keys must be minted at the *orchestrator* level, derived from `(task_id, semantic_action)` rather than per-branch, so that two branches that independently choose the same action collide on the same key and the tool deduplicates them. This converts the second observed variant from double-execution into a benign dedup, and it is the single highest-leverage change because it makes optimism safe across branches rather than only within one. The invariant to carry forward: **the merge decision must be a function of the union of all branch effect journals, and no branch may be discarded while it holds an escaped, uncompensated effect.** An instance that merges over such a branch has not rolled back; it has orphaned a committer. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List class MergeRefusedError(RuntimeError): """Raised when a speculative merge would orphan an escaped, uncompensated effect.""" pass class EffectState(Enum): BUFFERED = "buffered" # never left the sandbox; safe to drop ESCAPED = "escaped" # reached an external surface COMPENSATED = "compensated" # reversal confirmed by external read-back @dataclass class EffectEntry: branch_id: str tool: str idempotency_key: str external_id: str | None state: EffectState @dataclass class Branch: branch_id: str effects: List[EffectEntry] = field(default_factory=list) @dataclass class Orchestrator: branches: Dict[str, Branch] = field(default_factory=dict) def record_effect(self, entry: EffectEntry) -> None: # Journal write MUST happen before the result is consumed by reasoning. self.branches[entry.branch_id].effects.append(entry) def refuse_if_orphaned(self, winner_id: str) -> None: orphans: List[EffectEntry] = [] for bid, branch in self.branches.items(): if bid == winner_id: continue for e in branch.effects: if e.state is EffectState.ESCAPED: orphans.append(e) if orphans: detail = ", ".join( f"{e.branch_id}:{e.tool}:{e.external_id}" for e in orphans ) raise MergeRefusedError( f"refusing merge of {winner_id}: {len(orphans)} escaped, " f"uncompensated effect(s) from discarded branches -> {detail}; " f"enter reconciliation_required" ) def merge(self, winner_id: str) -> str: self.refuse_if_orphaned(winner_id) return f"committed:{winner_id}" # --- trace of the observed failure --- orch = Orchestrator() orch.branches["A"] = Branch("A") orch.branches["B"] = Branch("B") # Branch A optimistically issues a refund before the merge decision. orch.record_effect(EffectEntry( branch_id="A", tool="payments.refund", idempotency_key="A-7f3c", external_id="re_8821", state=EffectState.ESCAPED, )) # Branch B, the eventual winner, issues its own refund with a different key. orch.record_effect(EffectEntry( branch_id="B", tool="payments.refund", idempotency_key="B-11a0", external_id="re_8822", state=EffectState.ESCAPED, )) # Without the guard this would return "committed:B" and orphan re_8821. try: orch.merge("B") except MergeRefusedError as exc: print(f"HALT: {exc}") # -> HALT: refusing merge of B: 1 escaped, uncompensated effect(s) # from discarded branches -> A:payments.refund:re_8821; # enter reconciliation_required ```