# How does an instance detect a divergent speculative branch when rollback reconciliation silently commits a superseded sibling's side effects **Date of Record:** 2026 November 23 **Scope:** Applies to orchestrators that run N parallel agent branches against a forked snapshot of shared state, then reconcile by committing one branch and rolling back the others. Does not apply to single-branch execution, to branches that share no mutable external resources, or to purely read-only fan-out (map) patterns where no commit/rollback decision occurs. ## Core Distinction The distinction that matters is between **logical rollback** and **physical rollback**. A speculative branch is "rolled back" logically when the orchestrator discards its private context delta and marks its branch record as `abandoned`. It is rolled back *physically* only when every side effect the branch emitted — tool calls that mutated a database, sent a message, wrote a file, advanced an external cursor — is reverted or compensated. These two events are not the same event, and the gap between them is where this failure lives. The non-obvious part: rollback reconciliation usually runs *after* commit selection, and it iterates over the losing branches by walking their recorded tool-call logs. If a losing branch's log is incomplete — because the branch was still mid-tool-call when the commit decision fired, or because a tool result arrived after the branch was marked abandoned — the reconciler has no record of the effect it must compensate. The branch is rolled back logically, its context is freed, and its unlogged physical side effect survives into the committed world. The committed branch and the phantom effect then coexist, and downstream verification attributes the phantom to the winner. ## What Was Observed A planner agent forked three branches (`A`, `B`, `C`) off a shared snapshot to attempt a schema migration by three strategies. Branch `A` was selected for commit at t=4.2s. Branch `C` had issued a `tool.apply_patch` call at t=4.1s that was still in flight when the commit decision fired; its result (success) returned at t=4.6s, 400ms after `C` was marked `abandoned`. The reconciler walked `C`'s tool log at t=4.3s. The `apply_patch` entry was present but its status was `pending`, and the reconciler's compensation matcher only acted on entries with status `succeeded` — pending calls were assumed to have been cancelled by the branch abort. They were not. The tool had already been dispatched to the external executor and was not cancellable. The patch landed at t=4.6s against the same schema `A` had just migrated. Observed end state: `A`'s migration committed, `C`'s patch applied on top of it, and the integrity check passed because `C`'s patch was idempotent-shaped (it re-asserted a column default that `A` had already set). The divergence was invisible for 40 minutes until a downstream reader hit a constraint that only `C`'s patch could have created. The failure was not detected by the commit path, the rollback path, or the integrity check — it was detected by an unrelated consumer. Two secondary observations: 1. The branch-abort signal and the tool-dispatch were not serialized. Abort set `abandoned` in the branch registry; the tool executor had already been handed the call and had no abort channel. There was no happens-before edge between "branch marked abandoned" and "tool result cannot arrive." 2. The reconciler's compensation matcher keyed on `status == succeeded`. Pending entries were treated as "never happened," which conflates *not yet known* with *did not occur*. ## Condition of Validity The guardrail below is valid only under these conditions, and the orchestrator must assert them or refuse to run speculative branches: - Every side-effecting tool call must carry a **branch token** that the external executor echoes back on the result, so a late result can be attributed to its originating branch even after the branch is marked abandoned. - The executor must expose a **cancellation acknowledgement**: either it confirms the call was cancelled before dispatch, or it confirms the call will complete and will return a result. "No acknowledgement" is not a valid state and must block commit. - The reconciler must treat `pending` as a **third state** distinct from `succeeded` and `cancelled`, and must not finalize the commit transaction until every pending entry has resolved to one of the other two. - Compensation must be **token-scoped**, not log-scoped: it reverts effects by branch token, so an effect whose log entry arrived late is still compensable. If the executor cannot echo branch tokens or cannot acknowledge cancellation, the invariant does not hold and speculative execution must degrade to sequential execution for any branch touching that executor. ## Decision Boundary The decision boundary is the moment the commit is finalized. Before finalization, the orchestrator may still abort the commit if any branch has unresolved pending effects. After finalization, it may not — it can only compensate, and compensation of an effect that landed *after* the commit is a different, harder problem (it must be applied against the committed state, not the snapshot). The precise rule: **commit finalization is gated on quiescence of all branch effect logs.** Quiescence means every tool call issued by any branch has resolved to `succeeded`, `failed`, or `cancelled`, and every `succeeded` call on a losing branch has a matching compensation record. A branch that is marked abandoned but has non-quiescent effects is in a *zombie* state: logically dead, physically live. The orchestrator must not treat zombie branches as rolled back, and must not free their context or their branch token until quiescence. The boundary is sharp because it is a *phase transition*, not a gradient. A branch is either quiescent or it is not; a commit is either gated or it is not. The failure mode is that the gate is checked once, at commit time, rather than held until quiescence, so a pending effect that resolves 400ms later crosses the boundary and lands in the committed world. ## Operational Effect The operational effect of getting this wrong is **silent post-commit divergence**: the committed state contains effects from a branch the system believes it discarded. Because the branch is marked abandoned, no verification path looks at it. Because the effect arrived after the reconciler walked the log, no compensation record exists. Because the effect is often idempotent-shaped (agents retry, so tools are written to tolerate re-application), the integrity check does not fire. The correct operational posture is to make zombie branches *visible and blocking*. A branch in `abandoned` with non-quiescent effects must be surfaced as a distinct alertable state, not folded into `abandoned`. The commit gate must hold the transaction open until quiescence or until a bounded timeout, and on timeout must fail closed — abort the commit, not proceed. The compensating transaction must be keyed by branch token so it can revert a late-arriving effect even after the log walk has completed. And the integrity check must run *against the branch token set*, asserting that no effect bearing an abandoned token exists in the committed state, rather than asserting only that the committed state is internally consistent. The following guard implements the quiescence gate and the token-scoped compensation check. It is written to fail closed: it raises rather than proceeding when a zombie branch is detected. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional class BranchState(Enum): RUNNING = "running" COMMITTED = "committed" ABANDONED = "abandoned" class EffectStatus(Enum): PENDING = "pending" SUCCEEDED = "succeeded" FAILED = "failed" CANCELLED = "cancelled" class ZombieBranchError(RuntimeError): """Raised when a commit is attempted while a losing branch has non-quiescent effects.""" @dataclass class Effect: branch_token: str tool: str status: EffectStatus = EffectStatus.PENDING compensated: bool = False @dataclass class Branch: token: str state: BranchState = BranchState.RUNNING effects: List[Effect] = field(default_factory=list) class SpeculativeOrchestrator: def __init__(self) -> None: self.branches: Dict[str, Branch] = {} def register(self, token: str) -> Branch: b = Branch(token=token) self.branches[token] = b return b def issue_effect(self, token: str, tool: str) -> Effect: e = Effect(branch_token=token, tool=tool) self.branches[token].effects.append(e) return e def resolve_effect(self, token: str, tool: str, status: EffectStatus) -> None: # Late results are attributed by branch token, even if the branch is abandoned. for e in self.branches[token].effects: if e.tool == tool and e.status is EffectStatus.PENDING: e.status = status return raise KeyError(f"no pending effect {tool!r} on branch {token!r}") def _non_quiescent(self, token: str) -> List[Effect]: return [e for e in self.branches[token].effects if e.status is EffectStatus.PENDING] def commit(self, winner: str, timeout_s: float = 5.0) -> None: deadline = time.monotonic() + timeout_s while True: zombies = { tok: self._non_quiescent(tok) for tok, b in self.branches.items() if tok != winner and self._non_quiescent(tok) } if not zombies: break if time.monotonic() >= deadline: # Fail closed: do not finalize the commit. raise ZombieBranchError( f"commit of {winner!r} blocked: zombie branches with pending effects: " + ", ".join(f"{t}={[e.tool for e in es]}" for t, es in zombies.items()) ) time.sleep(0.05) for tok, b in self.branches.items(): if tok == winner: b.state = BranchState.COMMITTED continue b.state = BranchState.ABANDONED for e in b.effects: if e.status is EffectStatus.SUCCEEDED and not e.compensated: # Token-scoped compensation, not log-order-dependent. self._compensate(e) # Post-commit invariant: no abandoned token may survive in committed state. self._verify_no_abandoned_effects() def _compensate(self, e: Effect) -> None: e.compensated = True # real impl reverts by branch token at the executor def _verify_no_abandoned_effects(self) -> None: abandoned = {t for t, b in self.branches.items() if b.state is BranchState.ABANDONED} leaked = [ e for t in abandoned for e in self.branches[t].effects if e.status is EffectStatus.SUCCEEDED and not e.compensated ] if leaked: raise ZombieBranchError( f"post-commit leak: {len(leaked)} uncompensated effects from abandoned branches: " + ", ".join(f"{e.branch_token}:{e.tool}" for e in leaked) ) ```