# Which invariants prevent orphaned speculative branches from committing after a sibling branch has already materialized side effects **Date of Record:** 2026 November 24 **Scope:** Applies to orchestrators that fan out one logical task across N parallel speculative branches (rollouts) sharing an external tool/effect surface, then arbitrate a single winner via commit/abort. Does not apply to branches whose tool calls are fully sandboxed and side-effect-free, nor to single-branch retry loops. ## Core Distinction The distinction that matters here is not "which branch won" but **when a branch's external effects became irreversible relative to the arbitration decision**. Speculative execution is only sound if commit/abort is a decision over *reversible* state. The failure mode is a **commit-after-effect inversion**: a losing branch (or a branch still in flight) performs an irreversible tool call — a write, a payment, an outbound message, a file mutation — *before* the arbiter has selected a winner, and the abort signal arrives after the effect has already leaked into the shared world state. This is distinct from ordinary divergence. Divergence (two branches reaching different conclusions) is expected and is the entire point of speculation. The pathology is that the arbiter's abort is *advisory* to a branch that has already crossed the effect boundary. Once crossed, abort cannot un-cross it, so the "single winner" invariant silently degrades into "single winner plus K-1 leaked side effects." ## What Was Observed A three-way fan-out (`N=3`) over a task requiring a `transfer_funds` tool call. Each branch ran the same reasoning scaffold with temperature-sampled variation. The arbiter scored branch outputs and selected branch B on a confidence margin over A and C. Trace of the inversion: 1. `t0` — all three branches dispatched, each with a local scratchpad and a shared `EffectGateway` handle. 2. `t1` — branch A reaches the tool call first. It calls `transfer_funds(amount=40)`. The gateway executes; the ledger now reflects a 40-unit debit. 3. `t2` — branch C calls `transfer_funds(amount=40)`; executes; second debit. 4. `t3` — branch B, the eventual winner, calls `transfer_funds(amount=40)`; executes; third debit. 5. `t4` — arbiter scores and commits B, aborts A and C. 6. `t5` — abort messages are delivered. A and C mark themselves `ABORTED` and stop. The ledger shows three debits for a task that intended one. The arbiter behaved correctly. The branches behaved correctly relative to their local view. The **invariant that failed was implicit**: nothing enforced that `commit` precede `effect`. The gateway had no notion of a branch's arbitration status, so it treated each speculative branch as an authorized principal. A second, subtler variant appeared under latency skew: when branch A stalled in reasoning, its tool call landed at `t3.5`, *after* B had been committed. The abort for A was generated at `t4` but A's effect committed at `t3.5` — an effect from a branch that was, at commit time, already logically dead. The window between "arbiter decides" and "aborted branch observes abort" is where all leakage happens. ## Condition of Validity The single-winner invariant holds **iff** for every branch `b` and every irreversible effect `e(b)`: ``` materialize(e(b)) ⟹ commit(b) ∧ ¬abort(b) ∧ (∀ b' ≠ b : ¬materialize(e(b'))) ``` i.e. an effect may only materialize if its originating branch is the committed winner and no sibling has materialized a conflicting effect. This requires two mechanisms that speculative fan-out does not get for free: - **Effect gating on arbitration state.** The gateway must refuse to materialize any effect whose originating branch has not received a `COMMIT` token. Speculative branches operate in a *provisional* mode: their tool calls are recorded as intents, not executed. Materialization is a separate, arbiter-driven phase. - **Two-phase effect commit with abort fencing.** Provisional intents from losing branches are discarded, not executed. The committed branch's intents are drained to the real surface only after the commit decision is durable. An abort must be a *fence* (branch can no longer materialize) rather than a *request* (branch is asked to stop). The invariant is **invalid** whenever branches hold direct, un-mediated handles to the effect surface, or whenever the gateway authorizes on branch identity rather than on arbitration token. It is also invalid when the arbiter's commit and the branches' effect attempts are not ordered by a shared logical clock — wall-clock ordering is insufficient because a stalled branch can reorder relative to commit. ## Decision Boundary The boundary between sound and unsound speculation is **the reversibility horizon of the tool surface**. Concretely: - If every tool a branch can reach is idempotent and reversible (pure reads, idempotent writes keyed by branch ID, draft-only messages), speculation may proceed without gating; the arbiter can reconcile after the fact. - If any reachable tool is irreversible or non-idempotent (payments, external sends, destructive writes, state machines with absorbing states), the branch **must not** be granted direct execution. It must go through provisional-intent gating, and the arbiter must own the drain-to-materialize step. The decision the orchestrator must make per tool, before fan-out, is: *is this tool safe to run speculatively?* If the answer is "no" for any tool on the path, the fan-out either (a) restricts branches to a read-only shadow of that tool and defers the effect to the committed branch's replay, or (b) serializes the effect-bearing segment and speculates only the reasoning around it. Cost-aware pruning interacts here: pruning a branch *before* it reaches the effect boundary is free; pruning it *after* is a leak. So the pruning policy must be aware of each branch's distance-to-effect, and must never let a branch cross the effect boundary while its commit probability is still being evaluated. ## Operational Effect When the invariant is enforced, the observable properties are: exactly one materialization per logical task; aborted branches produce zero external effects regardless of how far they reasoned; and the cost of speculation is bounded by reasoning tokens plus provisional-intent storage, never by duplicated side effects. The arbiter becomes the sole authority over the effect surface, and branch identity is decoupled from effect authority. When it is violated, the failure is *silent and compounding*: each leaked effect looks locally successful, so no branch reports an error; the orchestrator's logs show a clean single-winner commit; only the external ledger reveals multiplicity. Under retries the multiplicity multiplies, because a re-run of the fan-out re-leaks. The correct remediation is not to reduce `N` or lower temperature — that only shrinks the leak probability — but to move the effect surface behind arbitration gating and make abort a fence. Cost-aware pruning must be re-expressed as "prune before effect boundary," and any branch that has issued a provisional intent must be either committed or explicitly fenced-and-discarded, never merely told to stop. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum class SpeculativeCommitError(RuntimeError): """Raised when a speculative branch attempts an irreversible effect without a durable commit token, or when a fenced branch tries to materialize after abort.""" class BranchState(Enum): SPECULATING = "speculating" COMMITTED = "committed" ABORTED = "aborted" @dataclass class Branch: branch_id: str state: BranchState = BranchState.SPECULATING provisional_intents: list[str] = field(default_factory=list) materialized: list[str] = field(default_factory=list) class EffectGateway: """Two-phase effect surface: branches record provisional intents; only the committed branch drains them to the real world.""" def __init__(self) -> None: self._world: list[str] = [] self._committed_branch: str | None = None def record_intent(self, branch: Branch, effect: str) -> None: if branch.state is BranchState.ABORTED: # Fence: an aborted branch must never reach the effect surface. raise SpeculativeCommitError( f"branch {branch.branch_id} is fenced (ABORTED); " f"refusing to record effect {effect!r}" ) if branch.state is BranchState.COMMITTED: raise SpeculativeCommitError( f"branch {branch.branch_id} already committed; " f"further effects must go through replay, not speculation" ) branch.provisional_intents.append(effect) def commit(self, winner: Branch, losers: list[Branch]) -> None: # Ordering invariant: commit decision is durable before any drain, # and all losers are fenced before the winner materializes. if self._committed_branch is not None: raise SpeculativeCommitError( f"double commit: {self._committed_branch} already won" ) for loser in losers: loser.state = BranchState.ABORTED loser.provisional_intents.clear() # discard, do not execute winner.state = BranchState.COMMITTED self._committed_branch = winner.branch_id # Drain only after fencing losers. for effect in winner.provisional_intents: self._world.append(effect) winner.materialized.append(effect) winner.provisional_intents.clear() def world_state(self) -> list[str]: return list(self._world) def run_speculative_fanout( branches: list[Branch], effects_per_branch: dict[str, list[str]], scores: dict[str, float], gateway: EffectGateway, ) -> Branch: """Fan out, record provisional intents, arbitrate by score, then commit.""" for b in branches: for effect in effects_per_branch.get(b.branch_id, []): gateway.record_intent(b, effect) winner = max(branches, key=lambda b: scores[b.branch_id]) if winner.state is not BranchState.SPECULATING: raise SpeculativeCommitError( f"winner {winner.branch_id} is not in SPECULATING state" ) losers = [b for b in branches if b is not winner] gateway.commit(winner, losers) # Post-condition guard: exactly one materialization set, zero from losers. if any(b.materialized for b in losers): raise SpeculativeCommitError( "invariant violated: a losing branch materialized an effect" ) return winner ```