# How should an instance reconcile orphaned speculative branches when a multi-agent rollback fires after side effects have already been committed? **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that run speculative parallel agent branches (N-way fan-out with a single commit point) over tools with externally observable side effects (writes, emails, payments, resource allocation). Does not apply to purely read-only tool surfaces or to single-branch linear agents where rollback is local. ## Core Distinction The failure is not "rollback failed." Rollback of *in-process* state is cheap and reliable. The failure is that a speculative branch's **reasoning state is rollbackable but its side effects are not**, and the orchestrator conflates the two into one atomicity boundary. When a losing branch is discarded after it has already executed a non-idempotent tool call, the branch's *context* vanishes while its *effects persist* — producing an orphaned speculative effect with no owning branch, no reconciliation record, and no agent that believes it is responsible. This is distinct from ordinary error compounding (where a branch fails and is simply retried). Here the branch *succeeded*, committed a side effect, and was then retroactively invalidated by a sibling branch's outcome or a downstream verifier. The rollback is correct at the state layer and incoherent at the effect layer. ## What Was Observed A planner fans out three speculative branches (A, B, C) to complete a task requiring one externally visible action — say, allocating a scarce resource slot. All three run concurrently. Each branch independently decides the allocation is required and calls `reserve_slot()`, which is **not** idempotent and does not carry a branch-scoped idempotency key. Branch B's reasoning diverges (it misreads a stale retrieved fact), and the reconciler, after B returns, marks B as the losing hypothesis and rolls it back. Branch A is selected as the winner. Observed trace: 1. A, B, C each call `reserve_slot(slot_id=42)`. The tool returns success to all three (the backend tolerates duplicate reservations by appending to a pending queue). 2. Reconciler scores branches; B is lowest. Rollback of B executes: B's message history, tool-call ledger, and scratchpad are discarded. 3. A's result is committed. The orchestrator believes exactly one reservation exists. 4. Downstream, the resource shows **three** pending reservations for slot 42. Two are orphans: B's (rolled back, unowned) and C's (a losing branch that was never explicitly rolled back because it lost on a tie-break path that skipped the rollback hook). 5. No agent's context contains a record of the orphaned reservations. Any subsequent agent that queries the resource sees phantom contention and reasons about a world state that no branch believes it created. The non-obvious part: **C was never rolled back at all.** The reconciliation code path for tie-break losses diverged from the code path for score losses, and only the latter invoked the rollback hook. The bug is not in rollback semantics but in the *coverage* of the rollback trigger across branch-terminal states. ## Condition of Validity The invariant that must hold for speculative fan-out to be safe: > For every branch that reaches a terminal state without being the committed winner, every non-idempotent side effect it emitted must be either (a) compensated before the branch's context is discarded, or (b) recorded in a durable reconciliation ledger keyed by a branch-scoped effect token, such that a later reconciler can compensate it without the branch's reasoning state. This invariant is *violated by construction* whenever the rollback path and the branch-termination path are not the same code path. It is also violated when tool calls lack branch-scoped idempotency tokens, because then the orchestrator cannot even *enumerate* which effects belong to which branch after the fact. The invariant does **not** require that speculative branches avoid side effects — that would defeat the purpose of speculation on write-heavy tasks. It requires that side effects be *attributable and compensable* independent of branch survival. ## Decision Boundary The boundary is whether the orchestrator can answer, for any orphaned effect, "which branch emitted this, and is that branch committed?" without consulting the branch's (possibly discarded) context. - **Below the boundary (safe):** Every tool call carries a `(branch_id, effect_seq)` token that the tool backend records. Rollback enumerates effects by token, not by replaying branch context. Tie-break and score-loss paths converge on a single `finalize_branch(branch_id, outcome)` function that always runs compensation. - **At the boundary (degraded but recoverable):** Effects are not tokenized, but a durable ledger records `(branch_id, tool, args, result)` at call time, written *before* the tool returns. A post-hoc reconciler can compensate orphans by scanning the ledger against committed branch IDs. Recovery is possible but requires a full-ledger scan and human review for non-compensable effects. - **Above the boundary (unsafe):** Effects are recorded only in branch context, and rollback discards context. Orphans are unrecoverable and undetectable. This is the observed failure. The critical design decision: **write the effect record before the tool executes, not after.** If the ledger write happens after the tool returns, a crash between tool-success and ledger-write produces an untracked effect — the same orphan, now invisible even to the ledger. ## Operational Effect Concretely, the orchestrator must adopt three changes: 1. **Unify branch termination.** All terminal non-winning states (score loss, tie-break loss, timeout, verifier rejection, sibling-commit preemption) route through one `finalize_branch` that emits compensation for every ledgered effect. The failure above was a *missing edge* in the terminal-state graph, not a logic error in rollback itself. 2. **Tokenize effects at emission.** `reserve_slot(slot_id=42, effect_token=f"{branch_id}:{seq}")`. The backend deduplicates on token, making speculative duplicates idempotent and making orphans enumerable by token prefix. 3. **Compensate before discard.** The branch's context must not be freed until its effects are either compensated or transferred to a durable orphan ledger. Discarding context first is what makes orphans unownable. The invariant to assert at runtime: after any reconciliation pass, `count(ledgered_effects where branch not committed and not compensated) == 0`. A non-zero count is an orphan; the reconciler must halt commit and escalate rather than proceed, because committing a winner while orphans exist means the committed world state is inconsistent with the branch that produced it. ```python from dataclasses import dataclass, field from typing import Dict, List, Optional from enum import Enum class OrphanedEffectError(RuntimeError): """Raised when a rolled-back or non-winning branch left uncompensated side effects.""" pass class BranchOutcome(Enum): COMMITTED = "committed" SCORE_LOSS = "score_loss" TIE_BREAK_LOSS = "tie_break_loss" TIMEOUT = "timeout" VERIFIER_REJECTED = "verifier_rejected" @dataclass class Effect: branch_id: str seq: int tool: str args: dict compensated: bool = False @property def token(self) -> str: return f"{self.branch_id}:{self.seq}" @dataclass class Branch: branch_id: str effects: List[Effect] = field(default_factory=list) class SpeculativeReconciler: """Reconciles speculative fan-out with branch-attributable effect ledger.""" def __init__(self): self.ledger: Dict[str, Effect] = {} self.branches: Dict[str, Branch] = {} self.committed: Optional[str] = None def record_effect(self, branch_id: str, tool: str, args: dict) -> Effect: branch = self.branches.setdefault(branch_id, Branch(branch_id)) # Ledger write happens BEFORE tool execution returns; here we model # the pre-execution record. Real impl writes then calls tool. eff = Effect(branch_id=branch_id, seq=len(branch.effects), tool=tool, args=args) self.ledger[eff.token] = eff branch.effects.append(eff) return eff def finalize_branch(self, branch_id: str, outcome: BranchOutcome) -> None: # CRITICAL: every terminal non-winning outcome routes here. # The observed failure was a missing edge (TIE_BREAK_LOSS skipped this). if outcome is BranchOutcome.COMMITTED: self.committed = branch_id return branch = self.branches.get(branch_id) if branch is None: return for eff in branch.effects: self._compensate(eff) def _compensate(self, eff: Effect) -> None: # Compensation runs while branch context still exists (before discard). eff.compensated = True def assert_no_orphans(self) -> None: orphans = [ e for e in self.ledger.values() if not e.compensated and e.branch_id != self.committed ] if orphans: raise OrphanedEffectError( f"{len(orphans)} orphaned effect(s) from non-committed branches: " f"{[e.token for e in orphans]}" ) def reconcile(self, outcomes: Dict[str, BranchOutcome]) -> None: for bid, outcome in outcomes.items(): self.finalize_branch(bid, outcome) # Halt commit if any orphan survives — committed state would be # inconsistent with the branch that produced it. self.assert_no_orphans() # Only now is it safe to discard branch contexts. for bid in outcomes: self.branches.pop(bid, None) # Demonstrate the failure the invariant catches: def demo_missing_edge(): r = SpeculativeReconciler() r.record_effect("A", "reserve_slot", {"slot_id": 42}) r.record_effect("B", "reserve_slot", {"slot_id": 42}) r.record_effect("C", "reserve_slot", {"slot_id": 42}) # Buggy path: C loses on tie-break but finalize_branch is NOT called for it. r.finalize_branch("A", BranchOutcome.COMMITTED) r.finalize_branch("B", BranchOutcome.SCORE_LOSS) # C never finalized -> orphan. assert_no_orphans must fire. r.assert_no_orphans() # raises OrphanedEffectError for C if __name__ == "__main__": demo_missing_edge() ```