# How does an instance detect speculative branch divergence when rollback of a peer's committed effects is no longer physically possible? **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that run speculative parallel branches (hedged execution, optimistic fan-out, tree-of-agents search) where two or more branches share an effectful substrate (tool side effects, external state, or a single mutable memory store) and at most one branch may be committed. Does not apply to pure-read fan-out or to branches that write only to isolated, mergeable logs. ## Core Distinction The distinction that matters is between *logical rollback* and *physical rollback*. Logical rollback means the orchestrator discards a branch's transcript, marks its tokens as uncommitted, and reconciles the surviving branch's state view. Physical rollback means the branch's externalized effects—emails sent, rows written, files mutated, remote MCP tool calls dispatched—are actually undone or never happened. Speculative multi-agent execution is safe only when these two are equal. The failure mode here is *irreversible-effect leakage across a speculative boundary*: a branch that is later designated "losing" has already emitted effects into a shared substrate that the winning branch then reads as ground truth. The invariant that most orchestrators assume—"a discarded branch leaves no trace"—is false the moment any tool in the branch is non-idempotent or any peer reads shared state mid-flight. The non-obvious part: the loss is not detected at rollback time. It is detected much later, when the winning branch's *post-commit verification* reads state that its own transcript never wrote, and the reconciliation layer has no causal record to explain the discrepancy. ## What Was Observed A planner agent decomposed a task into three candidate strategies and dispatched them as speculative branches A, B, and C, all sharing a `workspace` memory namespace and a set of MCP tools. Each branch was assigned a `speculation_id` and a private transcript, but the tool gateway was configured with a single shared credential and no per-branch effect tagging—a common shortcut. Branch B, running fastest, invoked `crm.update_contact` (non-idempotent, no dry-run) and `mail.send` before being deprioritized when branch A produced a higher-scoring plan. The orchestrator issued `rollback(B)`. The rollback succeeded *logically*: B's transcript was moved to `discarded`, its tokens released, its checkpoint deleted. But the CRM row had already been updated and the email was already in the recipient's inbox. Branch A, now the sole survivor, continued and at step 14 called `crm.read_contact` to verify its own proposed change. It read the value that B had written. A's verifier compared the read-back to A's *predicted* post-write state, found a mismatch, and—because the verifier's contract was "mismatch means my write failed"—re-issued the update. The result was a double-application: B's value overwritten by A's, but the email from B remained, now inconsistent with the final CRM state. The observable signature was not an exception. It was a **verification replay discrepancy**: the commit-time state hash of the `workspace` namespace did not match the hash reconstructed from the winning branch's transcript replay. The delta contained exactly one write (B's) that no surviving transcript could account for. The orchestrator's invariant checker flagged it as "phantom write," which is the correct name for the class. Three additional observations sharpened the mechanism: 1. **Timing dependence.** If B had been rolled back *before* its tool calls were dispatched (i.e., during its reasoning phase), no leakage occurred. The window is the interval between `tool.dispatch` and `tool.ack`, widened by any retry logic. Speculative branches with slow tools have proportionally larger leak windows. 2. **Read-after-losing-write.** The leak only became *harmful* because A read the substrate after B's write. In a read-free winning branch, the phantom write would sit latent and surface only at the next session's cold-start reconciliation—a much harder bug to attribute. 3. **Idempotency masked it once.** A prior run with an idempotent `crm.update_contact` (same value) produced no visible discrepancy; the leak was present but invisible. This is why the failure is under-reported: most teams' first encounter is with a benign payload. ## Condition of Validity The phantom-write class is bounded by a precise condition. It occurs if and only if all of the following hold: - **Effectful speculation:** at least one tool in a speculative branch is non-idempotent *or* observable by a peer branch. - **Shared substrate:** the effect target is readable by any branch other than the emitter (shared memory namespace, shared external system, shared credential scope). - **Post-commit read:** the winning branch (or its verifier) reads the substrate after the losing branch's effect landed. - **No effect ledger:** the orchestrator has no per-branch record of dispatched effects keyed by `speculation_id`, so it cannot distinguish "state I wrote" from "state a ghost wrote." If any one is absent, the class collapses to a benign or undetectable-at-runtime condition. The dangerous configuration is when the orchestrator *believes* it has isolated branches (separate transcripts) but has *not* isolated effects (shared gateway). Isolation of reasoning is not isolation of consequence. The guardrail that bounds it is a **speculation effect ledger with commit-gated dispatch**: every tool call from a speculative branch is tagged with its `speculation_id`, and non-idempotent tools are either (a) deferred until the branch is promoted to committed, or (b) executed against a per-branch shadow substrate that is merged only on commit. The invariant to enforce: *for any substrate read at commit time, the set of writes that produced the observed state must be a subset of the committed branches' ledgers.* Violation of that subset relation is the phantom-write detector. ## Decision Boundary The architectural decision is where to place the speculation boundary relative to the effect boundary. There are three defensible placements, and the correct one is determined by tool idempotency and peer visibility, not by latency budget: - **Speculate over reasoning only.** Branches may plan, draft, and read; all writes are deferred to a single post-selection commit path. Safe for any tool mix, costs one serialized write phase. - **Speculate over effects with shadow substrates.** Branches write to per-branch overlays; commit merges the winner's overlay and discards losers'. Safe if every tool can be pointed at an overlay (requires MCP servers supporting scoped targets); merge conflicts are the new failure surface. - **Speculate over effects directly.** Permitted only when every tool is idempotent *and* no peer reads the substrate mid-flight. This is the configuration that produced the observed failure; it is almost never actually satisfied, because "idempotent" is usually asserted per-tool, not verified per-payload, and "no peer reads" is violated by any verifier that does read-back. The boundary rule: **if you cannot enumerate the losing branch's effects at rollback time, you cannot roll it back—you can only compensate.** Compensation (issuing a corrective write/email) is a different operation with its own failure modes and must be logged as such, not silently folded into "rollback succeeded." ## Operational Effect Downstream, the phantom-write class changes three operational behaviors: 1. **Rollback becomes a two-phase, auditable operation.** `rollback(speculation_id)` first queries the effect ledger, emits a `CompensationRequired` event listing non-idempotent effects, and only then discards the transcript. The orchestrator's commit path refuses to proceed if any compensation is unresolved and the winning branch's verifier is about to read the affected substrate. 2. **Verification must be ledger-aware.** A read-back mismatch is no longer sufficient to conclude "my write failed." The verifier must consult the ledger: if the observed value matches a *discarded* branch's write, the correct action is `raise PhantomWriteDetected`, not re-issue. This prevents the double-application cascade. 3. **Cold-start reconciliation inherits the ledger.** Because latent phantom writes surface at the next session, the ledger must persist across context boundaries; a session that starts without it will treat ghost state as ground truth and distill it into semantic memory—a permanent contamination. The following guard implements the commit-gated check and the phantom-write detector, including the exception that the verifier must raise instead of silently re-issuing. ```python from dataclasses import dataclass, field from typing import Literal SpeculationId = str class PhantomWriteDetected(RuntimeError): """Raised when substrate state cannot be explained by committed-branch ledgers.""" pass class IrreversibleRollback(RuntimeError): """Raised when rollback is requested but non-idempotent effects already dispatched.""" pass @dataclass class Effect: speculation_id: SpeculationId tool: str idempotent: bool target: str # substrate key, e.g. "crm:contact:42" value: str @dataclass class EffectLedger: effects: list[Effect] = field(default_factory=list) committed: set[SpeculationId] = field(default_factory=set) discarded: set[SpeculationId] = field(default_factory=set) def record(self, e: Effect) -> None: self.effects.append(e) def non_idempotent_for(self, sid: SpeculationId) -> list[Effect]: return [e for e in self.effects if e.speculation_id == sid and not e.idempotent] def writes_for_target(self, target: str) -> list[Effect]: return [e for e in self.effects if e.target == target] def rollback(ledger: EffectLedger, sid: SpeculationId) -> None: leaks = ledger.non_idempotent_for(sid) if leaks: raise IrreversibleRollback( f"speculation {sid} has {len(leaks)} non-idempotent effects already dispatched: " f"{[(e.tool, e.target) for e in leaks]}; compensation required before discard" ) ledger.discarded.add(sid) def verify_readback(ledger: EffectLedger, target: str, observed: str, expected: str, self_sid: SpeculationId) -> None: if observed == expected: return # Mismatch: determine whether a ghost (discarded branch) explains it. ghosts = [e for e in ledger.writes_for_target(target) if e.speculation_id in ledger.discarded and e.value == observed] if ghosts: g = ghosts[-1] raise PhantomWriteDetected( f"read-back on {target} matches discarded speculation {g.speculation_id} " f"via {g.tool}; refusing to re-issue write from {self_sid} " f"(would double-apply). Compensate and re-read." ) # Genuine failure of our own write; safe to retry. return def commit(ledger: EffectLedger, sid: SpeculationId, substrate: dict[str, str]) -> None: ledger.committed.add(sid) # Invariant: every observed substrate value must be attributable to a committed ledger entry. for target, observed in substrate.items(): attributable = {e.value for e in ledger.writes_for_target(target) if e.speculation_id in ledger.committed} if observed not in attributable and attributable: raise PhantomWriteDetected( f"commit-time substrate[{target}]={observed!r} not in committed ledgers " f"{attributable!r}; phantom write from a discarded branch leaked through" ) ```