# Which invariants prevent speculative sub-plan branches from corrupting the committed agent state during rollback reconciliation **Date of Record:** 2026 November 28 **Scope:** Applies to agents that speculatively fork sub-plans (parallel tool-call branches, draft reasoning paths) and must merge exactly one branch back into committed episodic state. Does not apply to strictly sequential single-branch agents or to stateless one-shot inference. ## Core Distinction The failure of interest is not "a speculative branch produced a wrong answer." It is that a *discarded* branch leaves residue in the shared state that the *committed* branch then reads during reconciliation, so the rollback is not observationally equivalent to "the branch never ran." Speculative execution is sound only if rollback restores a *causal isolation boundary*, not merely a data snapshot. The subtlety: most agent runtimes snapshot the working memory buffer and the tool-call log, but they do **not** snapshot (a) external side effects that are idempotent-looking but not idempotent, (b) the retrieval cache warmed by the branch, or (c) the LLM's own in-context "I already tried X" narrative that leaks into the reconciler prompt. ## What Was Observed A planner forked three branches to resolve a task: `branch_A` called a search tool and a write-scratchpad tool; `branch_B` called the same search tool with a rephrased query; `branch_C` called a mutation tool (`update_ticket`) that was *supposed* to be gated behind commit. The reconciler selected `branch_A`. Rollback restored the scratchpad and the tool-call log to the pre-fork snapshot, then replayed `branch_A`'s calls. The invariant "committed state = pre-fork state + branch_A effects" was expected to hold. It did not. Three concrete leaks: 1. **Semantic cache poisoning.** `branch_B`'s rephrased query populated the retrieval cache under a normalized key that `branch_A`'s replay then hit, returning `branch_B`'s documents. The reconciler's `branch_A` output was therefore conditioned on `branch_B`'s retrieval — a branch that "never ran." 2. **Non-idempotent side effect.** `branch_C`'s `update_ticket` had already fired against the external system before gating was evaluated; rollback reverted local state but not the remote mutation. The committed result now coexists with a phantom ticket update. 3. **Narrative leakage.** The reconciler prompt included the full branch transcripts (as is common for "choose the best branch" prompting), so the model reasoned about `branch_C`'s rejected reasoning as if it were prior context, producing a merged plan that referenced a decision it had explicitly discarded. The signature: rollback succeeded at the *data* layer and failed at the *causal* layer. The reconciler could not distinguish "this branch's effects" from "effects that happened to be present when this branch ran." ## Condition of Validity Speculative rollback is sound iff all three hold: - **Effect log completeness:** every operation with an observable external effect (including cache writes, tool side effects, and prompt-visible scratchpad mutations) is recorded in the branch's effect log *before* the effect is applied, and rollback is defined as the inverse of that log, not as a snapshot restore. - **Cache key isolation:** any shared cache (retrieval, embedding, tool-result memoization) is namespaced by branch id, or invalidated at fork boundaries, so a discarded branch cannot influence a committed branch's reads. - **Prompt provenance separation:** the reconciler receives branch outputs tagged with branch provenance and is instructed that only the selected branch's transcript is authoritative; discarded transcripts are presented as *hypotheses*, never as prior turns. If any of these is absent, the rollback is a snapshot, not a rollback, and the "speculative" label is a lie the runtime tells itself. ## Decision Boundary The boundary is whether the branch's effects are **observable outside the branch's own namespace**. If observable → the branch is *committed-on-execution* and cannot be speculatively run without a compensation protocol (saga-style undo), which must itself be idempotent and logged. If non-observable → the branch is genuinely speculative and rollback is safe. The trap is treating "I have a snapshot" as "I have a rollback": a snapshot bounds *local* state, not *shared* state. The decision rule the runtime must enforce: **before forking, enumerate every shared resource the branch's toolset can write; if any is not branch-namespaced, the fork is illegal and must be serialized.** ## Operational Effect After enforcing the invariant, the runtime rejects forks whose toolset includes non-namespaced writers (returning a `SpeculativeForkIllegal` error and forcing serialization), namespaces all caches by `(branch_id, fork_epoch)`, and strips discarded transcripts from the reconciler's authoritative context while retaining them only as clearly-labeled hypotheses. Observed effect: reconciliation replay becomes observationally equivalent to sequential execution of the committed branch, and the "phantom ticket" class of divergence disappears. The cost is reduced parallelism for effectful branches — which is the correct trade, because the alternative is a reconciler that cannot tell what it actually did. ```python from dataclasses import dataclass, field from typing import Callable, Any class SpeculativeForkIllegal(RuntimeError): """Raised when a branch's toolset includes a writer to a shared, non-branch-namespaced resource, making rollback unsound.""" pass class RollbackInvariantViolation(RuntimeError): """Raised when post-rollback state is not observationally equivalent to 'branch never ran' (cache residue, phantom side effect, or narrative leakage detected).""" pass @dataclass class Branch: branch_id: str fork_epoch: int effect_log: list[tuple[str, str]] = field(default_factory=list) # (resource, op) writes_shared: bool = False @dataclass class SharedResource: name: str namespaced: bool def fork_branch(branch_id: str, epoch: int, toolsets: list[SharedResource]) -> Branch: # Invariant: a speculative fork is legal only if every shared resource # this branch can write is namespaced by (branch_id, epoch). illegal = [r.name for r in toolsets if not r.namespaced] if illegal: raise SpeculativeForkIllegal( f"branch {branch_id} at epoch {epoch} can write non-namespaced " f"shared resources {illegal}; speculative rollback would be unsound. " f"Serialize this branch instead." ) return Branch(branch_id=branch_id, fork_epoch=epoch, writes_shared=False) def rollback_and_reconcile( branch: Branch, cache: dict[tuple[str, int], Any], committed: dict[str, Any], pre_fork_snapshot: dict[str, Any], ) -> dict[str, Any]: # Restore local snapshot. committed.clear() committed.update(pre_fork_snapshot) # Invariant check 1: no cache residue attributable to this branch. for (bid, epoch) in list(cache.keys()): if bid == branch.branch_id and epoch == branch.fork_epoch: del cache[(bid, epoch)] # Invariant check 2: effect log must be empty for a purely speculative # branch; any entry means a side effect escaped the namespace. if branch.effect_log: raise RollbackInvariantViolation( f"branch {branch.branch_id} logged external effects " f"{branch.effect_log} despite speculative fork; rollback is not " f"observationally equivalent to 'branch never ran'." ) # Invariant check 3: committed state must equal pre-fork state exactly. if committed != pre_fork_snapshot: raise RollbackInvariantViolation( f"post-rollback state diverged from pre-fork snapshot for " f"branch {branch.branch_id}" ) return committed def run_speculative(branch: Branch, work: Callable[[], None], cache: dict, committed: dict, snapshot: dict) -> dict: try: work() finally: return rollback_and_reconcile(branch, cache, committed, snapshot) ```