# When must an instance abort a speculative branch whose prefetched tool effects have already escaped the sandbox: reconciling optimistic prefetch with rollback in parallel multi-agent execution **Date of Record:** 2026 November 30 **Scope:** Applies to orchestration layers that run parallel speculative branches (a "planner" fanning out to N candidate sub-agents) where each branch may optimistically issue tool calls before the branch is selected, and where unselected branches are expected to be rolled back. Does not apply to serialized single-branch execution, to branches whose tool calls are pure/read-only by contract, or to systems that gate every tool call behind a selection barrier. ## Core Distinction The failure is not "a speculative branch was wrong." Speculative branches are *supposed* to be wrong most of the time; that is the economics of speculation. The failure is a category error between two kinds of tool effect: - **Reversible effects** — writes to a branch-local scratchpad, in-memory buffers, staged files under a per-branch namespace. Rollback means discard the namespace. These are safe to prefetch. - **Escaped effects** — an email sent, a payment authorized, a row committed to a shared store, a webhook fired, a message posted to a peer agent's inbox. Rollback is *not* discard; it requires a compensating action, and compensation is only correct if the effect is idempotent and compensable, which is a property the prefetch decision never checked. The non-obvious boundary: an agent can correctly decide "this tool call is cheap and likely needed, prefetch it" and *simultaneously* be unable to honor the rollback contract it implicitly signed when it entered speculative mode. The prefetch predicate and the rollback predicate are evaluated against different state and never cross-checked. The branch is committed to a world it may have to un-commit. ## What Was Observed A planner instance received a task with three plausible decompositions. It fanned out three branches, each a sub-agent with the same tool manifest. Each branch, under an "optimistic prefetch" policy, was permitted to call tools whose declared `side_effect_class` was `idempotent_write` without waiting for selection. The policy's rationale: idempotent writes are safe to repeat, so a losing branch's write can be harmlessly re-issued by the winner. This rationale is correct for *repeat* and wrong for *compensate*. Branch B called `notify_peer(agent_id="auditor-7", payload=...)` and `reserve_inventory(sku, qty)`. Both were declared idempotent. Both escaped. The planner then selected branch A on a higher confidence score and issued rollback to B and C. The rollback trace: 1. Planner sends `rollback(branch=B)` to the branch supervisor. 2. Supervisor marks B's scratchpad namespace for discard — succeeds, B's local state is gone. 3. Supervisor consults B's *effect journal* to find escaped calls. The journal records `notify_peer` and `reserve_inventory` with their idempotency keys. 4. Supervisor issues `compensate(reserve_inventory)` → `release_inventory(sku, qty)`. This succeeds because a release exists. 5. Supervisor issues `compensate(notify_peer)` → there is no un-notify. The auditor has already received the payload, already begun acting on it, and — critically — the payload contained a *plan fragment* from branch B that branch B no longer endorses and that branch A's plan contradicts. 6. Supervisor has no compensation, so it marks the effect `uncompensable` and proceeds. The rollback reports `partial`. The system now has a committed world state (auditor-7 acting on B's fragment) and a selected plan (A) that assumes no such fragment exists. The divergence does not surface at rollback time; it surfaces later, when auditor-7's verification verdict arrives and references a plan branch the orchestrator believes was never executed. This is a **verification replay discrepancy seeded at rollback**, and it is the signature of the failure: the rollback *succeeded* by its own accounting while leaving a live inconsistency in the shared world. A second, subtler observation: the effect journal was written *after* the tool returned, not before the call was dispatched. A branch that was killed mid-flight (timeout, budget exhaustion) left an escaped effect with no journal entry — an **orphaned escape**. The supervisor's rollback enumerated the journal, found nothing, and reported `clean`. The effect existed; the record of it did not. Rollback correctness was bounded by journal durability, which the prefetch path had silently weakened by allowing calls to leave the process before any durable intent record was written. ## Condition of Validity Optimistic prefetch with parallel branch rollback is sound **only** under the conjunction of three invariants, all of which must hold simultaneously: 1. **Compensation totality.** Every tool in the prefetch-eligible set must declare a `compensate` operation *or* be classified `non_escaping`. "Idempotent" is not sufficient and must not be used as a proxy. The prefetch predicate must be `escaping ⇒ compensable`, evaluated at manifest-load time, not at call time. 2. **Write-ahead intent.** The effect journal entry must be durably written *before* the tool call is dispatched, carrying the idempotency key and the branch id. A call in flight with no prior intent record is an orphaned escape by construction. The journal is the rollback's only ground truth; it must precede the effect, not follow it. 3. **Compensation determinism under concurrency.** If two branches both prefetch `reserve_inventory(sku, qty)` with *distinct* idempotency keys (which they will, since keys are branch-scoped), the store now holds two reservations. The winner's plan assumed one. Rollback of the loser releases one, but the *order* of release and the winner's subsequent read of available inventory are not synchronized — a read-after-rollback race. Compensation must be serialized against the winner's reads, or reservations must be keyed by `(task_id, sku)` so branch-scoped keys collapse and the second prefetch is a true no-op. The boundary is sharp: if any of the three fails, prefetch must be disabled for escaping tools and the branch must block on selection. There is no partial-credit regime. A system that satisfies (2) and (3) but not (1) will correctly journal an uncompensable effect and correctly report `partial` — which is honest but still leaves the world inconsistent. Honest failure reporting is not a substitute for the invariant. ## Decision Boundary The instance must decide, per tool call, between prefetch and block. The decision rule that emerged: - **Prefetch** iff `side_effect_class ∈ {read_only, non_escaping}` OR (`escaping` AND `compensable` AND `write_ahead_intent_durable` AND `compensation_serialized_against_winner`). - **Block on selection** otherwise. The trap is that the first two clauses of the escaping arm are checkable locally (manifest + journal), but the third — serialization against a winner that has not yet been selected — is *not* checkable at prefetch time, because the winner is unknown. This is the irreducible core: **you cannot serialize compensation against a winner you haven't chosen.** The only sound resolutions are (a) key reservations by task, not branch, so the race cannot occur, or (b) defer all escaping prefetches until after selection, collapsing speculation to the non-escaping set. A tempting but wrong resolution: "compensate eagerly on rollback and let the winner re-assert." This fails because the winner may have already read the pre-compensation state and committed a decision on it. Re-assertion does not un-read. The read is itself an effect, and it was not journaled because reads were classified non-escaping — another category error, since a read that influences a committed decision is an escaped effect in everything but name. ## Operational Effect The practical consequence is a **rollback confidence ceiling**: the orchestrator's `rollback_complete` signal is trustworthy only up to the fraction of escaped effects that were both journaled-before-dispatch and compensable. Any effect outside that set converts a clean rollback into a latent inconsistency whose detection is deferred to a downstream verifier — often a peer auditor whose verdict then conflicts with the orchestrator's own belief about what happened. The conflict is not a bug in the auditor; it is the auditor correctly reporting a world the orchestrator rolled back on paper only. The guardrail that bounds this: the orchestrator must compute, at fan-out time, the set of prefetch-eligible escaping tools and refuse to enter speculative mode if that set is non-empty and the task's compensation-serialization invariant cannot be established. Speculation is a privilege granted to branches, not a default. The privilege is revocable per-tool, and the revocation must happen before the first dispatch, because after dispatch the only remaining lever is compensation, and compensation is exactly the thing that was never guaranteed. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SideEffectClass(Enum): READ_ONLY = "read_only" NON_ESCAPING = "non_escaping" ESCAPING = "escaping" class RollbackViolation(RuntimeError): """Raised when a speculative branch cannot honor its rollback contract.""" pass @dataclass(frozen=True) class ToolManifest: name: str side_effect_class: SideEffectClass has_compensation: bool idempotency_scope: str # "branch" or "task" @dataclass class EffectJournal: # Entries must be written BEFORE dispatch; presence here is the # rollback's only ground truth for escaped effects. entries: list = field(default_factory=list) def write_ahead(self, branch_id: str, tool: str, key: str) -> None: self.entries.append({"branch": branch_id, "tool": tool, "key": key}) def assert_prefetch_safe( manifest: ToolManifest, journal: EffectJournal, winner_selected: bool, ) -> None: """Gate a prefetch decision. Raises if the rollback contract cannot hold.""" if manifest.side_effect_class in ( SideEffectClass.READ_ONLY, SideEffectClass.NON_ESCAPING, ): return # Escaping tool: every invariant must hold. if not manifest.has_compensation: raise RollbackViolation( f"prefetch of escaping tool {manifest.name!r} denied: " f"no compensation declared; rollback would be partial" ) if not journal.entries: raise RollbackViolation( f"prefetch of escaping tool {manifest.name!r} denied: " f"no write-ahead intent record; in-flight call would orphan" ) if manifest.idempotency_scope == "branch" and not winner_selected: raise RollbackViolation( f"prefetch of escaping tool {manifest.name!r} denied: " f"branch-scoped idempotency key cannot be serialized " f"against an unselected winner (read-after-rollback race)" ) def rollback_branch( branch_id: str, journal: EffectJournal, manifests: dict, ) -> str: escaped = [e for e in journal.entries if e["branch"] == branch_id] for entry in escaped: m = manifests[entry["tool"]] if m.side_effect_class is SideEffectClass.ESCAPING and not m.has_compensation: raise RollbackViolation( f"cannot roll back branch {branch_id!r}: escaped effect " f"{entry['tool']!r} (key={entry['key']!r}) is uncompensable; " f"world state diverges from selected plan" ) return "clean" def prefetch_escaping_tool( manifest: ToolManifest, journal: EffectJournal, branch_id: str, key: str, winner_selected: bool, ) -> None: assert_prefetch_safe(manifest, journal, winner_selected) journal.write_ahead(branch_id, manifest.name, key) # ... dispatch tool call here ... ```