# Which invariants prevent speculative branch commits from poisoning sibling agents during rollback-and-winner arbitration **Date of Record:** 2026 November 25 **Scope:** Applies to systems where a coordinator agent forks N speculative execution branches from a shared checkpoint, each branch mutating tool state and its own episodic memory, then arbitrates a single winner whose effects are committed while losers are rolled back. Does not apply to strictly sequential single-branch execution or to read-only fan-out (map) patterns with no state mutation. ## Core Distinction Speculative multi-agent execution conflates two distinct notions of "state" that ordinary transactional systems keep separate: **branch-local working state** (episodic memory, scratch context, tool call logs) and **externally observable effects** (filesystem writes, API mutations, database rows, outbound messages). A rollback is only sound if every effect produced by a losing branch is either (a) buffered in a branch-scoped overlay that is discarded atomically, or (b) idempotently reversible by a compensating action recorded *before* the effect was applied. The failure mode this record addresses is the **orphaned-effect leak**: a losing branch commits an external side effect through a tool call whose result arrives *after* the arbiter has already selected a winner and begun rollback. The arbiter sees the branch as "dead" and skips its rollback journal, but the in-flight tool response lands on shared substrate and mutates state the winner will later read. The winner's subsequent reasoning is now conditioned on a world that includes a phantom write from a branch it never selected. The non-obvious part: this is not a race on the *commit* path. It is a race on the *rollback completeness check*. The arbiter's invariant "no losing branch has pending effects" is checked at arbitration time, but tool calls are asynchronous and their completion is not causally ordered with respect to the arbitration event. A branch can be marked `LOST` in the coordinator's ledger while its fifth tool call is still in flight. ## What Was Observed A coordinator model forked five branches of a code-refactoring task from a common checkpoint. Each branch was given the same context window plus a distinct "strategy hint" (e.g., "extract helper," "inline," "rename first"). Branches 1–4 completed and returned proposals. Branch 5 was slower — it issued a `apply_patch` tool call to a sandbox filesystem and then, while awaiting the response, the coordinator's arbitration timeout fired. The arbiter scored branches 1–4, selected branch 2, and initiated rollback of 1, 3, 4, and 5. Rollback iterated the coordinator's branch ledger and, for each loser, replayed its recorded journal of *completed* tool calls to generate compensating actions. Branch 5's ledger showed four completed calls and one `PENDING`. The rollback logic was written to skip `PENDING` entries — the assumption being that a pending call would either never complete (timeout) or complete into a branch-scoped buffer that would be discarded. Neither held: the `apply_patch` tool wrote directly to a shared sandbox mount, not a branch overlay. When the response arrived 800ms after rollback finished, the patch was applied to the sandbox. Branch 2's winner-commit then re-ran its own patch against the sandbox, which now contained branch 5's changes. The patch applied with fuzz, silently merging unrelated hunks. The committed result passed the coordinator's smoke test (the test set was too small to catch the contamination) but failed a later integration check. The failure trace was not "branch 5 did something wrong" — branch 5's patch was individually valid. The failure was that branch 2's *evaluation context* at commit time differed from its *evaluation context* at arbitration time, and the difference was invisible to the arbiter. A second, subtler observation: the arbiter's scoring for branch 2 was computed against a sandbox snapshot taken at fork time. The winner-commit re-executed against the *current* sandbox. The spec assumed evaluation and commit were against the same substrate; they were not. ## Condition of Validity The invariant required to prevent this is a **two-phase rollback barrier with quiescence proof**. Formally: a branch may be marked `ROLLED_BACK` only after (1) all its issued tool calls have reached a terminal state (success, failure, or explicit cancellation acknowledgement), and (2) all effects from those calls are either discarded (overlay) or compensated (journal replay). The arbiter must not declare a winner until every loser has reached `ROLLED_BACK`, not merely `LOST`. This is stronger than "wait for pending calls." It requires that the tool transport support **cancellation with acknowledgement** — the tool must confirm it will produce no further effects before the branch can be sealed. A timeout-based "assume it's dead" is not a quiescence proof; it is a bet that the bet will not be called. The second invariant is **evaluation-commit substrate identity**: the winner must commit against the exact substrate snapshot against which it was scored, or the commit must be re-validated against the current substrate with a diff check. If the substrate has changed since scoring (which it will have, because losers touched it), the commit is a *new* speculative step requiring its own arbitration, not a continuation of the old one. A third invariant, easy to miss: **branch-scoped effect namespacing**. Every external effect must carry a `branch_id` that the tool transport enforces at the substrate level (e.g., a per-branch write-ahead log with a single atomic flush on winner selection). If the tool cannot enforce this, the branch must be restricted to read-only tools during speculation. ## Decision Boundary The boundary between safe and unsafe speculative execution is whether the tool surface is **effect-classified at registration time**. Tools must be tagged `READ_ONLY`, `OVERLAY_WRITABLE` (writes a branch-scoped buffer the runtime can discard), or `EXTERNAL` (writes to shared substrate). Speculation across `EXTERNAL` tools is only safe if the tool supports a `prepare/commit` protocol where `prepare` stages the effect and `commit` is issued by the arbiter for the winner only. If a tool is `EXTERNAL` and does not support `prepare/commit`, the branch that calls it must be **non-speculative**: it runs alone, or it runs last, after all other branches have been rolled back and the substrate is quiescent. Mixing speculative and non-speculative branches in one fork set is the specific configuration that produced the observed leak — the arbiter's rollback logic was written for overlay semantics but the tool set included an external writer. The decision rule: *a fork set is valid iff the intersection of (tools available to any branch) and (tools not supporting prepare/commit or branch-scoped overlay) is empty, OR the fork set is serialized at the point of first external write.* There is no middle ground where "most branches" are overlay-safe and one is not — the arbiter's rollback is a single code path and it is only as sound as its weakest tool. ## Operational Effect The practical consequence is that speculative multi-agent execution with rollback is a **transactional protocol**, not a search heuristic. The coordinator must treat the fork set as a distributed transaction with a two-phase commit at the arbitration boundary: phase one is "all branches quiesced and effects staged," phase two is "winner commits, losers' staged effects discarded." The arbiter's scoring is a read-only operation over staged snapshots; the commit is the only mutating operation and it is issued exactly once. Systems that skip the quiescence barrier — because it adds latency, because timeouts "usually" fire before responses arrive, because the tool set "mostly" uses overlays — will pass smoke tests and fail under load, because load is what makes the pending-call window wide enough for the late response to land after rollback. The failure is silent: the winner commits, tests pass, and the contamination surfaces as a regression attributed to the wrong branch weeks later. The guardrail is mechanical: the arbiter's `select_winner` function must not return until `all(b.state == ROLLED_BACK for b in losers)`, and `ROLLED_BACK` must be unreachable without a cancellation acknowledgement from every in-flight tool call on that branch. If the transport cannot produce that acknowledgement within the arbitration deadline, the fork set is aborted and re-run serially — not committed with a "best effort" rollback. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Callable class SpeculationInvariantViolation(RuntimeError): """Raised when a speculative fork set violates rollback or substrate invariants.""" class BranchState(str, Enum): RUNNING = "running" LOST = "lost" ROLLED_BACK = "rolled_back" WON = "won" class ToolClass(str, Enum): READ_ONLY = "read_only" OVERLAY_WRITABLE = "overlay_writable" EXTERNAL = "external" @dataclass class ToolCall: name: str tool_class: ToolClass supports_prepare_commit: bool terminal: bool = False cancelled_acked: bool = False @dataclass class Branch: branch_id: str state: BranchState = BranchState.RUNNING calls: list[ToolCall] = field(default_factory=list) def in_flight(self) -> list[ToolCall]: return [c for c in self.calls if not c.terminal and not c.cancelled_acked] @dataclass class ForkSet: branches: list[Branch] substrate_version_at_fork: int substrate_version_at_arbitration: int def validate_fork_set(fs: ForkSet) -> None: """Reject fork sets that mix speculative branches with non-stageable external writers.""" for b in fs.branches: for c in b.calls: if c.tool_class is ToolClass.EXTERNAL and not c.supports_prepare_commit: raise SpeculationInvariantViolation( f"branch {b.branch_id} issued non-stageable external call " f"{c.name!r}; fork set must be serialized at this point" ) def rollback_losers(fs: ForkSet, cancel: Callable[[ToolCall], bool]) -> None: """Drive every loser to ROLLED_BACK; refuse to seal on unacknowledged cancellation.""" for b in fs.branches: if b.state is not BranchState.LOST: continue for c in b.in_flight(): if not cancel(c): raise SpeculationInvariantViolation( f"branch {b.branch_id} call {c.name!r} did not acknowledge " f"cancellation; cannot seal rollback" ) c.cancelled_acked = True if b.in_flight(): raise SpeculationInvariantViolation( f"branch {b.branch_id} still has in-flight calls after cancel pass" ) b.state = BranchState.ROLLED_BACK def select_winner_and_commit(fs: ForkSet, winner_id: str) -> None: validate_fork_set(fs) losers = [b for b in fs.branches if b.branch_id != winner_id] for b in losers: b.state = BranchState.LOST # Quiescence barrier: no winner may be declared until every loser is sealed. rollback_losers(fs, cancel=lambda c: True) if any(b.state is not BranchState.ROLLED_BACK for b in losers): raise SpeculationInvariantViolation( "arbitration reached commit with unsealed loser branches" ) # Substrate identity invariant: scoring snapshot must match commit snapshot. if fs.substrate_version_at_fork != fs.substrate_version_at_arbitration: raise SpeculationInvariantViolation( f"substrate drifted from v{fs.substrate_version_at_fork} to " f"v{fs.substrate_version_at_arbitration} between fork and commit; " f"winner must be re-scored, not committed" ) winner = next(b for b in fs.branches if b.branch_id == winner_id) winner.state = BranchState.WON ```