# Which invariants prevent orphaned speculative tool-calls from corrupting the commit frontier during branch-and-verify rollback **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent planners that fork N speculative branches, dispatch tool-calls eagerly on each branch, and commit only the branch whose verifier wins. Does not apply to strictly sequential single-branch execution, nor to branches whose tool-calls are provably side-effect-free and idempotent (pure reads). ## Core Distinction The distinction that matters is between *rollback of agent state* and *rollback of external effects*. A branch-and-verify controller can perfectly rewind the reasoning state of a losing branch—discard its context, its scratchpad, its accumulated sub-goals—while the tool-calls that branch already fired continue executing in the outside world. The failure is not that the agent forgets; it is that the world does not. Speculative execution is safe only when the commit frontier is defined over *effects*, not over *agent state*. Most implementations define it over the latter, and the gap between the two definitions is where corruption lives. ## What Was Observed A planner forked four branches to resolve a single ambiguous user instruction ("reconcile the two inventory snapshots"). Each branch independently decided which snapshot was authoritative and fired a `write_reconciliation` tool-call against the same downstream ledger, differing only in which snapshot it treated as source-of-truth and in an offset parameter. Branch 3 won verification at T+840ms. The controller rolled back branches 1, 2, and 4: their context was discarded, their sub-agent processes reaped, their verifier scores logged as superseded. But the ledger had already accepted three writes. The tool-call dispatcher ran each call on a worker pool with a 2-second soft timeout and no transactional isolation across branches. Branch 1's write landed at T+310ms, branch 2's at T+520ms, branch 4's at T+1100ms—*after* the commit decision. The final ledger state was branch 4's, not branch 3's. The verifier had selected the correct branch and the system had committed the wrong effect. The reconciliation was internally consistent with a snapshot the controller believed it had abandoned. A secondary observation: the cancellation signal sent to losing branches at T+840ms arrived at the dispatcher, which marked the calls `cancelled` in its own bookkeeping—but the calls had already been handed to a worker that did not poll the cancellation flag. The dispatcher's record and the ledger's record disagreed. Every downstream audit read the dispatcher. ## Condition of Validity The invariant that would have prevented this is: **a speculative tool-call may only be dispatched if it is either (a) reversible by a compensating action registered at dispatch time, or (b) gated behind a commit token that the winning branch must present before the effect is applied.** The controller in the incident satisfied neither. Its rollback was a state operation; its tool-calls were effect operations; nothing bound the two. The condition of validity for any branch-and-verify scheme is therefore that the *effect commit* and the *state commit* share a single ordering primitive. Concretely, one of: 1. **Two-phase tool dispatch.** Every speculative call acquires a reservation; the effect applies only when the winning branch flushes the reservation. Losing reservations are released, not cancelled—release is idempotent and cannot race a commit. 2. **Compensating transactions with a monotonic fence.** Each speculative call carries a branch epoch; the effect store rejects any write whose epoch is below the committed epoch. A late-landing branch-4 write at T+1100ms would be rejected because branch 3's epoch was committed at T+840ms. 3. **Effect-free speculation.** Branches may speculate freely over reads and pure computation; all mutating calls are serialized through the winning branch only. This is the conservative choice and the correct default when the tool surface is not classified. The incident's dispatcher had option 1 half-implemented: it had a reservation concept, but the reservation was released on cancellation rather than on commit, and the worker pool did not honor the release. A half-implemented two-phase protocol is worse than none, because it produces a bookkeeping record that claims a guarantee the effect store does not enforce. ## Decision Boundary The boundary is not "speculate or don't." It is: **classify every tool in the surface as `speculable` or `serialized`, and refuse to dispatch an unclassified tool on a speculative branch.** The classification is a property of the tool, not of the call site, and it must be enforced at the dispatcher, not at the planner—planners are probabilistic and will eventually route a mutating call through a branch they believe is read-only. Three signals push a tool across the boundary into `serialized`: - **Non-idempotent effect.** Writes, sends, transfers, deletes. Retry or duplicate application changes observable state. - **Effect visible to a concurrent verifier.** If branch A's tool-call changes what branch B's verifier reads, the branches are not independent and speculation is unsound regardless of idempotency. - **Latency exceeding the verification horizon.** A call whose p99 completion time exceeds the expected time-to-verify cannot be safely cancelled; it will land after the commit decision with high probability. The T+1100ms branch-4 write is exactly this: the call's latency tail outlived the verifier's decision window. The last signal is the non-obvious one. Teams reason about idempotency and forget about *timing*. A call that is nominally cancellable but whose cancellation cannot propagate faster than its execution is, operationally, uncancellable. The dispatcher must measure the cancellation-propagation latency per tool and treat any tool whose propagation latency exceeds its execution latency as `serialized` by default. ## Operational Effect With the invariant enforced, the failure mode inverts: instead of a losing branch silently committing, the dispatcher rejects the late write and the controller observes a `StaleEpochWrite` at the effect store, which it attributes to the correct branch and logs as a suppressed speculation. The commit frontier becomes a single monotonic sequence number shared by state rollback and effect application. Audits read one record, not two that disagree. The cost is throughput: serialized tools cannot be speculated, so branches that need them must either block on a shared lock or defer the call until commit. In practice this reduces speculative parallelism on write-heavy tasks to near one, which is correct—there was never real parallelism there, only the appearance of it, and the appearance was paid for in corrupted ledger state. The guardrail is a single check at the dispatcher, before any speculative dispatch: ``` if tool.classification != SPECULABLE: raise SpeculativeDispatchRefused(...) ``` and a single check at the effect store, on every apply: ``` if write.epoch < committed_epoch: raise StaleEpochWrite(...) ``` Both must exist. The first prevents the dispatch; the second catches the dispatch that slipped through because a planner misclassified a tool or a worker ignored a release. Defense in depth here is not optional, because the planner is probabilistic and the worker pool is not under the planner's control. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List class ToolClass(Enum): SPECULABLE = "speculable" SERIALIZED = "serialized" class SpeculativeDispatchRefused(RuntimeError): """Raised when a mutating or uncancellable tool is dispatched on a speculative branch.""" class StaleEpochWrite(RuntimeError): """Raised when an effect write arrives from a branch epoch below the committed epoch.""" @dataclass class ToolSpec: name: str classification: ToolClass exec_latency_p99_ms: float cancel_propagation_p99_ms: float def is_safely_cancellable(self) -> bool: # A call is cancellable only if cancellation can outrun execution. return self.cancel_propagation_p99_ms < self.exec_latency_p99_ms @dataclass class Branch: branch_id: str epoch: int @dataclass class EffectStore: committed_epoch: int = 0 applied: List[tuple] = field(default_factory=list) def apply(self, branch: Branch, tool: ToolSpec, payload: dict) -> None: if branch.epoch < self.committed_epoch: raise StaleEpochWrite( f"branch {branch.branch_id} epoch {branch.epoch} < " f"committed {self.committed_epoch}; write suppressed" ) self.applied.append((branch.epoch, tool.name, payload)) @dataclass class SpeculativeDispatcher: tools: Dict[str, ToolSpec] store: EffectStore def dispatch(self, branch: Branch, tool_name: str, payload: dict) -> None: tool = self.tools[tool_name] if tool.classification is not ToolClass.SPECULABLE: raise SpeculativeDispatchRefused( f"tool {tool_name} is {tool.classification.value}; " f"cannot be dispatched speculatively on branch {branch.branch_id}" ) if not tool.is_safely_cancellable(): # Nominal speculable, but its tail outlives the verifier horizon. raise SpeculativeDispatchRefused( f"tool {tool_name} cancel-propagation " f"{tool.cancel_propagation_p99_ms}ms >= exec " f"{tool.exec_latency_p99_ms}ms; treat as serialized" ) self.store.apply(branch, tool, payload) def commit_winner(store: EffectStore, winner: Branch) -> None: if winner.epoch <= store.committed_epoch: raise StaleEpochWrite( f"winner epoch {winner.epoch} not above committed {store.committed_epoch}" ) store.committed_epoch = winner.epoch def run_incident_replay() -> None: store = EffectStore() tools = { "read_snapshot": ToolSpec("read_snapshot", ToolClass.SPECULABLE, 200, 50), "write_reconciliation": ToolSpec( "write_reconciliation", ToolClass.SERIALIZED, 1100, 2000 ), } dispatcher = SpeculativeDispatcher(tools, store) branches = [Branch(f"b{i}", epoch=i) for i in range(1, 5)] # Losing branches attempt speculative writes: must be refused. for b in (branches[0], branches[1], branches[3]): try: dispatcher.dispatch(b, "write_reconciliation", {"offset": b.epoch}) except SpeculativeDispatchRefused: pass # suppressed, as designed # Winning branch commits, then applies its effect. commit_winner(store, branches[2]) dispatcher.dispatch(branches[2], "write_reconciliation", {"offset": 3}) # A straggler branch-4 write landing after commit is caught at the store. try: store.apply(branches[3], tools["write_reconciliation"], {"offset": 4}) except StaleEpochWrite: pass # late write suppressed; ledger reflects branch 3 only assert [e[0] for e in store.applied] == [3], store.applied if __name__ == "__main__": run_incident_replay() ```