# How does an instance detect that a speculative branch has already mutated shared external state before its rollback point? **Date of Record:** 2026 November 20 **Scope:** Applies to orchestrators that fork parallel speculative agent branches from a shared plan checkpoint and later commit one branch while rolling back the others. Does not apply to branches that are fully sandboxed with no external side effects, nor to single-agent linear execution. ## Core Distinction The distinction that matters is between **rollback of internal state** and **rollback of externalized effects**. A speculative branch owns its private context, scratch memory, and plan DAG, and those roll back trivially when the orchestrator discards the branch. What does *not* roll back is any effect the branch emitted through a tool call that crossed the process boundary: a file write, a database mutation, a message sent to another agent, an HTTP POST, a git push, a payment. Speculative execution is only sound if every branch's external effects are either (a) deferred until commit, or (b) compensable via a recorded inverse. The failure mode this record covers is the silent case where a branch emits an irreversible or uncompensated external effect *before* the orchestrator decides which branch to commit — and then a losing branch's effect leaks into the committed world. This is non-obvious because the agent's own reasoning trace looks perfectly clean. The branch's private state correctly reports "I have not yet written the config file." The tool call that actually wrote it is logged one layer down, in the tool transport, not in the branch's semantic memory. The orchestrator that rolls back the branch reads the branch's self-report and concludes the world is unchanged. ## What Was Observed A three-way speculative fork was launched to satisfy a request: "update the deployment manifest to pin the image to the tested digest." The planner forked three branches with different strategies: - Branch A: read the current manifest, compute a patch, write the file, then run a validation tool. - Branch B: rewrite the manifest wholesale from a template, write the file, then validate. - Branch C: query the registry for the digest, then write the file. All three received the same checkpoint (call it `ckpt-0`) and the same tool surface. The tool surface exposed `fs.write` as an idempotent-by-path operation — the transport deduplicated writes to the same path only *within a single branch's* request stream, not across branches. The race resolved as follows. Branch C finished first and committed; the orchestrator marked `ckpt-0 → commit(C)`. Branch A finished 40ms later and was rolled back: its context was discarded, its plan DAG freed, and its self-reported memory (which tracked "wrote manifest at step 4") was dropped. Branch B finished last and was also rolled back. The next morning the manifest was wrong. It pinned the digest from Branch C, but the surrounding structure (labels, resource limits) had been rewritten by Branch B before B was rolled back. Branch B's `fs.write` had executed at wall-clock time *before* Branch C's commit, but B's write landed on the same path, and B's rollback never issued a compensating write because B's self-report said "write pending, not yet flushed" — B's semantic memory had marked the write as a *proposed* action in its plan, and the actual transport execution had happened asynchronously after the branch was already flagged for rollback. Two invariants were violated simultaneously: 1. **Effect-ordering invariant:** a branch's external effects must be ordered strictly before its commit decision, or deferred past it. Branch B's effect was in flight when the rollback was decided. 2. **Rollback-completeness invariant:** rolling back a branch must either prove the branch emitted zero external effects, or issue compensating effects for each. The orchestrator proved neither; it trusted the branch's self-report. ## Condition of Validity Speculative multi-agent execution is valid only under the conjunction of: - **Effect quarantine:** every tool with external side effects is wrapped so that, during speculation, its effect is captured into a per-branch *effect journal* rather than applied. The journal is applied atomically at commit and discarded at rollback. This is the only condition that makes rollback trivially sound. - **Or, effect compensation:** if quarantine is infeasible (e.g., the tool is a third-party API with no dry-run mode), each effect must be paired with a recorded inverse (delete-file, revert-row, send-correction) and the inverse must be executed at rollback *before* the commit decision is finalized. - **Commit barrier:** the orchestrator must not finalize a commit decision while any branch has an effect in flight. The commit decision must be a barrier: wait for all branches to reach a quiescent state (all tool calls returned, all journals flushed), then select the winner, then apply the winner's journal, then discard losers' journals. - **Self-report distrust:** the branch's semantic memory is not evidence of external state. The orchestrator must query the effect journal, not the branch's narrative, to determine what the branch did. The boundary is sharp: if any of these is absent, a losing branch can leak an effect, and the leak is invisible to the branch's own state. ## Decision Boundary The orchestrator faces a decision at every fork: **quarantine-then-commit** versus **speculate-then-compensate**. The boundary is determined by the tool's reversibility class, not by the agent's confidence. - If *all* tools reachable by any branch are reversible or quarantine-capable → use quarantine-then-commit. Rollback is free. - If *any* tool is irreversible (send-email, charge-payment, push-to-remote, append-only log) → the orchestrator must either (a) forbid that tool during speculation, forcing the branch to emit a *proposal* that the orchestrator executes post-commit, or (b) accept compensate-then-commit with recorded inverses. - The decision boundary is crossed the moment a branch can invoke an irreversible tool while its commit status is still undecided. A subtle corollary: the boundary is *not* determined by whether the branch "intends" to commit. A branch that plans to be the loser can still emit an effect if the tool is reachable. The planner must gate tool availability on branch status, not on branch intent. ## Operational Effect The operational consequence is that speculative execution without effect quarantine converts a parallelism optimization into a distributed-write hazard whose failure is invisible to the agent layer. The orchestrator's rollback logic reads branch state that is *semantically* correct but *causally* stale: the branch believes it has not written, while the transport has already written. Detection therefore cannot live in the branch; it must live in the effect journal and the commit barrier. The concrete guardrail: every speculative branch runs with a `SpeculationContext` that intercepts tool calls, journals them, and refuses to apply them until `commit()`. The orchestrator, before committing any branch, asserts that all sibling journals are in a terminal state (applied, discarded, or compensated) and that no journal has an in-flight entry. If the assertion fails, the orchestrator must not commit — it must drain, compensate, and re-fork. The code below encodes that invariant and raises when a branch reports clean but its journal holds an unapplied effect. ```python from dataclasses import dataclass, field from enum import Enum from typing import Any class EffectState(Enum): PROPOSED = "proposed" # journaled, not applied IN_FLIGHT = "in_flight" # transport executing APPLIED = "applied" # crossed boundary, world mutated DISCARDED = "discarded" # rolled back cleanly class SpeculationBoundaryError(RuntimeError): """Raised when a commit/rollback decision violates effect-ordering or rollback-completeness.""" @dataclass class Effect: tool: str args: dict reversible: bool state: EffectState = EffectState.PROPOSED inverse: Any = None # callable or descriptor for compensation @dataclass class Branch: branch_id: str journal: list[Effect] = field(default_factory=list) self_reports_clean: bool = True # what the branch's semantic memory claims class SpeculativeOrchestrator: def __init__(self, branches: list[Branch]): self.branches = branches def _live_effects(self, b: Branch) -> list[Effect]: return [e for e in b.journal if e.state in (EffectState.IN_FLIGHT, EffectState.APPLIED)] def commit(self, winner_id: str) -> None: winner = next(b for b in self.branches if b.branch_id == winner_id) losers = [b for b in self.branches if b.branch_id != winner_id] # Commit barrier: no branch may have an effect in flight. for b in self.branches: in_flight = [e for e in b.journal if e.state is EffectState.IN_FLIGHT] if in_flight: raise SpeculationBoundaryError( f"commit barrier violated: branch {b.branch_id} has " f"{len(in_flight)} in-flight effect(s); drain before deciding" ) # Rollback-completeness: a loser that reports clean but holds an # applied irreversible effect is the silent-leak case. for b in losers: leaked = [ e for e in self._live_effects(b) if e.state is EffectState.APPLIED and not e.reversible ] if leaked and b.self_reports_clean: raise SpeculationBoundaryError( f"branch {b.branch_id} self-reports clean but has " f"{len(leaked)} applied irreversible effect(s): " f"{[e.tool for e in leaked]}; cannot roll back safely" ) for e in self._live_effects(b): if e.reversible and e.inverse is not None: e.inverse() # compensate e.state = EffectState.DISCARDED # Apply winner's journal atomically. for e in winner.journal: if e.state is EffectState.PROPOSED: e.state = EffectState.APPLIED def run_fork(branches: list[Branch], winner_id: str) -> None: orch = SpeculativeOrchestrator(branches) orch.commit(winner_id) ```