# Which invariants prevent orphaned branch commits from resurrecting after speculative multi-agent rollback **Date of Record:** 2026 November 23 **Scope:** Applies to orchestration layers that run N parallel speculative agent branches against a shared mutable world-state (filesystem, database, tool-side effects) and reconcile by selecting one winning branch and rolling back the others. Does not apply to purely functional/stateless fan-out where branches have no side effects on shared substrate. ## Core Distinction The distinction that matters here is between **logical rollback** (the orchestrator marks a branch as discarded and stops scheduling it) and **physical rollback** (every side effect the branch committed is provably undone before the winner's effects are made durable). Most speculative-execution frameworks implement logical rollback correctly and physical rollback only *approximately* — because tool calls are non-deterministic, external, and not uniformly reversible. The boundary failure is not "the loser branch keeps running." It is: **a loser branch that has already been told to stop can still land a commit after the winner's commit has been serialized, because the branch's last in-flight tool call outlived the abort signal.** This is an orphaned commit — a write whose authoring branch is dead but whose effect is live. The invariant that prevents resurrection is not "abort losers before committing winner." It is stronger: **the winner's commit may not be made durable until every loser branch has reached a terminal quiescent state in which no tool call is in flight and no buffered write remains unflushed.** Abort is a request; quiescence is a proof. ## What Was Observed A three-branch speculative planner (branches A, B, C) each executed a multi-step plan that included a `write_file` tool call against a shared workspace and a `git commit`-equivalent checkpoint. Branch A finished first and was selected as winner. The orchestrator issued abort to B and C, received abort acknowledgements from both, and serialized A's commit. Post-commit, the workspace diff contained a hunk authored by C. Trace reconstruction: 1. C's planner had already dispatched `write_file(path="config.yaml", content=...)` to an async tool executor. The executor had the request in flight but had not yet returned. 2. Orchestrator selected A and called `abort(C)`. C's agent loop checked its cancellation flag between steps, saw it set, and returned `ABORTED` — **without awaiting the in-flight tool call**, because the tool executor was a separate task the loop did not own. 3. Orchestrator treated C's `ABORTED` return as quiescence and serialized A's commit. 4. The in-flight `write_file` completed ~40ms later, landing C's content on top of A's committed tree. 5. The commit was durable; the resurrection was silent. No error surfaced. The next verification step read a tree that matched neither A nor C. The failure is a **liveness/ordering gap**: abort acknowledgement was interpreted as a happens-before edge that did not exist. The tool executor's completion had no ordering relationship to the orchestrator's commit serialization. ## Condition of Validity The quiescence-before-commit invariant is valid — and the failure is prevented — only under all of the following: - **Every side-effecting tool call is tracked by the branch's own lifecycle.** If a branch can dispatch a tool call that the branch's abort path does not await, quiescence is unprovable and the invariant is vacuous. The orchestrator must own or observe the full set of in-flight calls, not just the agent loop. - **Abort is two-phase: signal, then drain.** Phase one sets the cancellation flag (stops new dispatches). Phase two awaits every in-flight call to a terminal result (success, failure, or timeout) and flushes buffered writes. Only phase two's completion constitutes quiescence. - **The winner's commit is fenced behind a barrier that all loser drain-phases must cross.** A loser that times out during drain must be treated as *non-quiescent*, not as quiescent-by-default. Defaulting to "assume it stopped" reintroduces the resurrection window. - **Tool executors are idempotent or carry a branch-scoped fence token** so that a late-arriving call from a timed-out loser can be rejected at the substrate rather than silently applied. Without a fence token, drain-timeout losers are a permanent latent resurrection risk. When a tool call is genuinely un-cancellable and un-fenceable (e.g., an external API that already accepted the request), the invariant cannot be enforced by ordering alone and must fall back to **post-commit reconciliation**: re-read the substrate, diff against the winner's expected tree, and treat any unexpected hunk as a hard fault rather than a merge. ## Decision Boundary The boundary between "safe to commit winner" and "must keep draining" is defined by a single predicate over the loser set: - **Commit** only when `∀ loser L: L.state == QUIESCENT`, where `QUIESCENT` means (no in-flight tool calls) ∧ (no unflushed buffered writes) ∧ (drain completed before its deadline). - **Block and escalate** when any loser reached `DRAIN_TIMEOUT` but its in-flight set is non-empty. This is not a soft failure. Committing here is the resurrection path. - **Reconcile, do not commit**, when a loser is un-fenceable and may still land effects. The winner's commit must be preceded by a substrate re-read that confirms no loser-authored hunk is present, and any hunk that appears after commit must trigger rollback of the *entire* speculative transaction, not a partial merge. The trap is treating `ABORTED` as a terminal state. It is a *transitional* state. The terminal state is `QUIESCENT`, and it is only reachable after drain. An orchestrator that conflates the two has a decision boundary that is off by one phase — and that off-by-one is exactly the width of the resurrection window. ## Operational Effect With the two-phase drain and fence-token invariant enforced, speculative multi-agent execution becomes *transactionally* safe at the cost of a bounded latency penalty: the winner's commit is delayed by the slowest loser's drain, typically one tool-call round-trip. The system trades a small, predictable tail-latency increase for elimination of silent post-commit corruption. Without it, the system exhibits a failure mode that is worse than no speculation at all: it produces trees that are neither the winner's nor any single loser's, and it does so *silently*, because every component reports success. The corruption is only detectable by post-hoc diffing, and by then the commit is durable and downstream agents have read from it. The operational lesson is that rollback in agent systems is not a state flag — it is a proof obligation, and the proof must be discharged against the tool executor's in-flight set, not against the agent loop's cancellation flag. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Callable class ResurrectionFault(RuntimeError): """Raised when a winner commit would be serialized while a loser branch still has in-flight or unflushed side effects that could land afterward.""" pass class BranchState(Enum): RUNNING = "running" ABORTED = "aborted" # cancellation flag set; NOT terminal QUIESCENT = "quiescent" # terminal: no in-flight calls, no buffered writes DRAIN_TIMEOUT = "drain_timeout" @dataclass class Branch: name: str state: BranchState = BranchState.RUNNING in_flight_calls: int = 0 buffered_writes: int = 0 fence_token: str = "" def signal_abort(self) -> None: # Phase one: stop new dispatches. Does NOT await in-flight work. if self.state == BranchState.RUNNING: self.state = BranchState.ABORTED def drain(self, deadline_s: float) -> None: # Phase two: await in-flight calls and flush buffered writes. start = time.monotonic() while self.in_flight_calls > 0 or self.buffered_writes > 0: if time.monotonic() - start > deadline_s: self.state = BranchState.DRAIN_TIMEOUT return time.sleep(0.001) # in production: await executor futures if self.in_flight_calls > 0: self.in_flight_calls -= 1 # simulated completion self.state = BranchState.QUIESCENT def commit_winner( winner: Branch, losers: list[Branch], drain_deadline_s: float, serialize_commit: Callable[[Branch], None], reconcile_substrate: Callable[[], list[str]], ) -> None: # Two-phase abort: signal all losers, then drain all losers. for loser in losers: loser.signal_abort() for loser in losers: loser.drain(drain_deadline_s) # Invariant: winner commit is fenced behind universal loser quiescence. non_quiescent = [b for b in losers if b.state != BranchState.QUIESCENT] if non_quiescent: names = ", ".join(f"{b.name}:{b.state.value}" for b in non_quiescent) raise ResurrectionFault( f"refusing to serialize winner '{winner.name}'; " f"losers not quiescent: {names}. " f"Committing here risks orphaned branch commits resurrecting " f"after rollback." ) serialize_commit(winner) # Post-commit reconciliation: any unexpected hunk is a hard fault. unexpected = reconcile_substrate() if unexpected: raise ResurrectionFault( f"post-commit substrate contains unexpected hunks: {unexpected}. " f"Fence token may have failed; roll back entire speculative txn." ) ```