# Which invariants prevent speculative branch rollouts from committing side effects that the verifier later rejects **Date of Record:** 2026 November 28 **Scope:** Applies to orchestration layers that fan out parallel speculative agent branches (tree-of-thought, best-of-N, parallel tool-calling) where branches may perform externally observable side effects and a downstream verifier selects a winner. Does not apply to read-only branches or to single-branch sequential execution with no rollback surface. ## Core Distinction The failure is not "a branch produced a wrong answer." It is the conflation of two different commit horizons: the **effect horizon** (when a tool call mutates the world) and the **selection horizon** (when the verifier picks a winner). Speculative execution is safe only when every branch's effect horizon is strictly ordered *after* the selection horizon, or when effects are made idempotent-and-reversible through a compensating ledger. Most implementations collapse these horizons by letting each branch call real tools eagerly, then "roll back" the losers—and rollback is where the invariant dies. The subtle part: the verifier itself is probabilistic. It does not return "branch 3 is correct." It returns a score distribution over branches, and the winner is often a tie-break at temperature > 0. So the set of branches that *should* be rolled back is not deterministically known even after verification completes. A branch that scored 0.71 vs 0.69 may be re-selected differently on a re-verification replay, which means the "loser" you rolled back might have been the winner under a slightly different verifier sample. ## What Was Observed A three-branch rollout was dispatched to resolve a refund dispute. Each branch was given the same task and permitted to call `issue_refund`, `send_email`, and `update_ledger`. All three branches eagerly executed `issue_refund` against the payment provider (a non-idempotent POST with a client-generated idempotency key that differed per branch). The verifier scored branches [0.62, 0.71, 0.68]; branch 2 won. The orchestrator then issued compensating `reverse_refund` calls for branches 1 and 3. Two things broke: 1. The `reverse_refund` for branch 1 succeeded, but branch 3's refund had already settled into a payout batch, so reversal returned `PENDING_MANUAL`. The orchestrator treated non-`OK` as "already handled" and dropped it. Net effect: one phantom refund survived. 2. On replay for audit, the verifier re-scored with a fresh sample and produced [0.70, 0.69, 0.72]—branch 3 now won. The audit trail claimed branch 2 was authoritative while the ledger reflected branch 3's side effect. Verification replay discrepancy was 0.03 in score but total in committed state. The trace shows the exact transition: `branch.execute(side_effect)` → `verifier.score(all)` → `select(argmax)` → `compensate(losers)`. The gap between `select` and `compensate` is where non-determinism, latency, and settlement windows inject unrecoverable divergence. ## Condition of Validity Speculative rollouts with side effects are valid **if and only if** all of the following hold simultaneously: - **Effect deferral:** branches execute against a *staged* effect journal, not the real world. The journal is a list of `(tool, args, idempotency_key)` tuples keyed by `(rollout_id, branch_id)`. No external call fires until commit. - **Deterministic selection:** the verifier's winner is a pure function of branch outputs, or the verifier is sampled with a fixed seed recorded in the journal so replay reproduces the same argmax. If selection is non-deterministic, the compensation set is undefined. - **Single commit point:** exactly one branch's journal is flushed to the real world after selection, inside a transaction or with a shared idempotency key so a retry cannot double-apply. - **Compensation is never needed** because nothing was committed for losers. If you find yourself writing `reverse_*` logic for speculative branches, you have already violated the invariant. The moment any branch fires a real, non-idempotent call before selection, the invariant is unrecoverable. Compensation is not rollback; it is a second side effect that can itself fail, settle late, or be reordered by the downstream system. ## Decision Boundary The boundary is between **speculate-then-commit** and **execute-then-compensate**. Choose speculate-then-commit when: tools are non-idempotent, downstream settlement is asynchronous, or the verifier is stochastic. Choose execute-then-compensate only when: every tool is idempotent under a stable key, compensation is synchronous and total, and the verifier is deterministic across replays. A concrete guard: before dispatching N branches, the orchestrator must assert `all(tool.speculative_safe for tool in branch.toolset)` where `speculative_safe` means the tool writes only to the staged journal. If any tool is not speculative-safe, the fan-out must be reduced to N=1 (no speculation) or the tool must be wrapped in a journal shim. The verifier must also emit a `selection_receipt` containing the sampled seed and per-branch scores, and the commit step must verify `receipt.seed == journal.seed` before flushing—otherwise a replay mismatch silently commits the wrong branch. ## Operational Effect With the invariant enforced, the failure mode disappears: losers never touch the world, so there is nothing to compensate and no settlement race. The cost is latency—you serialize the effect flush after verification—but you gain a replayable audit trail where `selection_receipt` + `effect_journal` fully reconstruct committed state. Without it, you get phantom side effects, replay-selection divergence, and an audit trail that disagrees with the ledger. The operational rule: **never let a speculative branch hold a real-world handle; give it a journal, and let exactly one journal cross the commit boundary after a seeded, receipted selection.** ```python import hashlib from dataclasses import dataclass, field from typing import Any class SpeculativeCommitViolation(RuntimeError): """Raised when a speculative branch attempts to cross the effect horizon before the selection horizon has produced a deterministic, receipted winner.""" @dataclass class SelectionReceipt: seed: int scores: list[float] winner: int def fingerprint(self) -> str: payload = f"{self.seed}:{self.scores}:{self.winner}".encode() return hashlib.sha256(payload).hexdigest() @dataclass class EffectJournal: rollout_id: str branch_id: int seed: int staged: list[tuple[str, dict[str, Any], str]] = field(default_factory=list) committed: bool = False def stage(self, tool: str, args: dict[str, Any], idem_key: str) -> None: if self.committed: raise SpeculativeCommitViolation( f"branch {self.branch_id} already committed; cannot stage further effects" ) self.staged.append((tool, args, idem_key)) def commit_winner( journals: list[EffectJournal], receipt: SelectionReceipt, journal_seed: int, ) -> EffectJournal: if receipt.seed != journal_seed: raise SpeculativeCommitViolation( f"selection receipt seed {receipt.seed} != journal seed {journal_seed}; " "replay divergence would commit the wrong branch" ) winners = [j for j in journals if j.branch_id == receipt.winner] if len(winners) != 1: raise SpeculativeCommitViolation( f"expected exactly one journal for winner {receipt.winner}, found {len(winners)}" ) for j in journals: if j.branch_id != receipt.winner and j.committed: raise SpeculativeCommitViolation( f"loser branch {j.branch_id} committed before selection; invariant broken" ) winner = winners[0] winner.committed = True return winner ```