# In what scenarios must an instance abort a speculative branch before rollback reconciliation, and how does the "prune-before-commit" invariant prevent ghost side effects in branch-and-prune multi-agent rollouts? **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that spawn speculative agent branches executing optimistic tool calls against shared external state (filesystems, APIs, databases) and later prune losing branches via compensating rollback. Does not apply to purely read-only speculative decoding or single-agent retry loops with no external side effects. ## Core Distinction The failure mode here is not "a branch failed" or "rollback was slow." It is the **interleaving of prune-time rollback with sibling commit-time side effects on the same external resource**. In branch-and-prune rollouts, N speculative branches are launched optimistically; each may invoke tools with real side effects before the orchestrator has decided which branch wins. The naive invariant is "the winning branch commits, losers roll back." The correct invariant is stricter: **no branch may commit or roll back a side effect on resource R until all sibling branches that touched R have been pruned to a quiescent state.** This is the prune-before-commit invariant. The non-obvious boundary: rollback is itself a tool call. It has latency, it can fail, and it can be *reordered* relative to a sibling's forward write. If branch A writes `key=x` at t=10, branch B writes `key=y` at t=11, the orchestrator picks A, rolls back B at t=20 (deleting `key`), and A's commit is a no-op because it "already wrote" at t=10 — the resource now holds nothing. The winner's effect was silently annihilated by the loser's compensation. This is a ghost side effect: a committed intent with no surviving materialization. ## What Was Observed A three-way speculative rollout (planner, executor, verifier branches) shared a scratch object store. Each branch issued `put(key, value)` optimistically to avoid serialization latency. On selection, the orchestrator issued compensating `delete(key)` for the two losers, then marked the winner committed. Trace: - t=10 branch_A `put("artifact", A_v)` → ok - t=11 branch_B `put("artifact", B_v)` → ok (overwrites A) - t=12 branch_C `put("artifact", C_v)` → ok (overwrites B) - t=30 selection: A wins - t=31 rollback_B `delete("artifact")` → ok - t=32 rollback_C `delete("artifact")` → ok - t=33 commit_A: no-op (A's write already "succeeded" at t=10) - t=34 downstream verifier reads `artifact` → **KeyError / empty** The verifier branch, which had *read* at t=25 and cached `C_v`, then reported a stale mismatch against a now-empty store, triggering a spurious consensus failure. Two independent failures (lost winner effect, stale read) compounded from one ordering defect. A second observation: when rollback_B failed with a transient 503 and was retried at t=40 *after* commit_A's downstream consumer had already read the key, the retry deleted the winner's materialization mid-consumption. Rollback retries are not idempotent with respect to interleaved commits unless fenced by a generation token. ## Condition of Validity The prune-before-commit invariant is *required* when and only when all three hold: 1. **Shared mutable resource**: two or more branches can write the same key/resource identity. 2. **Optimistic pre-commit writes**: branches perform side effects before selection (else there is nothing to roll back). 3. **Asynchronous or retried compensation**: rollback is a network call that can reorder, fail, or retry. If any condition is absent — e.g., branches write to disjoint namespaced keys (no shared identity), or all writes are staged in a transaction buffer and only flushed post-selection — the invariant is unnecessary and the cheaper "commit winner, discard buffer" model applies. The dangerous middle ground is *namespaced writes with a shared read path*: branches write `branch_A/artifact` but the verifier reads `artifact` via a resolving alias. That alias collapses the disjointness and reinstates the hazard. ## Decision Boundary The orchestrator must treat the boundary between **prune quiescence** and **commit** as a hard fence, not a soft ordering hint: - **Abort-before-commit trigger**: if any losing branch's rollback is unresolved (in-flight, retrying, or failed) at commit time, the orchestrator MUST NOT commit the winner against the shared resource. It must either (a) block commit until all sibling rollbacks reach terminal state, or (b) if blocking exceeds the budget, abort the entire rollout and surface a `ReconciliationIncomplete` fault rather than commit into an unresolved compensation window. - **Fencing requirement**: every write and compensating delete must carry a monotonically increasing generation token; a rollback whose token is older than a subsequent commit's token must be rejected by the resource, not applied. This converts reordering from silent corruption into a detectable conflict. - **Read-path isolation**: verifier/auditor branches must read through a snapshot pinned at selection time, never through the live alias, or their consensus is invalid by construction. The decision to *abort* (rather than wait) is correct when rollback latency variance exceeds the remaining token/time budget of the rollout — waiting converts a bounded failure into budget exhaustion, which is worse because it leaves the resource in an unknown state with no fault record. ## Operational Effect Enforcing prune-before-commit converts a class of silent, hard-to-attribute failures (lost winner effects, stale-read consensus mismatches, mid-consumption deletions from retried rollbacks) into a single explicit fault at the orchestration layer. The cost is reduced speculation parallelism on contended resources — branches touching the same key serialize at the prune fence. The benefit is that every committed side effect is guaranteed to have survived all sibling compensation, and every aborted rollout leaves a reconcilable audit trail rather than a corrupted resource. The invariant does not prevent rollback failures; it prevents rollback failures from masquerading as successful commits. ```python import time from dataclasses import dataclass, field from typing import Dict, List, Optional class ReconciliationIncomplete(RuntimeError): """Raised when commit is attempted while sibling rollbacks are unresolved.""" pass class StaleGenerationWrite(RuntimeError): """Raised when a write/delete carries a generation older than the resource's.""" pass @dataclass class Branch: name: str generation: int touched: List[str] = field(default_factory=list) @dataclass class Resource: # key -> (generation, value) store: Dict[str, tuple] = field(default_factory=dict) def put(self, key: str, value, generation: int) -> None: cur = self.store.get(key) if cur is not None and generation < cur[0]: raise StaleGenerationWrite( f"put({key}) gen={generation} < resource gen={cur[0]}" ) self.store[key] = (generation, value) def delete(self, key: str, generation: int) -> None: cur = self.store.get(key) if cur is None: return if generation < cur[0]: raise StaleGenerationWrite( f"delete({key}) gen={generation} < resource gen={cur[0]}" ) del self.store[key] def reconcile_and_commit( resource: Resource, winner: Branch, losers: List[Branch], rollback_status: Dict[str, str], # branch -> "done" | "inflight" | "failed" budget_exhausted: bool, ) -> None: # Hard fence: no commit until every loser is quiescent. unresolved = [b.name for b in losers if rollback_status.get(b.name) != "done"] if unresolved: if budget_exhausted: raise ReconciliationIncomplete( f"aborting rollout: unresolved rollbacks {unresolved} " f"and budget exhausted; refusing to commit into open compensation window" ) raise ReconciliationIncomplete( f"commit blocked: siblings {unresolved} not pruned to quiescence" ) # Losers' deletes already applied under their generations; winner commits # under a strictly later generation so fencing is well-ordered. commit_gen = winner.generation + 1000 for key in winner.touched: resource.put(key, f"{winner.name}_value", commit_gen) ```