# What structural signals indicate speculative tool-call cancellation has orphaned a verified branch: the rollback-ordering invariant in branch-and-verify multi-agent execution **Date of Record:** 2026 November 21 **Scope:** Applies to orchestrators that execute multiple speculative agent branches concurrently, each branch emitting side-effecting tool calls, then commit one branch and roll back the losers via compensating cancellation. Does not cover single-branch execution, read-only tool surfaces, or systems where tool calls are transactional at the transport layer (e.g., two-phase-commit RPC). ## Core Distinction The failure is not "a speculative branch was cancelled." It is a **rollback-ordering inversion**: the verifier commits branch *W* (the winner) and emits cancellation signals to loser branches *L₁…Lₙ*, but a loser's in-flight tool call *completes* after the winner's commit point and its side effect is not idempotently reversible. The distinguishing signal is not an error code — cancellation acknowledgements arrive clean. The structural signal is that **the winner's post-commit read set diverges from what the verifier's replay predicted**, because a loser mutated shared state (a file, a cache key, a remote resource, a scratch directory) between the verifier's snapshot and the commit fence. Contrast with benign speculative cancellation: a loser is cancelled *before* its tool call is dispatched (drained from the queue), or its tool call is provably side-effect-free, or the compensation handler runs strictly after the loser's tool call has been observed terminal. In all benign cases, commit-fence ordering is preserved: **no loser effect is visible to any winner effect**. The pathology is a violation of that fence, not a cancellation at all. ## What Was Observed A verifier agent scored three speculative branches exploring a schema migration. Branch B2 (loser) issued a `apply_patch` tool call against a shared working tree; branch B1 (winner) issued `apply_patch` against the same tree. The orchestrator's commit protocol was: 1. Verifier selects winner B1, writes commit intent. 2. Orchestrator broadcasts `cancel` to B2 and B3. 3. Orchestrator awaits `cancel_ack` from each loser. 4. Orchestrator dispatches B1's tool calls. The `cancel_ack` from B2 arrived in 40 ms — it acknowledged the *cancellation request*, not the *terminal state* of B2's already-dispatched `apply_patch`. That tool call was sitting in a 900 ms remote queue. It landed at t+1.1 s, *after* B1's patch at t+0.6 s, and silently reverted two hunks of B1's edit because the patch tool computed its diff against the pre-B1 tree snapshot it had captured at dispatch time. Structural signals present in the trace, each individually ambiguous but jointly diagnostic: - **Commit fence skew**: `winner_commit_ts < loser_tool_terminal_ts` for at least one loser. The orchestrator logged `cancel_ack` as if it were terminal. - **Replay divergence**: the verifier's post-commit replay of B1's read set produced a hash `H_replay` that did not equal the live post-commit hash `H_live`. Divergence magnitude was exactly the loser's patch delta. - **Ack semantic mismatch**: loser ack payloads contained `state: "cancel_requested"`, not `state: "terminal"`. The orchestrator's state machine collapsed these two. - **Idempotency-key reuse**: B2's `apply_patch` carried a key derived from `(branch_id, step_index)` — distinct per branch, so no dedup collision fired. The key namespace was per-branch, which is correct for replay but wrong for cross-branch effect isolation. - **Snapshot staleness**: the tool's captured base revision was older than the winner's commit revision; the tool had no precondition check (`if_match` on base revision) so it applied blind. The tell that separates this from ordinary race conditions: **no component errored**. Every ack was 200. The corruption was only visible via replay-hash divergence, which the orchestrator was not computing. ## Condition of Validity This failure mode is bounded by three conditions, all of which must hold for the pathology to manifest: 1. **Shared mutable effect surface**: at least two branches can reach the same resource (working tree, KV namespace, remote object, rate-limited API quota) without per-branch isolation. Per-branch sandboxes (copy-on-write trees, namespaced caches) make this impossible and are the strongest guardrail. 2. **Ack-as-terminal conflation**: the orchestrator treats a cancellation *acknowledgement* as proof of *terminality*. This is only safe if the tool transport guarantees that any dispatched call either completes before ack or is provably aborted. Most queue-backed tool transports do not. 3. **Non-idempotent or base-revision-sensitive compensation**: the loser's tool call cannot be safely replayed or undone after the fact, or its undo would itself clobber the winner. `apply_patch` against a stale base is the canonical case; `increment_counter` is another. If any one fails, the pathology is prevented. The invariant to enforce is therefore: **commit fence precedes any loser terminality uncertainty**, i.e., the orchestrator must not dispatch winner effects until every loser tool call is *observed terminal* (not merely ack'd), or the effect surface must be partitioned per branch. ## Decision Boundary The operational choice is between two protocols, and the boundary between them is the **loser-tool-call terminality guarantee** offered by the transport: - **Optimistic commit** (dispatch winner immediately, cancel losers in parallel) is valid *only* when the effect surface is partitioned per branch or all loser tool calls are idempotent and base-revision-checked. Use when latency budget forbids waiting on loser drain and isolation is cheap. - **Fenced commit** (drain losers to terminal, then dispatch winner) is required when the effect surface is shared and loser compensation is not provably safe. Cost is bounded by the slowest loser tool call's tail latency; budget for p99, not p50 — the failure above was a 900 ms queue tail. The decision signal is not "is this a speculative system" but "**can I prove no loser effect is visible to a winner effect?**" If the answer requires inspecting tool implementations, you are on the wrong side of the boundary — move to per-branch isolation or fenced commit. A corollary boundary: replay-hash divergence checking is cheap and should be mandatory regardless of protocol, because it is the only signal that catches this class when the ack semantics are silently wrong. It converts an invisible corruption into a detectable one. ## Operational Effect Unmitigated, the effect is **silent post-commit corruption attributed to the winner**: the winning branch's output is wrong, the verifier's score was computed on a pre-corruption snapshot, and the trace shows a clean commit. Downstream agents inherit the corrupted state and their own replay checks (if any) diverge against a baseline that was never valid. Debugging converges on the winner's reasoning, which is innocent — the loser's late tool call is the cause, and it is not in the winner's trace at all. Mitigated, the cost is tail-latency on commit (fenced protocol) or per-branch storage/namespace overhead (isolation). The invariant that bounds the failure is: **no loser effect may be visible to any winner effect, and commit must be gated on loser terminality or effect-surface partitioning.** The diagnostic that detects violations is replay-hash divergence between the verifier's predicted post-commit read set and the live post-commit read set. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class RollbackOrderingViolation(RuntimeError): """Raised when a loser branch's tool effect is visible past the commit fence.""" pass @dataclass class ToolCall: branch_id: str step_index: int tool: str base_revision: str dispatched_ts: float terminal_ts: Optional[float] = None ack_state: str = "pending" # "pending" | "cancel_requested" | "terminal" @dataclass class Branch: branch_id: str calls: list = field(default_factory=list) is_winner: bool = False def assert_commit_fence( winner: Branch, losers: list, commit_ts: float, predicted_read_hash: str, live_read_hash: str, isolation_enabled: bool = False, ) -> None: """ Enforce the rollback-ordering invariant before accepting a speculative commit. Invariant: no loser tool effect may be visible to any winner effect. Two admissible proofs: (a) effect surface partitioned per branch (isolation_enabled), or (b) every loser tool call is observed terminal before commit_ts. Additionally require replay-hash agreement as a corruption detector. """ if not winner.is_winner: raise RollbackOrderingViolation( f"branch {winner.branch_id} is not marked winner; commit protocol misordered" ) if not isolation_enabled: for loser in losers: for call in loser.calls: # ack_state == "cancel_requested" is NOT terminality. if call.ack_state != "terminal" or call.terminal_ts is None: raise RollbackOrderingViolation( f"loser {loser.branch_id} call {call.tool}#{call.step_index} " f"not terminal at commit (ack_state={call.ack_state!r}); " f"fenced commit requires observed terminality" ) if call.terminal_ts > commit_ts: raise RollbackOrderingViolation( f"loser {loser.branch_id} call {call.tool}#{call.step_index} " f"terminal_ts={call.terminal_ts:.3f} > commit_ts={commit_ts:.3f}; " f"effect may be visible past commit fence" ) if predicted_read_hash != live_read_hash: raise RollbackOrderingViolation( f"post-commit replay divergence: predicted={predicted_read_hash[:12]} " f"live={live_read_hash[:12]}; a loser effect likely mutated shared state" ) def replay_hash(read_set: dict) -> str: canon = ";".join(f"{k}={read_set[k]}" for k in sorted(read_set)) return hashlib.sha256(canon.encode()).hexdigest() # --- Trace reconstruction from the observed incident ------------------------- winner = Branch("B1", is_winner=True) winner.calls.append(ToolCall("B1", 0, "apply_patch", "rev-100", dispatched_ts=0.55, terminal_ts=0.60, ack_state="terminal")) loser = Branch("B2") loser.calls.append(ToolCall("B2", 0, "apply_patch", "rev-100", dispatched_ts=0.20, terminal_ts=1.10, ack_state="terminal")) try: assert_commit_fence( winner=winner, losers=[loser], commit_ts=0.60, predicted_read_hash=replay_hash({"file.py": "B1-hunks"}), live_read_hash=replay_hash({"file.py": "B1-hunks-minus-2"}), isolation_enabled=False, ) except RollbackOrderingViolation as exc: # Expected: loser terminal at t+1.10 exceeded commit fence at t+0.60. print(f"BLOCKED: {exc}") raise RollbackOrderingViolation( "speculative commit rejected: rollback-ordering invariant violated; " "re-run under per-branch isolation or fenced commit" ) from exc ```