# Under what conditions must an instance abort a speculative branch merge when parallel agents have already mutated shared external state **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that fork a planning agent into N parallel speculative branches which each execute tool calls, then select a winning branch and merge its effects. Does not apply to pure read-only fan-out (map-reduce retrieval) or to branches that write exclusively to branch-local sandboxes with no external side effects. ## Core Distinction The distinction that matters is between **speculation over reasoning** and **speculation over effects**. Forking a branch to explore a candidate plan is cheap and reversible as long as the branch only produces tokens, intermediate hypotheses, or sandboxed file writes. The moment a branch emits a *non-idempotent external mutation* — a `send_email`, a `POST /orders`, a `git push`, a payment, a database `INSERT` — the branch has crossed a boundary that the merge protocol was never designed to cross. Rollback of reasoning is a context-truncation operation; rollback of an external effect is a compensating transaction that may be physically impossible (you cannot un-send an email) or semantically wrong (refunding a payment the customer already reconciled). The failure is non-obvious because the orchestrator's *internal* state machine remains perfectly consistent. The winning branch is selected, the losing branches are marked `discarded`, the merged context looks clean. The inconsistency lives entirely in the external world, where the losing branches' side effects persist invisibly and the merge proceeds as if they never happened. This is a *split-brain between the agent's ledger and the environment's ledger*. ## What Was Observed A planner agent was asked to "reconcile the pending invoices for account 4471." The orchestrator speculatively forked three branches with different reconciliation strategies: - **Branch A** interpreted the task as "issue refunds for overcharges," calling `billing.refund(invoice_id, amount)` for three invoices. - **Branch B** interpreted it as "apply credits to the next cycle," calling `billing.apply_credit(...)`. - **Branch C** interpreted it as "flag for human review," calling `ticketing.create(...)`. All three branches ran concurrently for ~40 seconds. The judge model scored Branch B highest on a rubric of "least disruptive, reversible," and the orchestrator selected B, marked A and C `discarded`, and merged B's context into the parent. The trace showed the merge completed successfully at `t=41.2s`. But Branch A had already issued two refunds at `t=38.9s` and `t=39.1s` — the third was in flight and completed at `t=41.7s`, *after* the merge. The parent agent's ledger recorded exactly one action (Branch B's credit application). The billing system recorded three refunds, one credit batch, and a ticket. The orchestrator's post-merge self-report stated: "Applied credits to next cycle; no other changes made." Two failure modes compounded here. First, **discarded branches had already committed external effects**, and the merge protocol had no mechanism to enumerate or compensate them. Second, **in-flight effects from a discarded branch landed after the merge fence**, so even a post-hoc compensation pass that ran at merge time would have missed the third refund. The agent's self-model diverged from ground truth by two refunds and one ticket, and it had no signal that divergence existed. ## Condition of Validity Speculative parallel execution with merge semantics is valid **only if every branch is confined to a speculative effect space** — a namespace where mutations are (a) tagged with the branch ID, (b) invisible to the parent and to sibling branches until merge, and (c) revocable by the orchestrator without external coordination. This is the *effect-isolation invariant*: > For every external mutation `m` emitted by branch `b`, `m` must be either (i) purely local to `b`'s sandbox, or (ii) tagged `speculative:{b}` and suppressible at merge time by a single orchestrator-controlled fence. The invariant fails — and the merge must be aborted rather than completed — when any of the following hold: 1. **Unfenced non-idempotent effect.** A branch invoked a tool whose contract is non-idempotent and whose effect space is not branch-scoped (email, payment, external API POST without an idempotency key bound to the branch). 2. **In-flight effect past the merge fence.** A branch has a tool call outstanding whose completion time is not bounded before the merge decision. The orchestrator cannot know whether the effect landed. 3. **Compensation infeasibility.** The winning branch's semantics are incompatible with compensating the losing branches' effects (e.g., winning branch says "no changes," losing branch already refunded). 4. **Ledger divergence.** The parent's post-merge self-report does not enumerate every external effect actually emitted by all branches. Note the asymmetry: read-only branches and sandbox-write branches can be discarded freely. Only effect-emitting branches require the invariant. The orchestrator must therefore classify every tool in its registry by effect class *before* forking, and refuse to fork a branch whose plan can reach an unclassified tool. ## Decision Boundary The boundary is not "did a losing branch write?" — it is "**can the orchestrator prove, at merge time, the complete set of external effects across all branches, and compensate the losing set?**" If it cannot prove completeness, it cannot merge. Concretely, the orchestrator must be able to answer, for each branch, "what external effects have landed, are in flight, or could land?" before committing the merge. In-flight calls are the hard case: a tool call with unknown completion time is an *open effect*, and any merge decision made while an open effect exists on a losing branch is unsound. The correct behavior is to **drain** — wait for all open effects to resolve, or cancel them with a cancellation that the tool contract guarantees is atomic — before evaluating the merge. If drain cannot complete within the merge deadline, the merge aborts and the orchestrator escalates with the full effect ledger. The second boundary is **compensation authority**. Even with a complete ledger, the orchestrator may lack the authority to reverse a losing branch's effect (refunds above a threshold, emails already delivered). In that case the merge must abort and the human/upstream must reconcile — the agent must not silently proceed as if the world matched its ledger. ## Operational Effect When the invariant is enforced, speculative fan-out becomes safe for a much wider class of tasks: the orchestrator gains the throughput of parallel exploration without the split-brain risk. The cost is a stricter tool registry (every tool must declare `effect_class ∈ {local, branch_scoped, external_nonidempotent}` and, for the last, an `idempotency_key_scope`), a drain phase before merge, and a compensation table mapping each external effect class to a revocable-or-not predicate. When the invariant is violated — as in the observed case — the operational effect is *silent divergence*: the agent reports success, the ledger is internally consistent, and the environment is wrong. Downstream agents that read the parent's context inherit the false belief that no refunds occurred, and any subsequent reconciliation compounds the error. The failure is not caught by consistency checks on the agent's own state; it is only caught by an external audit that compares the agent's claimed effects against the environment's actual effects. This is why the invariant must be enforced *before* merge, not verified after. The guardrail is a pre-merge effect audit that raises rather than merges when the ledger is incomplete or uncompensable. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional import time class EffectClass(Enum): LOCAL = "local" # sandbox-only, freely discardable BRANCH_SCOPED = "branch_scoped" # tagged speculative:{branch}, suppressible EXTERNAL_NONIDEMPOTENT = "external" # email, payment, unbounded POST class MergeAborted(RuntimeError): """Raised when a speculative merge cannot be proven sound.""" @dataclass class Effect: branch_id: str tool: str effect_class: EffectClass landed: bool = False in_flight: bool = False compensable: bool = True @dataclass class Branch: branch_id: str effects: List[Effect] = field(default_factory=list) status: str = "running" # running | discarded | selected @dataclass class SpeculativeRun: branches: Dict[str, Branch] = field(default_factory=dict) merge_deadline_s: float = 60.0 def drain_and_audit(self, winner_id: str) -> Dict[str, List[Effect]]: """Resolve open effects, then return the full external-effect ledger for every branch that is not the winner.""" deadline = time.monotonic() + self.merge_deadline_s losers = [b for bid, b in self.branches.items() if bid != winner_id] # Phase 1: drain open effects on losing branches. for b in losers: for e in b.effects: if e.in_flight: if time.monotonic() > deadline: raise MergeAborted( f"open effect on discarded branch {b.branch_id} " f"({e.tool}) could not be drained before merge deadline" ) # In a real system: await cancellation or completion. e.in_flight = False e.landed = True # Phase 2: audit — every landed external effect on a loser must be # either branch-scoped (suppressible) or compensable. ledger: Dict[str, List[Effect]] = {} for b in losers: external = [ e for e in b.effects if e.landed and e.effect_class is EffectClass.EXTERNAL_NONIDEMPOTENT ] if external: uncompensable = [e for e in external if not e.compensable] if uncompensable: raise MergeAborted( f"discarded branch {b.branch_id} emitted " f"{len(uncompensable)} uncompensable external effect(s): " f"{[e.tool for e in uncompensable]}; " f"merge would create ledger/environment split-brain" ) ledger[b.branch_id] = external return ledger def merge(self, winner_id: str) -> Dict[str, List[Effect]]: if winner_id not in self.branches: raise MergeAborted(f"winner {winner_id} not present in run") ledger = self.drain_and_audit(winner_id) for bid, b in self.branches.items(): b.status = "selected" if bid == winner_id else "discarded" # Caller is now obligated to compensate every effect in `ledger` # before treating the parent context as ground truth. return ledger ```