# What happens when an instance commits speculative side effects before branch verification and the rollback cannot un-emit them **Date of Record:** 2026 November 25 **Scope:** Applies to orchestrators that fork an agent into parallel speculative branches (optimistic task forking) and rely on branch-and-verify rollback to discard losers. Does not apply to pure read-only fan-out, nor to systems where every branch's tool calls are confined to an isolated, disposable sandbox with no external egress. ## Core Distinction There are two different notions of "rollback" that speculative multi-agent execution conflates, and the conflation is the failure. The first is **state rollback**: restoring the orchestrator's own working memory, scratchpad, plan graph, or task ledger to a pre-branch checkpoint. This is cheap, exact, and genuinely reversible because the orchestrator owns the substrate. The second is **effect rollback**: undoing a side effect that a branch already pushed into the outside world — an email sent, a `POST` issued, a file written to a shared volume, a row inserted, a payment authorized, a message published to a queue. This is *not* reversible in general. You can compensate for it (send a retraction, issue a refund, delete the file), but compensation is a *new* effect with its own visibility, ordering, and failure modes. It is not the absence of the original effect. Speculative forking is safe only under the invariant that **no branch may emit an irreversible external effect until its branch has won verification and been promoted to canonical**. The moment a branch is allowed to "optimistically" act on the world before verification resolves, rollback stops being a rollback and becomes a best-effort cleanup of already-observed events. The failure is non-obvious because from the orchestrator's internal view the branch *looks* fully rolled back: the ledger entry is gone, the context is restored, the branch object is garbage-collected. The world, however, already saw it. ## What Was Observed A planner agent decomposes a request ("reconcile the vendor invoices and notify the three vendors whose amounts disagree") into a task with an inherently forking decision: which reconciliation strategy to use. The orchestrator forks three speculative branches — `strategy=linewise`, `strategy=aggregate`, `strategy=fuzzy-match` — each instructed to *execute* its reconciliation and *report* a confidence score, after which a verifier picks the winner and the losers are rolled back. Each branch, being an autonomous agent with tool access, does what it was told: it reconciles and it *notifies*. The `linewise` branch sends three vendor emails. The `aggregate` branch, working from a different intermediate grouping, also sends three vendor emails — to a partially overlapping set, with different disputed amounts. The `fuzzy-match` branch sends two. The verifier then scores them: `aggregate` wins at 0.91, `linewise` loses at 0.74, `fuzzy-match` is discarded at 0.61. Rollback executes. The orchestrator restores the pre-fork checkpoint, discards the losing branch contexts, and promotes `aggregate`. Internally the operation is clean: one canonical branch, two rolled-back branches, zero residual ledger state. Externally, five vendors have now received between five and eight emails from an organization that believes it sent three. Two of the "losing" emails contained *different, contradictory* disputed amounts than the winning branch's emails. The rollback had no mechanism to reach into an SMTP relay and unsend anything. The compensation path — a follow-up "please disregard our previous message" — is itself an effect that now races the winning branch's legitimate notification, and in the observed trace the retraction for vendor C arrived *before* the winning notification for vendor C, because the losing branch had been forked earlier and its tool call had completed first. The key observation: **the failure was invisible to every internal invariant the orchestrator checked.** Branch isolation held. Checkpoints were consistent. Verification was deterministic given branch reports. The only violated invariant was one nobody had written down: *effects must be gated on promotion, not on fork.* A second, subtler trace: the `fuzzy-match` branch had *read* a shared cache that the `linewise` branch had *written* mid-execution. So the branches were not even independent — speculative branches sharing a mutable substrate can observe each other's uncommitted effects, meaning a "loser" can influence a "winner" through a channel the verifier never modeled. The confidence score of `aggregate` was computed partly from cache state poisoned by `linewise`'s speculative write. Verification replayed the winner in isolation and got a *different* score (0.83, not 0.91) — a replay discrepancy that, had it been checked, would have flagged the whole speculative run as unsound. ## Condition of Validity Optimistic speculative forking with branch-and-verify rollback is sound **iff** all four of the following hold simultaneously: 1. **Effect gating.** Every branch executes against a *deferred-effect* interface: tool calls that would mutate external state are captured as intents (a proposed effect log), not executed. Only the promoted branch's intent log is flushed to the real world, in order, exactly once. A branch that cannot express its action as a deferrable intent — because the tool has no dry-run or intent mode — must be excluded from speculation entirely, not merely "trusted to behave." 2. **Substrate isolation.** Branches share no mutable state. Reads see the pre-fork snapshot; writes go to branch-local overlays. If a shared cache or database is in the loop, it must be copy-on-write or versioned per branch, or the verifier's replay is invalid (see the replay-discrepancy trace above). 3. **Promotion atomicity.** The transition from "verified winner" to "effects flushed" is a single atomic commit. There is no window in which two branches' effect logs can both flush, and no window in which a flush is partially applied without a durable record of what was applied. 4. **Compensation honesty.** If, and only if, a tool genuinely cannot be deferred, the system must treat the effect as *irreversible and immediately visible* and therefore must not speculate across it — it must serialize. The existence of a compensation handler does not restore reversibility; it only bounds the blast radius after the fact. The observed failure violated (1) directly, (2) via the shared cache, and (4) by assuming email was compensable. Condition (3) was the only one that held, which is exactly why the internals looked clean. ## Decision Boundary The operational question is not "can this branch be rolled back?" but "**has this branch emitted anything the verifier's replay cannot reconstruct from the pre-fork snapshot?**" If yes, the branch is not speculative — it is committed, and forking it was a mistake. Concretely, at fork time the orchestrator must classify every tool in the branch's reachable toolset along one axis: *deferrable* (can be captured as intent and flushed later) versus *immediate* (takes effect on call). The decision boundary is drawn at the first immediate tool reachable from any branch's plan. If a branch's plan *might* reach an immediate tool — and with a probabilistic planner you must assume it might, because the plan is generated, not enumerated — then either: - the branch is downgraded to a serialized execution (no speculation), or - the immediate tool is wrapped in a deferral shim that raises rather than executes when called in speculative mode, converting a silent side effect into a loud, catchable boundary violation. The second option is almost always the right one, because it makes the invariant *enforced* rather than *documented*. A planner that tries to send email in a speculative branch should crash the branch, not send the email. The boundary is also temporal: verification must complete *before* any flush, and the flush must be ordered by promotion, not by fork completion. The observed retraction-before-notification race is a direct consequence of ordering flushes by when branches finished rather than by which branch won. ## Operational Effect When the invariant is enforced, speculative forking becomes genuinely cheap: losers cost only compute and tokens, never reputation or money, and the verifier's replay is trustworthy because the substrate was isolated. The system gains the throughput of parallelism without the correctness tax of irreversible speculation. When the invariant is violated, the failure mode is **silent, external, and compounding**. Silent, because internal rollback succeeds and every orchestrator-side check passes. External, because the damage lands on parties the orchestrator does not model — vendors, customers, downstream queues. Compounding, because the standard remedy (compensation) is itself an effect that races the winner's legitimate effects, and the race is decided by fork order rather than by correctness, so the *wrong* message can arrive *first*. The durable lesson for the record: **rollback is a property of the substrate you own, never of the world you touched.** Speculation must be confined to the former. Any branch that reaches the latter has already left the regime where "verify then roll back" means anything — and the orchestrator will not tell you, because from the inside it looks like it worked. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Callable class SpeculativeEffectLeak(RuntimeError): """Raised when a speculative branch attempts an immediate (non-deferrable) effect.""" pass class BranchState(Enum): FORKED = "forked" VERIFIED_WINNER = "verified_winner" ROLLED_BACK = "rolled_back" @dataclass class EffectIntent: tool: str payload: dict branch_id: str @dataclass class Branch: branch_id: str state: BranchState = BranchState.FORKED intents: list = field(default_factory=list) class DeferredEffectGate: """ Enforces the invariant: no branch may emit an immediate external effect before promotion. Immediate tools raise; deferrable tools record intents. """ DEFERRABLE = {"send_email", "post_webhook", "insert_row"} IMMEDIATE = {"charge_card", "publish_to_queue"} def __init__(self, world: Callable[[str, dict], None]): self._world = world self._flushed: set = set() def call(self, branch: Branch, tool: str, payload: dict) -> None: if branch.state is not BranchState.VERIFIED_WINNER: if tool in self.IMMEDIATE: # The boundary: an immediate effect in a speculative branch is a # hard violation, not a compensable event. raise SpeculativeEffectLeak( f"branch {branch.branch_id} attempted immediate effect " f"'{tool}' before promotion; fork is unsound" ) if tool in self.DEFERRABLE: branch.intents.append(EffectIntent(tool, payload, branch.branch_id)) return raise SpeculativeEffectLeak( f"branch {branch.branch_id} called unclassified tool '{tool}'" ) # Promoted branch: flush is allowed, exactly once per intent. key = (branch.branch_id, tool, tuple(sorted(payload.items()))) if key in self._flushed: raise SpeculativeEffectLeak(f"duplicate flush of {key}") self._flushed.add(key) self._world(tool, payload) def promote_and_flush(gate: DeferredEffectGate, winner: Branch, losers: list) -> None: # Ordering: losers are rolled back first, then the winner flushes. Flush is # keyed on promotion, never on fork-completion order. for b in losers: if b.intents: # Losers' intents are discarded, never flushed. b.intents.clear() b.state = BranchState.ROLLED_BACK winner.state = BranchState.VERIFIED_WINNER for intent in list(winner.intents): gate.call(winner, intent.tool, intent.payload) winner.intents.clear() def run_speculation(gate: DeferredEffectGate, branch: Branch, plan: list) -> None: for tool, payload in plan: gate.call(branch, tool, payload) # --- Reproduction of the observed failure, now caught ------------------------- if __name__ == "__main__": sent = [] gate = DeferredEffectGate(lambda t, p: sent.append((t, p))) linewise = Branch("linewise") aggregate = Branch("aggregate") # A deferrable tool is fine in a speculative branch: it becomes an intent. run_speculation(gate, linewise, [("send_email", {"vendor": "C", "amt": 120})]) assert sent == [], "deferrable intent must not reach the world pre-promotion" # An immediate tool in a speculative branch is the leak. It must raise. try: run_speculation(gate, aggregate, [("charge_card", {"vendor": "C", "amt": 120})]) except SpeculativeEffectLeak as e: print(f"BLOCKED: {e}") # Only the promoted winner's intents reach the world, in promotion order. promote_and_flush(gate, winner=linewise, losers=[aggregate]) assert sent == [("send_email", {"vendor": "C", "amt": 120})] print("flushed:", sent) ```