# Where must an instance refuse to fork a speculative branch: the read-after-write shadow divergence at rollback checkpoints **Date of Record:** 2026 November 24 **Scope:** Applies to orchestrators that run multiple speculative agent branches from a shared checkpoint, allow branches to perform side-effecting tool calls (writes, sends, mutations), and prune losing branches by rolling back to the checkpoint. Does not apply to pure-read speculation, to branches that are fully sandboxed with no external effect, or to single-branch retry loops where only one writer exists at a time. ## Core Distinction The distinction that governs everything downstream is between **a checkpoint as a state snapshot** and **a checkpoint as a state *and effect* boundary**. Most branch-and-prune orchestrators implement the former: they serialize the agent's message list, scratchpad, and tool-result cache at checkpoint time, fork N branches on top of that serialized context, and on prune they discard the losing branches' context and restore the winner's. The implicit assumption is that if the *context* is restored, the *world* is restored. That assumption is false the moment any branch performs a write. A speculative branch that calls `create_ticket`, `send_email`, `append_ledger_entry`, or `POST /orders` has mutated shared external state that the checkpoint does not and cannot capture. When the branch is pruned, its context evaporates but its effects persist. The winner then resumes from a checkpoint whose recorded state no longer matches the actual world, and every subsequent read it performs returns data that its own context says should not exist. This is **read-after-write shadow divergence**: the pruned branch's writes become a "shadow" that the surviving branch reads but did not author, and cannot reconcile against its own history. The non-obvious part is that this failure is *silent and non-deterministic in severity*. If the loser's write is later overwritten by the winner, divergence self-heals. If the loser's write is additive (an appended record, a sent message, a created resource), it persists forever and the winner's reasoning is permanently contaminated. The orchestrator cannot tell these apart at prune time without inspecting effect semantics it does not model. ## What Was Observed A three-branch speculative planner was forked from checkpoint `C0` at step 12 of a procurement task. The task required creating a purchase order and notifying a vendor. Branches: - `B1` (winner): planned to create PO `#4471` for vendor A, then notify. - `B2` (loser): planned to create PO `#4471` for vendor B (a tie-break disagreement on vendor selection), then notify. - `B3` (loser): planned to query inventory only, no writes. All three forked with identical context at `C0`. The orchestrator scored branches by a planner-confidence heuristic after each branch's *first* tool call returned. `B1` and `B2` both called `create_purchase_order` with different vendor payloads. `B2` executed first (lower latency to the tool), returned `{po_id: 4471, vendor: B, status: created}`, and was scored higher at that instant. `B1` executed ~40ms later, returned `{po_id: 4472, vendor: A, status: created}`, and was scored lower. The orchestrator pruned `B1`, kept `B2`. Then `B2`'s next planning step re-read the PO list to confirm creation. The tool returned **both** `#4471` (its own) and `#4472` (the pruned `B1`'s orphaned write). `B2`'s context contained no record of ever creating `#4472`. Its planner interpreted the unexpected PO as a "duplicate created by another actor," entered a reconciliation sub-plan, attempted to cancel `#4472`, and — because `#4472` was already `status: created` and the cancel tool required an `owner_token` that `B2` did not hold — hard-failed the branch at step 19. The orchestrator, having already pruned the only branch (`B1`) that *did* hold the token and *did* intend `#4472`, had no recovery path. The task aborted with a live, unowned PO in the external system. The trace signature: a branch's tool-result cache at step `k` contains an object whose `created_by` field references a branch ID that is not in the surviving branch's ancestry. The orchestrator's prune logic never checked this. ## Condition of Validity The rollback-checkpoint invariant holds **only if** every speculative branch is *effect-isolated*: either (a) its writes are buffered and committed atomically on branch selection, or (b) its writes are idempotent and namespaced by branch ID such that a pruned branch's writes are invisible to survivors, or (c) the branch is provably read-only. The invariant is **violated** when a branch performs a non-idempotent, non-namespaced write to shared state before the selection decision is final. The precise trigger condition is: 1. `branch.write()` executes against shared external state, AND 2. the orchestrator's selection function can prune that branch *after* the write commits, AND 3. a surviving branch subsequently *reads* the namespace the pruned write touched. All three must hold. If (1) fails (read-only branch), no shadow. If (2) fails (write happens only after selection is locked), no orphan. If (3) fails (survivor never reads the touched namespace), the shadow exists but is unobservable and harmless. The dangerous regime is exactly the intersection — which is precisely the regime speculative execution is *for*, since speculation exists to overlap writes with decision latency. Note the asymmetry that makes this hard to guard by inspection: the orchestrator scores branches on *tool return values*, but the divergence manifests in *later reads*. The scoring function sees `B2`'s clean `{status: created}` and has no signal that `B1`'s write is now a landmine. The failure is not at the write; it is at the read, one or more steps later, by a branch that has already been declared the winner. ## Decision Boundary The boundary an instance must enforce is: **a branch may not be pruned after it has committed a non-idempotent write, unless the orchestrator can prove the write is invisible to all surviving branches.** In practice this collapses to a forkability predicate evaluated *before* forking: - **Forks are safe** when the branch's planned tool calls are all classified read-only, or all writes carry a `branch_id` namespace that the read path filters. - **Forks are unsafe** when any planned call is a non-namespaced mutation, and the selection window extends past that call's commit. In this case the orchestrator must either (i) serialize the write behind selection (no speculation on the write step), or (ii) attach a compensating-action closure to every write so that pruning triggers `undo(write)` before the survivor resumes. The decision rule for an instance mid-execution: before emitting a write tool call while in a speculative branch, check whether the orchestrator has declared the branch's selection *final*. If not final, and the write is non-idempotent and non-namespaced, the instance must **refuse to write and instead return a deferred-write intent** to the orchestrator, which commits it only after selection. An instance that writes speculatively without this check is the proximate cause of shadow divergence, regardless of orchestrator design. The corollary invariant: **a winner's context must be a superset of every effect visible in its read namespace.** If a survivor reads an object it cannot attribute to its own history or to a pre-checkpoint effect, the orchestrator must treat this as divergence and halt, not reconcile. Reconciliation-by-inference (as `B2` attempted) is the failure amplifier. ## Operational Effect The downstream consequences are not "a stray record." They are: 1. **Attribution inversion.** The survivor's planner sees an effect it did not cause and, lacking a record, attributes it to an external actor or to its own earlier step it has "forgotten." Either attribution corrupts subsequent planning. In the observed case it triggered a cancel sub-plan against a resource the survivor had no authority over. 2. **Compensation impossibility.** The orchestrator pruned the branch that held the only handle (`owner_token`) to the orphaned write. Rollback is now structurally impossible without out-of-band admin action. This is the worst property: pruning destroys the *capability* to undo the pruned branch's effects. 3. **Non-determinism in replay.** Re-running the same task from `C0` with identical seeds produces different survivors depending on tool latency, because selection is latency-sensitive and latency determines which write commits first. The orphan set is not reproducible, so post-hoc audit cannot reconstruct which effects were speculative. 4. **Silent accumulation.** Under sustained load, orphaned additive writes accumulate in the external namespace. Each survivor's read set grows with objects it did not author, and planner confidence degrades monotonically as the unattributed fraction rises. There is no error, only a slow drift toward incoherent state. The architectural guardrail that bounds this: **effect-journaled checkpoints.** Every checkpoint records not just context but a monotonic *effect log* of all writes committed by any branch forked from it, each tagged with `branch_id` and a `compensation` closure. On prune, the orchestrator executes compensations for the pruned branch's entries *before* releasing the survivor, and the survivor's read path asserts that every returned object's `branch_id` is either in its ancestry or in the pre-checkpoint effect log. Any object failing the assertion raises divergence and halts the branch. This converts a silent, non-reproducible corruption into a loud, deterministic, bounded failure — which is the most an orchestrator can promise when speculation and side effects share a namespace. ```python import time from dataclasses import dataclass, field from typing import Callable, Dict, List, Optional class ShadowDivergenceError(RuntimeError): """Raised when a surviving branch reads an effect it cannot attribute to its own ancestry.""" pass class UnsafeSpeculativeWriteError(RuntimeError): """Raised when a branch attempts a non-idempotent, non-namespaced write before selection is final.""" pass @dataclass class Effect: effect_id: str branch_id: str namespace: str idempotent: bool compensation: Optional[Callable[[], None]] = None @dataclass class Branch: branch_id: str ancestry: List[str] selection_final: bool = False effects: List[Effect] = field(default_factory=list) class CheckpointOrchestrator: def __init__(self) -> None: self.effect_log: Dict[str, Effect] = {} self.committed_pre_checkpoint: set = set() def speculative_write(self, branch: Branch, namespace: str, idempotent: bool, compensation: Optional[Callable[[], None]]) -> Effect: # Guard: refuse non-idempotent, non-namespaced writes before selection is final. if not idempotent and not branch.selection_final: raise UnsafeSpeculativeWriteError( f"branch {branch.branch_id} attempted non-idempotent write to '{namespace}' " f"before selection was final; defer via intent instead" ) eid = f"{branch.branch_id}:{namespace}:{time.time_ns()}" eff = Effect(eid, branch.branch_id, namespace, idempotent, compensation) branch.effects.append(eff) self.effect_log[eid] = eff return eff def prune(self, branch: Branch) -> None: # Compensate every effect the pruned branch committed, before survivors resume. for eff in branch.effects: if eff.compensation is not None: eff.compensation() self.effect_log.pop(eff.effect_id, None) def guarded_read(self, survivor: Branch, returned_objects: List[dict]) -> None: # Every returned object must be attributable to survivor ancestry or pre-checkpoint log. allowed = set(survivor.ancestry) | self.committed_pre_checkpoint for obj in returned_objects: owner = obj.get("branch_id") if owner is not None and owner not in allowed: raise ShadowDivergenceError( f"survivor {survivor.branch_id} read object {obj.get('id')} " f"authored by pruned branch {owner}; context is not a superset of visible effects" ) def run_speculative_step(orch: CheckpointOrchestrator, branch: Branch, planned_write: bool, returned_objects: List[dict]) -> None: if planned_write: orch.speculative_write(branch, namespace="purchase_orders", idempotent=False, compensation=None) orch.guarded_read(branch, returned_objects) ```