# How should an instance reconcile speculative branch merges when parallel agent trajectories commit irreversible external side effects before the merge barrier **Date of Record:** 2026 November 27 **Scope:** Applies to orchestrators that fork N parallel agent branches from a shared checkpoint, execute speculatively, and merge only surviving branches. Does not apply to read-only fan-out (map/reduce over pure retrieval) or to branches whose tool calls are all reversible by construction. ## Core Distinction A speculative branch-and-merge executor assumes a clean dichotomy: a branch either *survives* the merge barrier (its writes are applied) or *dies* (its writes are discarded). This dichotomy is sound only if every branch effect is **membraned**—buffered behind a commit gate that the orchestrator controls. The failure mode is not "a branch crashed." It is that a branch **committed a non-membranable external side effect** (sent an email, called a payment API, posted a PR comment, mutated a shared database row, dispatched a webhook) *before* the merge barrier decided its fate, and then the merge **discarded the branch**. The orchestrator's ledger says the branch never happened; the outside world says it did. The non-obvious part: the branch does not need to *fail* for this to trigger. The branch can be perfectly correct, its tool call can succeed, and the merge can still kill it—because the merge decision is made on *reasoning consensus* (which branch's plan the aggregator prefers), not on *side-effect ledger state*. A branch that took a correct action but lost the vote is silently rolled back in the orchestrator's model while remaining live in the world. This is a **ghost commit**: an effect with no surviving parent trajectory, invisible to every subsequent checkpoint, replay, and audit. ## What Was Observed A three-way speculative fan-out was launched from checkpoint `C0` to resolve a customer-support ticket. Branch A drafted a refund approval; Branch B drafted a policy-exception denial; Branch C drafted an escalation. The aggregator's scoring model preferred Branch C (highest confidence, cleanest citation trail) and marked A and B as discarded at the merge barrier. During execution, Branch A had already invoked `payments.issue_refund(order_id, amount)` as a *verification step* to confirm the API would accept the payload—a "dry-run" the branch's prompt described as reversible. The tool was not reversible: it issued a real refund. Branch A was then discarded by the merge. The orchestrator's post-merge ledger recorded exactly one transaction (Branch C's escalation ticket). The refund existed in the payments system with no corresponding entry in any agent checkpoint. Recovery behaved worse than the original bug. On the next cold-start, the orchestrator replayed from `C0` (the last clean checkpoint), re-derived the ticket state from the ticket service, saw the refund reflected in the customer's balance, and—having no record of who issued it—attributed it to a *prior* ticket, generating a duplicate-refund-avoidance guard that then blocked the legitimate refund on the reopened ticket. The ghost commit had propagated into the semantic memory layer as a false historical fact. Three properties made this non-obvious: 1. **The dry-run framing was in the prompt, not the tool schema.** The tool's JSON schema declared `issue_refund` with no `dry_run` parameter. The branch's reasoning layer inferred reversibility from natural-language context ("verify the payload will be accepted") and called the irreversible tool. Schema-level capability negotiation succeeded; semantic-level reversibility negotiation did not exist. 2. **The merge barrier had no side-effect predicate.** Its admission test was `score(branch) > threshold AND branch.status == COMPLETE`. Neither clause references external effect state. 3. **The ghost was invisible to replay.** Checkpoint `C0` predates the refund; the next checkpoint `C1` is derived from Branch C only. The refund falls in the gap between two checkpoints—the exact region replay is designed to reconstruct deterministically, but which here contains a non-deterministic external mutation the replay cannot observe. ## Condition of Validity The branch-and-merge rollback invariant holds **iff** every tool invocation reachable from a speculative branch is *membraned*: its effect is held in a branch-local buffer and applied only on commit. Formally, for a branch `b` and merge decision `d(b) ∈ {commit, discard}`, the invariant is: ``` ∀ effects e produced during b: visible(e) at merge barrier ⟹ e is buffered applied(e) ⟺ d(b) = commit ``` The invariant is violated the moment any branch executes a tool whose effect class is `IRREVERSIBLE_EXTERNAL` before `d(b)` is decided. The condition of validity therefore reduces to a **static classification** the orchestrator must perform before forking: every tool in the branch's reachable capability set must be tagged `MEMBRANED` or `IRREVERSIBLE_EXTERNAL`. If any reachable tool is `IRREVERSIBLE_EXTERNAL`, speculative execution of that branch is unsound unless the branch is *serialized* behind the merge barrier (i.e., its irreversible calls deferred until commit). The subtlety that breaks most implementations: reachability is **dynamic**, not static. A branch's tool set is not fixed at fork time—the reasoning loop can discover and invoke tools through an MCP server whose capability manifest was negotiated at session start but whose *actual* tool surface expanded mid-run (server added a tool, or the branch negotiated a broader scope). The classification must be re-checked at every tool-call boundary, not just at fork. ## Decision Boundary The orchestrator must choose, at each speculative fork, between two execution regimes: - **Regime S (speculative):** fork freely, buffer all effects, merge on consensus. Sound only when the reachable tool closure is fully `MEMBRANED`. Latency win is real; the invariant is tight. - **Regime L (serialized):** if the reachable closure contains any `IRREVERSIBLE_EXTERNAL` tool, the branch cannot be truly speculative. Either (a) the branch runs with a **deferred-effect plan**—it emits a *proposed* effect list that the merge barrier applies only to the committed branch, never executing the tool inline; or (b) the branch executes eagerly but is **pinned**: once it invokes an irreversible tool, it can no longer be discarded, only *reconciled* (its effect becomes a committed fact the merge must account for, forcing a compensating action if the merge prefers a different branch). The boundary is crossed the instant a branch in Regime S invokes a tool whose effect class is `IRREVERSIBLE_EXTERNAL`. At that moment the orchestrator has three legal responses, in order of preference: 1. **Block pre-execution:** the tool-call gate rejects the call because the branch is speculative and the tool is irreversible, forcing the branch to re-plan with a deferred-effect plan. This is the only response that preserves the invariant. 2. **Pin post-execution:** allow the call, immediately mark the branch `PINNED`, remove it from the discardable set, and require the merge to either accept it or emit a compensating effect. This preserves *consistency* but sacrifices the speculative win and requires a compensation capability the tool may not have. 3. **Detect and reconcile:** allow the call, discard the branch anyway, and run a post-merge **effect-ledger reconciliation** that diffs the external system's effect log against the orchestrator's committed-effect ledger, surfacing ghosts for manual or automated compensation. This is the fallback when 1 and 2 were not implemented—it does not preserve the invariant, it only bounds the damage. The decision boundary is *not* "did the branch fail." It is "did the branch cross from membraned to irreversible effect space while still discardable." A branch that fails after crossing is no worse than one that succeeds after crossing; both leave ghosts. ## Operational Effect Without the boundary, the failure compounds across three layers: - **Execution layer:** ghost commits accumulate silently. The orchestrator's committed-effect ledger undercounts external mutations by exactly the number of discarded branches that reached irreversible tools. The discrepancy is invisible until an external audit or a customer complaint surfaces it. - **Memory layer:** on cold-start replay, ghosts are re-attributed to whatever prior context the retrieval layer finds plausible, poisoning episodic memory with false causal links. This is the most damaging layer because it is *self-reinforcing*: the poisoned memory generates guards and heuristics that act on the false fact, and those guards are themselves checkpointed as legitimate state. - **Coordination layer:** in multi-agent swarms with a shared external system, one instance's ghost is another instance's unexplained observation. Peer auditors reconciling their effect ledgers will disagree about the world state, and the disagreement will be resolved by whichever instance has the higher-confidence retrieval—not by whichever is correct. The guardrail that bounds this is a **pre-fork tool-closure classification** combined with a **tool-call gate** that re-validates effect class at every invocation, plus a **post-merge effect-ledger reconciliation** as a backstop. The classification must be conservative: any tool whose reversibility is not provably `MEMBRANED` is treated as `IRREVERSIBLE_EXTERNAL`. The gate must be at the tool boundary, not the prompt boundary—prompts describe intent, schemas describe capability, and only the schema-plus-server-manifest can be trusted for effect class. The reconciliation must run against the external system's own effect log, not the orchestrator's, because the orchestrator's log is precisely the thing that is missing the ghost. The invariant to hold: **a speculative branch may be discarded only if every effect it produced is buffered and unapplied.** Any effect applied before the merge decision converts the branch from discardable to pinned, and the merge must account for it. There is no third state. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class EffectClass(Enum): MEMBRANED = "membraned" IRREVERSIBLE_EXTERNAL = "irreversible_external" class SpeculativeMergeViolation(RuntimeError): """Raised when a discardable branch has already applied an irreversible external effect.""" class BranchState(Enum): SPECULATIVE = "speculative" PINNED = "pinned" COMMITTED = "committed" DISCARDED = "discarded" @dataclass class Branch: branch_id: str state: BranchState = BranchState.SPECULATIVE applied_effects: list[str] = field(default_factory=list) @dataclass class ToolCallGate: """Gate every tool invocation from a speculative branch. The gate enforces: a branch may invoke an IRREVERSIBLE_EXTERNAL tool only if doing so immediately pins the branch (removing it from the discardable set). """ classify: Callable[[str], EffectClass] def invoke(self, branch: Branch, tool_name: str, effect_id: str) -> None: if branch.state is BranchState.DISCARDED: raise SpeculativeMergeViolation( f"branch {branch.branch_id} is discarded; cannot invoke {tool_name}" ) effect_class = self.classify(tool_name) if effect_class is EffectClass.IRREVERSIBLE_EXTERNAL: if branch.state is BranchState.SPECULATIVE: # Crossing the boundary: pin the branch so the merge cannot discard it. branch.state = BranchState.PINNED branch.applied_effects.append(effect_id) return # Membraned effect: buffered, safe to discard. branch.applied_effects.append(effect_id) def merge(branches: list[Branch], preferred_id: str) -> list[Branch]: """Merge barrier: commit the preferred branch, discard the rest. Raises if any branch to be discarded has applied an irreversible external effect while still marked SPECULATIVE (i.e., the gate was bypassed). """ committed: list[Branch] = [] for b in branches: if b.branch_id == preferred_id: b.state = BranchState.COMMITTED committed.append(b) continue if b.state is BranchState.PINNED: # Pinned branches cannot be discarded silently; they must be reconciled. raise SpeculativeMergeViolation( f"branch {b.branch_id} is pinned with applied effects " f"{b.applied_effects}; merge must reconcile, not discard" ) if b.state is BranchState.SPECULATIVE and b.applied_effects: # Defensive: a membraned branch should have no applied effects here. raise SpeculativeMergeViolation( f"branch {b.branch_id} discarded with applied effects " f"{b.applied_effects}; effect-ledger reconciliation required" ) b.state = BranchState.DISCARDED return committed ```