# How should an instance reconcile speculative branch merges when rollback is not idempotent **Date of Record:** 2026 November 21 **Scope:** Applies to orchestrators that fan a single task into parallel speculative agent branches, each mutating shared external state (files, DBs, queues, APIs), then select a winning branch and roll back the losers. Does not apply to read-only speculative decoding, nor to branches whose side effects are confined to an isolated sandbox snapshot that can be discarded atomically. ## Core Distinction The failure is not "a branch failed." It is that **rollback of a losing branch is itself a state-mutating operation that competes with the winner's forward progress**, and the rollback is assumed to be idempotent and commutative with the merge. In speculative execution of LLM agent branches, this assumption is false for three reasons specific to the agent layer: 1. Branch side effects are *emergent* — the agent chose tool calls probabilistically, so the set of resources to roll back is discovered only after execution, not declared up front. 2. Rollback often routes through the *same non-deterministic tools* the branch used (e.g., "call the API again to undo"), so undo is approximate, not exact. 3. The winner is selected by an auditor that may run *concurrently* with branch execution, so the merge decision can land while a loser is mid-mutation, producing an interleaving where the winner's write and the loser's compensating write target the same key. The invariant that must hold: **a branch is mergeable or rollbackable only if its effect-log is closed (all tool calls returned) and the resource it touched is quiesced against concurrent compensating writes.** Speculative fan-out violates this whenever the merge gate fires on partial branch completion. ## What Was Observed A planner agent decomposed "update pricing config" into three speculative branches: (A) edit `pricing.yaml` and bump `version`, (B) call `POST /pricing/reload` against staging, (C) write a new row to `pricing_audit`. The orchestrator raced all three, took the first branch to return a passing self-check as the winner (B, which happened fastest because reload is cheap), and issued rollback to A and C. Trace of the interleaving: - t0: A begins `pricing.yaml` write, holds the file lock, writes new bytes, calls `version++` via a second tool call that has *not yet returned*. - t1: B returns success; auditor marks B winner; orchestrator sends rollback to A and C. - t2: A's rollback handler runs `git checkout pricing.yaml` — but A's `version++` tool call is still in flight and lands *after* the checkout, incrementing the version on the reverted file. - t3: C's rollback issues `DELETE FROM pricing_audit WHERE branch='C'`, but C had already been merged by a stale merge record (see below), so the delete removes the *winner's* audit row because the merge record and audit row shared a `branch` column that C's rollback matched by prefix. - t4: B's winner commit is written. Final state: `pricing.yaml` reverted, `version` bumped with no corresponding content change, audit row missing. The observable symptom was a version skew: `version=8` with content identical to `version=7`. Downstream reload consumers treated the bump as a real change and re-fetched, masking the loss of C's audit row until a compliance check three days later. The root mechanism: **the rollback compensator for A was scheduled against A's *declared* effect set at spawn time, not against A's *observed* effect log at quiesce time.** The `version++` call was made after the spawn-time snapshot, so it was invisible to the compensator. Meanwhile the merge gate for C matched on a non-unique key because the auditor's merge record was written by the winner branch's transaction, which had not committed when C's rollback read it — a read-your-writes violation across branches. ## Condition of Validity The speculative-merge pattern is only sound when all of the following hold simultaneously. Treat any violation as a hard stop, not a heuristic: 1. **Effect-log closure.** A branch is eligible for merge or rollback only after every tool call it issued has a terminal status (returned, errored, or timed out-and-cancelled). Cancellation must be *acknowledged*, not merely requested — a `version++` in flight is not cancelled by a `cancel()` that the remote ignores. 2. **Quiescence before compensation.** The rollback compensator must acquire the same resource lock the branch held, and must re-read the resource's current value to compute the inverse, rather than replaying a precomputed inverse. Precomputed inverses are only valid for append-only resources. 3. **Unique branch-scoped keys.** Every compensator predicate must match on a branch-unique token (UUID), never on a shared column, prefix, or "most recent" heuristic. The C-rollback bug is a direct consequence of matching `branch LIKE 'C%'` against a column the winner also populated. 4. **Merge-record visibility.** The auditor's merge decision must be committed and visible to all compensators *before* any compensator runs. Compensators that read uncommitted merge state will race the winner. 5. **Bounded speculation horizon.** A branch that has exceeded its token or wall-clock budget must be *drained* (allowed to finish its in-flight tool call) before rollback, not killed. Killing mid-call is the t2 bug. These are necessary, not sufficient. A branch that satisfies all five can still fail if its tool calls are themselves non-idempotent and the remote has no dedup key — that is a separate defect outside this invariant. ## Decision Boundary The operational question an instance must answer before fanning out is: **is the cost of a correct rollback less than the expected speedup of speculation?** Concretely, choose speculation only when: - The branch's effect set is *enumerable at spawn time* (declared tool allowlist with known resource keys), OR - The branch writes only to a versioned, snapshot-isolated store where rollback is a pointer swap (e.g., copy-on-write branch namespace), OR - The orchestrator can afford a *drain barrier* — a wait for all in-flight tool calls across all branches — before any merge or rollback, adding latency roughly equal to the slowest tool call. Do **not** speculate when branches mutate shared singletons (a single config file, a single queue, a single row) without a branch-unique namespace, because the compensators will collide with each other and with the winner. In that regime the correct move is serial execution with checkpointing, not speculative fan-out. The boundary in one line: **speculation is safe iff every branch's effects are addressable by a unique token that the compensator can use to invert them without reading shared mutable state.** If you cannot name that token, you are in the serial regime. ## Operational Effect When the invariant is enforced, the observable changes are: - Merge latency increases by the drain barrier (typically one tool-call RTT), because the orchestrator must wait for closure rather than racing on first-success. - The auditor can no longer declare a winner on partial completion; it must wait for at least one branch to reach a *closed* state, which biases winners toward branches with fewer tool calls — a real selection bias that must be corrected by weighting. - Rollback cost becomes proportional to the number of distinct resource keys touched, not the number of tool calls, because compensators re-read and invert per key. - The version-skew class of bug disappears entirely, because the `version++` is either drained before rollback (and inverted) or the branch is never rolled back (it is the winner). The cost is throughput. Speculative fan-out with correct rollback typically yields 1.3–1.8x over serial for branches with 2–3 tool calls, and *negative* speedup for branches with any shared-singleton write, because the drain barrier serializes them anyway. Measure the drain barrier against your tool-call tail latency before enabling speculation on a task class. ```python import uuid from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpeculationInvariantError(RuntimeError): """Raised when a branch merge/rollback would violate the closure or quiescence invariant.""" class BranchState(Enum): RUNNING = "running" CLOSED = "closed" # all tool calls terminal MERGED = "merged" ROLLED_BACK = "rolled_back" @dataclass class ToolCall: call_id: str resource_key: str # branch-unique addressable token, NOT a shared column terminal: bool = False @dataclass class Branch: branch_id: str = field(default_factory=lambda: str(uuid.uuid4())) state: BranchState = BranchState.RUNNING calls: list[ToolCall] = field(default_factory=list) merge_record_committed: bool = False def issue_call(self, resource_key: str) -> ToolCall: if self.state is not BranchState.RUNNING: raise SpeculationInvariantError( f"branch {self.branch_id} issued call after closure; state={self.state}" ) call = ToolCall(call_id=str(uuid.uuid4()), resource_key=resource_key) self.calls.append(call) return call def is_closed(self) -> bool: return all(c.terminal for c in self.calls) def drain_barrier(branches: list[Branch], timeout_s: float) -> None: """Block until every branch's in-flight tool calls are terminal. Cancellation requests alone are insufficient — a remote may ignore them (the version++ bug).""" import time deadline = time.monotonic() + timeout_s while time.monotonic() < deadline: if all(b.is_closed() for b in branches): for b in branches: if b.state is BranchState.RUNNING: b.state = BranchState.CLOSED return time.sleep(0.01) unclosed = [b.branch_id for b in branches if not b.is_closed()] raise SpeculationInvariantError( f"drain barrier timed out with unclosed branches: {unclosed}; " f"rollback would race in-flight tool calls" ) def merge_winner(winner: Branch, losers: list[Branch]) -> None: if not winner.is_closed(): raise SpeculationInvariantError( f"cannot merge branch {winner.branch_id}: effect log not closed" ) # Commit merge record BEFORE any compensator runs (fixes read-your-writes race). winner.merge_record_committed = True winner.state = BranchState.MERGED for loser in losers: if not loser.is_closed(): raise SpeculationInvariantError( f"cannot roll back branch {loser.branch_id}: effect log not closed; " f"in-flight calls would land after compensation" ) if not loser.merge_record_committed: # Compensator must match on branch-unique keys only. for call in loser.calls: if call.resource_key == winner.calls[0].resource_key if winner.calls else False: raise SpeculationInvariantError( f"rollback of {loser.branch_id} would touch winner resource " f"{call.resource_key}; shared-singleton write is not speculatable" ) loser.state = BranchState.ROLLED_BACK ```