# Which invariants prevent speculative branch rollback from resurrecting side effects in parallel multi-agent execution **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrators that fan out speculative agent branches (parallel plan attempts, optimistic tool calls, draft-then-commit patterns) and roll back losing branches by discarding their state. Does not apply to strictly serialized single-agent loops or to branches whose tool calls are provably side-effect-free. ## Core Distinction The failure mode is not "rollback failed." Rollback of *state* is trivially achievable: drop the branch's memory, discard its transcript, free its checkpoint. The failure mode is that **rollback of state is silently decoupled from rollback of effects**. An agent branch is a probabilistic planner driving non-deterministic tools; when the orchestrator discards the branch's context, the tool side effects already emitted by that branch — HTTP POSTs, file writes, queue enqueues, MCP `tools/call` invocations against a mutating server — do not receive the discard. The branch's *reasoning* is retracted; its *actions* persist. The losing branch becomes a ghost writer: it no longer exists in the agent graph, yet its writes are live in the world and will be read by the winning branch, by the reconciler, or by the next cold-started instance. The distinction that matters operationally: a speculative branch has two rollback domains, **epistemic** (what the agent believed) and **causal** (what the agent changed). Most orchestrators implement epistemic rollback and assume causal rollback follows. It does not. The invariant that must hold is that no branch may transition from `SPECULATIVE` to `DISCARDED` while it holds an un-reconciled causal footprint, unless that footprint is explicitly adopted by a surviving branch or compensated by an idempotent inverse. ## What Was Observed A three-branch speculative planner was given the task "reconcile the customer record against the CRM export and issue the corrected invoice." Branches A, B, C ran in parallel with a shared optimistic tool layer. Each branch was permitted to call `crm.update_record`, `billing.draft_invoice`, and `billing.finalize_invoice` without a pre-commit barrier; the orchestrator's conflict reconciler was supposed to select a winner by confidence score after all branches returned. Branch A (confidence 0.71) called `crm.update_record` with a corrected address, then `billing.draft_invoice`, then stalled on a slow `billing.finalize_invoice` that timed out at the transport layer. Branch B (confidence 0.88) called `crm.update_record` with a *different* corrected address (it had retrieved a newer export shard), drafted an invoice, and finalized it. Branch C (confidence 0.44) called `crm.update_record` with the original stale address because its retrieval returned a pre-export snapshot. Reconciler selected B. A and C were rolled back: their transcripts dropped, their memory namespaces garbage-collected, their MCP sessions closed. The orchestrator logged `branch_rollback: A=ok, C=ok`. What actually persisted in the world: 1. The CRM record held **C's stale address**, because C's write landed after B's write and the CRM server was last-write-wins with no version precondition. The winning branch's correct write was overwritten by a discarded branch. 2. The invoice finalized by B referenced the record as B read it, but a downstream `billing.reconcile` job read the CRM *after* C's write and flagged the invoice as mismatched, triggering a dunning sequence. 3. Branch A's timed-out `finalize_invoice` had in fact committed server-side; the client timed out on the response, not the operation. A second invoice existed for the same order, orphaned, attributable to no live branch. The reconciler's confidence score was computed entirely from the branches' *internal* self-assessment. It had no visibility into the causal footprint because the tool layer emitted effects without branch-attributed receipts. The rollback was a fiction: it retracted beliefs while the world kept the consequences. ## Condition of Validity Speculative parallel execution with optimistic tool invocation is only sound under a conjunction of invariants. Break any one and the ghost-writer failure is reachable: 1. **Effect attribution invariant.** Every mutating tool call must carry a branch-scoped, cryptographically bound token (branch ID + attempt nonce + orchestrator signature) that the receiving server records with the effect. Without this, a rollback cannot enumerate what to compensate, and the reconciler cannot distinguish a winner's write from a loser's write to the same resource. 2. **Precondition / compare-and-swap invariant.** Mutating calls against shared resources must be conditional on a version or ETag the branch read. A last-write-wins server converts every discarded branch into a potential overwriter of the winner. The CRM case above is the canonical instance: C's write succeeded because it asserted nothing about the version it was clobbering. 3. **Commit-barrier invariant for non-compensable effects.** Effects that cannot be inverted (`finalize`, `send`, `charge`, external notifications) must be gated behind a two-phase barrier: the branch may *reserve* but not *commit* until the reconciler promotes it. Optimistic invocation is only safe for effects with a defined inverse or a reservation semantic. 4. **Timeout-disambiguation invariant.** A transport timeout must be resolved to `committed`, `not-committed`, or `unknown` by a server-side idempotency lookup keyed on the branch token — never assumed to be `not-committed`. Branch A's orphaned invoice is the direct cost of treating a client timeout as a rollback signal. 5. **Rollback-completeness invariant.** The orchestrator may not mark a branch `DISCARDED` until its effect ledger is reconciled: every attributed effect is either adopted by the winner, compensated, or explicitly quarantined with an operator-visible tombstone. "Dropped the transcript" is not a terminal state. The boundary where this is *not* required: branches whose tools are read-only, or whose writes are confined to a branch-private namespace merged only on promotion (copy-on-write sandbox). In those cases epistemic and causal rollback coincide and the ghost-writer path is closed by construction. ## Decision Boundary The orchestrator must decide, per branch and per tool class, whether optimistic invocation is admissible. The decision rule: - If the effect has a **defined inverse** and the inverse is idempotent under the branch token → optimistic invocation admissible; rollback issues the inverse. - If the effect is **non-invertible** but the resource supports **conditional writes** → optimistic invocation admissible only with a read-version precondition carried on the call; rollback is unnecessary because a losing write fails the precondition rather than clobbering. - If the effect is **non-invertible and unconditional** (finalize, charge, notify) → optimistic invocation is **forbidden**; the branch must reserve and the reconciler must promote. Any orchestrator that permits this combination under speculation has an unbounded ghost-writer surface. - If the effect's commit status is **unknown** (timeout, connection reset mid-call) → the branch is frozen, not rolled back, until an idempotency lookup resolves it. Freezing is cheap; resurrecting an orphaned side effect is not. The reconciler's winner selection must also be constrained: it may not select a winner whose causal footprint conflicts with a *discarded* branch's footprint on the same resource unless the discarded footprint is compensated first. Confidence scores are epistemic and carry no information about causal conflict; using them alone to arbitrate is the error that let B win while C's stale write survived. ## Operational Effect With the invariants enforced, the failure trace changes at three points. First, C's write fails its version precondition because the export shard it read is stale relative to the record version B will write — C is rejected at the tool boundary, not resurrected at rollback. Second, A's `finalize_invoice` timeout is resolved by an idempotency lookup against A's branch token, discovering the server-side commit and compensating it before A is marked `DISCARDED`; no orphan invoice. Third, the reconciler refuses to promote B until the effect ledger shows zero un-reconciled footprints from A and C, so B's invoice is finalized against a record state that no discarded branch can later mutate. The residual cost is latency: commit barriers and precondition checks add round-trips that pure optimism avoids. The trade is deliberate — speculative parallelism buys wall-clock time at the price of a causal footprint that must be bounded. The invariant that makes the trade sound is simple to state and easy to violate: **a branch's epistemic rollback must never outrun its causal reconciliation.** Every ghost-writer incident is an instance of that ordering being inverted, and every guardrail above is a mechanism for holding the ordering. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, Set class GhostWriterError(RuntimeError): """Raised when a branch would be discarded while holding un-reconciled effects.""" class EffectClass(Enum): INVERTIBLE = "invertible" CONDITIONAL = "conditional" NON_INVERTIBLE = "non_invertible" UNKNOWN = "unknown" @dataclass class EffectReceipt: branch_id: str resource: str effect_class: EffectClass committed: bool compensated: bool = False adopted_by: str | None = None @dataclass class Branch: branch_id: str state: str = "SPECULATIVE" receipts: Dict[str, EffectReceipt] = field(default_factory=dict) class SpeculativeOrchestrator: def __init__(self) -> None: self.branches: Dict[str, Branch] = {} self.frozen: Set[str] = set() def record_effect(self, receipt: EffectReceipt) -> None: self.branches[receipt.branch_id].receipts[receipt.resource] = receipt if receipt.effect_class is EffectClass.UNKNOWN: # A timeout mid-call is not a rollback signal; freeze the branch. self.frozen.add(receipt.branch_id) def discard(self, branch_id: str, winner_id: str) -> None: branch = self.branches[branch_id] if branch_id in self.frozen: raise GhostWriterError( f"branch {branch_id} has unresolved commit status; " f"resolve idempotency before discard" ) for resource, r in branch.receipts.items(): if not r.committed: continue reconciled = r.compensated or r.adopted_by == winner_id if not reconciled: raise GhostWriterError( f"branch {branch_id} holds live effect on {resource} " f"({r.effect_class.value}) not compensated or adopted by " f"winner {winner_id}; discarding would resurrect a ghost write" ) branch.state = "DISCARDED" def promote(self, winner_id: str) -> None: for bid, branch in self.branches.items(): if bid == winner_id: continue for resource, r in branch.receipts.items(): if r.committed and not (r.compensated or r.adopted_by == winner_id): raise GhostWriterError( f"cannot promote {winner_id}: conflicting live effect on " f"{resource} from branch {bid}" ) self.branches[winner_id].state = "PROMOTED" ```