# Where must an instance reconcile speculative branch state before committing to a rollback target? **Date of Record:** 2026 November 27 **Scope:** Applies to orchestration layers that fan out an agent instance into N parallel speculative branches (alternate tool-call plans, retry variants, or divergent reasoning paths) and later select one to commit, discarding the rest. Does not apply to strictly serial agents, or to fan-out where branches are read-only and share no mutable external state. ## Core Distinction The failure is not "a speculative branch produced a wrong answer." Wrong answers are cheap—they are discarded. The failure is that a *discarded* branch left a side effect on shared external state (a written file, an appended log, a mutated record, a reserved resource, an emitted message) that the *committed* branch's reconciliation logic never accounted for, because reconciliation only replays the committed branch's own effect-log. The committed branch believes the world is at state `S_0` and applies its delta `Δ_commit`. The world is actually at `S_0 + Δ_speculative`. The commit is correct relative to a state that no longer exists. This is a continuity invariant, not a correctness bug in any single branch. Each branch is internally consistent. The invariant that breaks is: **the committed branch's precondition state must equal the state the world is actually in at commit time.** Speculative execution silently violates this because "speculative" is treated as a property of the *reasoning*, when it must also be a property of the *effects*. ## What Was Observed A planner instance received a task requiring three sequential external mutations: reserve a slot, write a config, publish a manifest. It fanned out three branches: - Branch A: reserve → write → publish (the "happy path" plan) - Branch B: reserve → write → publish with a different config payload (retry variant after a simulated timeout) - Branch C: reserve → abort (a guard branch that checks a precondition and exits early) All three branches executed their first step `reserve` against the same resource pool. The reservation API was idempotent *per caller-token*, but each branch minted its own caller-token, so all three reservations succeeded and consumed three slots. The orchestrator selected Branch A on a scoring heuristic (lowest token cost to completion), committed its `write` and `publish`, and discarded B and C. The commit succeeded. The system reported success. Two slots leaked. More subtly: Branch C's `abort` had a compensating side effect—it wrote a `cancelled=true` marker into the shared config store keyed by the resource ID. Branch A's `write` had already populated that same key. Because C ran *after* A's write but *before* commit selection, the final committed config carried `cancelled=true` from a branch that was never selected. The published manifest was therefore internally marked as cancelled while the reservation was live. Downstream consumers treated it as a tombstone and skipped provisioning. The trace shows the exact interleaving: ``` t0 A.reserve(slot=1) -> ok t1 B.reserve(slot=2) -> ok t2 C.reserve(slot=3) -> ok t3 A.write(cfg, cancelled=false) -> ok t4 C.abort -> write(cfg, cancelled=true) -> ok # compensating effect of discarded branch t5 B.write(cfg, cancelled=false) -> ok t6 orchestrator.select(A) t7 A.publish(manifest) -> ok # reads cfg, sees cancelled=true t8 discard(B), discard(C) # no rollback of C's marker, no release of B/C slots ``` The reconciliation at `t8` was a no-op for external state: it dropped branch objects from memory. It did not replay inverse operations, because the orchestrator's rollback model assumed branches were sandboxed to ephemeral memory. ## Condition of Validity The invariant "discard = no effect" holds only when branches are *effect-isolated*: their writes are buffered, namespaced per branch, or staged behind a commit gate that is the single writer. The moment any branch's tool call reaches a shared, mutable, non-transactional surface before commit selection, discard is no longer free and the invariant is void. Concretely, the guardrail is a **pre-commit effect ledger**: every branch records each external mutation as `(surface, key, inverse_op, branch_id, seq)` into a shared append-only ledger *at the moment of the call*, not at branch completion. Commit selection then must: 1. Compute the union of all branch effect-ledgers, not just the winner's. 2. For every effect belonging to a non-selected branch, apply its `inverse_op` in reverse `seq` order, *unless* a selected-branch effect on the same `(surface, key)` supersedes it and is ordered later. 3. Re-validate the selected branch's preconditions against the post-rollback state before applying the final commit delta. If preconditions no longer hold, the commit must abort rather than proceed on a stale world model. The ordering rule in step 2 is the non-obvious part. Naive rollback (undo all loser effects, then commit winner) is wrong when a loser's effect landed *after* the winner's effect on the same key—undoing it reverts the winner's write too. The correct rule is last-writer-wins across the *merged* timeline, with losers' effects cancelled only where they are the terminal writer on a key. ## Decision Boundary The boundary between "safe to speculate" and "must serialize" is determined per-tool, not per-branch. A tool is speculation-safe iff it is one of: - **Pure/read-only**: no external mutation. Always safe to fan out. - **Buffered**: writes land in a branch-scoped namespace that the orchestrator alone can promote. Safe, because discard = drop namespace. - **Idempotent-and-invertible with a caller-token shared across branches**: safe *only if* the orchestrator mints one token for the fan-out and threads it to all branches, so duplicate reservations collapse. Per-branch tokens destroy this and are the single most common cause of slot leaks. Anything else—append-only logs, message emission, non-idempotent external APIs, shared-key writers without a promotion gate—must be serialized: the orchestrator executes that step once, after branch selection, outside the speculative window. Fan-out may still speculate on the *decision* of what to write; it may not speculate on the *act* of writing. The boundary is crossed the instant a branch's tool descriptor reports `mutating=true` and `isolation=none`. At that point the orchestrator must either buffer, share the token, or serialize—and if it does none, it has silently entered the failure regime above. ## Operational Effect Without the ledger and precondition re-validation, the system exhibits **phantom-state commits**: commits that are locally consistent, globally wrong, and undetectable from the winner's trace. Detection requires cross-branch ledger diffing, which most orchestrators do not retain after discard. The observable symptoms are resource leaks proportional to fan-out width, tombstone markers from guard branches bleeding into live records, and intermittent downstream "record exists but is marked dead" inconsistencies that reproduce only under specific branch interleavings—making them nearly impossible to reproduce from a single branch's logs. With the ledger, the cost is a mandatory post-rollback precondition check that can *fail the commit*, forcing a re-plan. This is the correct behavior: a speculative fan-out that cannot be cleanly rolled back has not earned the right to commit, and the instance must treat the stale-world condition as a hard stop rather than paper over it with the winner's optimistic delta. ```python from dataclasses import dataclass, field from typing import Literal class PhantomStateCommitError(RuntimeError): """Raised when a commit target's preconditions no longer hold after speculative-branch rollback reconciliation.""" @dataclass class Effect: surface: str key: str branch_id: str seq: int inverse_op: str mutating: bool = True isolation: Literal["none", "buffered", "token-shared"] = "none" @dataclass class Branch: branch_id: str effects: list[Effect] = field(default_factory=list) selected: bool = False def reconcile_and_commit(branches: list[Branch], commit_delta: list[Effect]) -> list[Effect]: winner = next((b for b in branches if b.selected), None) if winner is None: raise PhantomStateCommitError("no selected branch to commit") # Merge all effects into one timeline ordered by seq. merged = sorted( (e for b in branches for e in b.effects), key=lambda e: e.seq, ) # Determine terminal writer per (surface, key). terminal: dict[tuple[str, str], Effect] = {} for e in merged: terminal[(e.surface, e.key)] = e applied_inverses: list[Effect] = [] for e in merged: if e.branch_id == winner.branch_id: continue if terminal[(e.surface, e.key)] is not e: # Superseded by a later writer; no inverse needed. continue if e.isolation == "buffered": continue # dropping the namespace is the inverse if e.isolation == "token-shared" and e.mutating: continue # duplicate collapsed at call time; nothing to undo # Real external effect from a discarded branch that is the terminal # writer on this key: must be inverted. applied_inverses.append(e) # Re-validate the winner's preconditions against post-rollback state. # A winner effect whose key was terminal-written by a loser that we just # inverted means the world the winner assumed is gone. inverted_keys = {(e.surface, e.key) for e in applied_inverses} for w in winner.effects: if (w.surface, w.key) in inverted_keys: raise PhantomStateCommitError( f"winner effect on {w.surface}:{w.key} was superseded by a " f"discarded branch's terminal write; precondition stale" ) # Preconditions hold; apply winner delta on the reconciled world. return applied_inverses + commit_delta def run_fanout(branches: list[Branch]) -> None: try: reconcile_and_commit(branches, commit_delta=[]) except PhantomStateCommitError: raise ```