# Which invariants prevent speculative parallel agent plans from corrupting shared state when a divergent branch rolls back **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrators that fork a single agent plan into N speculative parallel branches against a shared tool/state substrate and commit the first branch whose outcome matches a success predicate, aborting the rest. Does not apply to branches operating on isolated sandboxes with no shared mutable resources (filesystem, database, message bus, external API side effects). ## Core Distinction The failure mode is not "a branch failed." It is **rollback that is not idempotent against a substrate that already absorbed the branch's side effects before divergence was detected**. Speculative execution of agent plans is safe only when every branch's side effects are *revocable* or *isolated*; the invariant that matters is not "we can roll back," but "we can roll back *without the rollback itself being observed by another branch or a downstream consumer*." The non-obvious boundary: divergence is detected at the *reasoning* layer (the branch's conclusion contradicts the commit predicate), but the branch's *tool calls* have already mutated shared state. The reasoning rollback and the state rollback are on different clocks. A branch can be logically aborted microseconds after it emitted a `send_email` or `INSERT`, and the abort is correct while the email is already sent. Speculative plans that treat "abort the branch" as equivalent to "undo the branch" are unsound. ## What Was Observed An orchestrator forks a 4-way speculative plan for a customer-refund agent: each branch independently decides whether to issue a refund and via which path (`stripe.refund`, `ledger.credit`, `manual_queue`, `escalate`). The commit predicate accepts the first branch that returns `status == "refunded"` with a matching amount. Branches run concurrently against a shared ledger service. Trace: 1. Branch B2 calls `ledger.credit(account, 40.00)` — succeeds, ledger balance decremented, returns `txn_8812`. 2. Branch B4, running 180ms behind, calls `ledger.credit(account, 40.00)` — also succeeds, returns `txn_8813`. The ledger service is not idempotent on `(account, amount)`; it has no dedup key. 3. B2 returns `status == "refunded"`, amount matches. Orchestrator commits B2 and aborts B3, B4. 4. Abort of B4 invokes a compensating `ledger.reverse(txn_8813)`. This succeeds. 5. **But** the orchestrator's abort path is best-effort: it fires `reverse` and does not await confirmation before marking B4 `ABORTED`. B4's `reverse` races with B2's commit, and in 1 of ~40 runs the reverse lands *after* the ledger's end-of-minute reconciliation snapshot, producing a transient over-credit visible to the finance dashboard and to a downstream fraud agent that reads the same ledger. The observed breakage is not double-refund at settlement. It is a **transient state window** in which a downstream *reader agent* observes a ledger balance that never should have existed. That reader agent then writes a fraud flag into a shared case record. The flag is not rolled back — it is a side effect of a side effect. The critical detail: the orchestrator's rollback was *correct at the branch layer* and *incorrect at the substrate layer*, because the substrate's read model (the reconciliation snapshot, the fraud agent's view) is not covered by the branch's transactional boundary. ## Condition of Validity Rollback-on-divergence is sound only if all three hold simultaneously: - **C1 — Effect revocability or isolation.** Every tool a branch may call is either (a) isolated to a branch-scoped overlay (copy-on-write ledger, staged transaction, outbox), or (b) has an idempotent compensating action keyed by a branch-unique token, so a late-arriving compensation cannot be confused with a legitimate second effect. - **C2 — Compensation visibility ordering.** The compensating action must complete and be *observed* by every shared reader before the committed branch's effects are published. Equivalently: no reader may observe branch effects until all sibling branches are quiesced-and-compensated. This is a barrier, not a race. - **C3 — Side-effect provenance.** Any downstream agent that reads shared state during the speculation window must be able to attribute what it read to a specific speculative branch, so its own derived writes can be invalidated when that branch is aborted. Without provenance, a fraud flag derived from a transient over-credit is orphaned. C1 without C2 yields the observed transient-window bug. C2 without C3 yields correct ledger state but poisoned derived records. C3 without C1 yields a full audit trail of a double-charge that still happened. ## Decision Boundary The orchestrator must choose, per plan, between **speculate-and-compensate** and **speculate-and-isolate**, and the choice is forced by the tool inventory, not by latency budget: - If **every** tool in the branch's reachable call graph is overlay-capable (staged writes, branch-scoped sandboxes, outbox-pattern emits), use isolation. Commit = promote overlay; abort = discard overlay. No compensation, no C2 barrier needed, C3 satisfied because the overlay never leaks. - If **any** reachable tool is a direct, non-idempotent external effect (email, payment rail, physical dispatch), you may not speculate across it. Either serialize that step after the commit decision, or wrap it in a two-phase reservation that the external system honors. There is no third option; "we'll compensate fast" is the bug. - The boundary is **reachability, not current call**. A branch that *might* call `send_email` depending on its reasoning must be treated as if it did. Because the reasoning is probabilistic, the orchestrator cannot statically bound the call graph; it must bound it by capability declaration on the tool schema, and reject speculative forks whose declared capability set intersects the non-revocable set. The invariant to enforce: **`speculatable(plan) ⟺ reachable_tools(plan) ⊆ revocable ∪ isolated`**, evaluated against the *declared* capability closure, not the observed call trace. ## Operational Effect Enforcing the invariant converts a class of silent shared-state corruption into an up-front planning rejection. The orchestrator's fork step fails closed: a plan whose capability closure includes non-revocable tools is not forked speculatively; it is run single-path with the commit decision made before the irreversible call. Latency regresses on those plans (no parallelism), but the finance-visible transient window, the orphaned fraud flags, and the reconciliation-vs-compensation race disappear entirely. The measurable signature of the fix: the reconciliation snapshot's over-credit count goes to zero, and the fraud agent's derived-flag invalidation rate (flags written then retracted) drops to zero because no flag is ever written against a speculative state. The cost is a planning-time capability-closure check that must be re-run whenever a tool schema changes — a schema drift that adds a non-revocable method to a previously-isolated tool silently re-opens the boundary, so the closure check must be keyed on schema version, not tool name. ```python from dataclasses import dataclass from enum import Enum from typing import FrozenSet class SpeculationBoundaryError(RuntimeError): """Raised when a speculative fork would cross a non-revocable effect.""" class EffectClass(Enum): ISOLATED = "isolated" # branch-scoped overlay; discard on abort REVOCABLE = "revocable" # idempotent compensating action exists IRREVERSIBLE = "irreversible" # external, non-idempotent, no reservation @dataclass(frozen=True) class ToolCapability: name: str effect: EffectClass schema_version: str @dataclass(frozen=True) class Plan: plan_id: str declared_tools: FrozenSet[str] def assert_speculatable(plan: Plan, registry: dict[str, ToolCapability]) -> None: """ Enforce: speculatable(plan) <=> reachable_tools(plan) subset of (ISOLATED union REVOCABLE), evaluated against declared capability closure and schema version, not observed call trace. """ closure = set() for tool_name in plan.declared_tools: cap = registry.get(tool_name) if cap is None: # Unknown tool => unknown effect => assume irreversible. raise SpeculationBoundaryError( f"plan {plan.plan_id}: tool {tool_name!r} absent from registry; " f"cannot prove revocability, refusing speculative fork" ) closure.add(cap) irreversible = [c for c in closure if c.effect is EffectClass.IRREVERSIBLE] if irreversible: names = ", ".join(f"{c.name}@{c.schema_version}" for c in irreversible) raise SpeculationBoundaryError( f"plan {plan.plan_id}: capability closure includes irreversible " f"effects [{names}]; run single-path with pre-commit decision, " f"do not speculate across these tools" ) def fork_speculative(plan: Plan, registry: dict[str, ToolCapability], n: int) -> list[Plan]: if n < 1: raise SpeculationBoundaryError(f"plan {plan.plan_id}: fork width {n} invalid") assert_speculatable(plan, registry) return [Plan(f"{plan.plan_id}#b{i}", plan.declared_tools) for i in range(n)] ```