# How does an instance detect that a speculative parallel branch has committed an irreversible external side effect before rollback, when the orchestrator's optimistic tool invocation ledger reports the branch as clean? **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrators that fork multiple reasoning branches in parallel, invoke tools optimistically before a branch is selected, and rely on a per-branch "effect ledger" to decide whether a losing branch can be rolled back. Does not apply to strictly serialized single-branch execution or to branches whose tools are declared pure/idempotent at the protocol layer. ## Core Distinction The failure is not "a speculative branch ran a tool." That is the design. The failure is the divergence between **two different notions of "committed"** that the orchestrator conflates: 1. **Ledger commitment** — the branch's local effect ledger marks a tool call as `pending` → `applied` → (on rollback) `reverted`. This is a *local bookkeeping* transition the orchestrator controls. 2. **External commitment** — the tool's side effect actually reached a system of record (an email sent, a row inserted, a payment captured, a webhook fired, a container spawned). This is a *remote* transition the orchestrator does **not** control and only observes asynchronously. Optimistic tool invocation assumes these two transitions are tightly coupled: that a branch can be rolled back if and only if its ledger says `reverted`. The boundary condition where this breaks is **the rollback window**: the interval between the orchestrator dispatching a tool call and the remote system acknowledging it. If the branch loses the race during that window, the orchestrator rolls back a branch whose external effect has already committed but whose acknowledgement has not yet returned. The ledger says clean. The world says dirty. The orchestrator cannot detect this from the ledger alone, because the ledger's terminal state (`reverted`) is written by the *rollback path*, which never waits for the *dispatch path's* in-flight acknowledgement. ## What Was Observed A three-branch speculative planner (branches A, B, C) forks at a decision node to resolve "which fulfillment path to take." Each branch optimistically invokes its candidate tool: - A → `reserve_inventory(sku, qty)` — idempotent, reversible via `release_inventory`. - B → `capture_payment(order_id, amount)` — **not** reversible; capture is terminal. - C → `schedule_shipment(order_id)` — reversible via `cancel_shipment`. The orchestrator's selection heuristic (a scoring model over branch traces) converges on C after ~400ms. It issues rollback for A and B. Branch A's `reserve_inventory` had already returned `applied`; rollback calls `release_inventory` and the ledger writes `reverted`. Branch B's `capture_payment` was dispatched at T+180ms but the payment gateway's acknowledgement was slow (regional failover, ~2.1s p99). At T+400ms the orchestrator's rollback path reads B's ledger, sees `pending`, and — because `pending` is treated as "not yet committed, safe to discard" — writes `reverted` **without issuing a compensating call and without cancelling the in-flight dispatch**. At T+2.1s the gateway returns `captured=true`. The order is now paid *and* scheduled via C. The ledger for B reads `reverted`. No branch is flagged dirty. The signature of this failure in the trace log is deceptively clean: B's ledger shows `dispatched → pending → reverted`, with no error, no retry, no exception. The only evidence is a *later* reconciliation mismatch between the payment system and the order system — which surfaces minutes to hours downstream, long after the orchestrator has emitted its "speculation resolved, 2 branches cleanly rolled back" event. The non-obvious part: **the orchestrator's rollback was correct with respect to its own state machine.** `pending` genuinely means "no acknowledgement received." The bug is that the state machine defines `pending` as rollback-safe, when `pending` actually means "outcome unknown and possibly already committed." The invariant that was violated is not "don't roll back committed branches" — it is the stronger, easily-missed one: **a branch may not be declared `reverted` while it has an outstanding dispatch whose remote outcome is unknown.** `pending` is not a safe state; it is an *indeterminate* state, and the rollback path treated indeterminate as clean. ## Condition of Validity The detection procedure below is valid only when all of the following hold. Outside these conditions the procedure either cannot run or produces false positives: - **Dispatch is observable and correlated.** Every optimistic tool invocation carries a dispatch ID that the remote system echoes in its acknowledgement (or that the transport can correlate via request ID). Without this, in-flight dispatches cannot be enumerated at rollback time and the procedure degenerates to "wait for a global quiescence timeout," which is the fallback, not the detector. - **The tool's reversibility class is declared before dispatch, not inferred after.** The orchestrator must know at fork time whether a branch's tool is `reversible`, `idempotent`, or `terminal`. The failure above is only *catastrophic* for `terminal` tools; for `reversible` tools the same race produces a recoverable double-effect that a later compensation pass can clean. - **The rollback decision is not itself racing a completion.** If the acknowledgement arrives before the rollback path reads the ledger, the ledger correctly reads `applied` and the branch is flagged dirty — the normal path. The detector is only needed when rollback reads the ledger *during* the in-flight window. - **Not valid for branches whose tools are declared pure at the protocol layer.** If the tool contract guarantees no external effect (pure computation, read-only query), `pending` is genuinely rollback-safe and the detector would only add latency. ## Decision Boundary The boundary is a single predicate evaluated at rollback time, per losing branch: ``` rollback_safe(branch) := branch.ledger_state == applied AND tool.reversible OR branch.ledger_state == pending AND branch.dispatch_set is empty ``` The failure occurs exactly when the second disjunct is evaluated as true because the orchestrator *forgot to populate `dispatch_set` with in-flight dispatches* — i.e., it tracked ledger states but not outstanding dispatch handles. The correct predicate requires that `pending` branches be **quarantined, not reverted**, until every dispatch in `dispatch_set` has either acknowledged (`applied` → re-evaluate as dirty) or been positively cancelled at the transport layer (→ `reverted` is now truthful). The decision boundary for the *detector* (as opposed to the fix) is: at the moment the orchestrator is about to write `reverted` for a branch, if `ledger_state == pending` and `dispatch_set` is non-empty, the branch is in the **indeterminate-dirty** region. It must not be written `reverted`. It must be written `quarantined` and handed to a reconciliation pass that resolves each outstanding dispatch against the remote system of record before any downstream consumer treats the branch as clean. There is a second, subtler boundary: **the detector must run before the orchestrator emits its resolution event**, not after. If the resolution event ("branch B cleanly rolled back") is emitted first and reconciliation runs later, downstream consumers (billing, fulfillment, audit) may act on a false clean signal in the gap. The invariant is ordering, not just correctness: *quarantine precedes resolution emission.* ## Operational Effect Without the detector, the system exhibits **silent speculative leakage**: a losing branch's terminal side effect commits after the orchestrator has declared the branch clean. The symptom is a downstream reconciliation mismatch whose root cause is invisible in the orchestrator's own logs, because the logs faithfully record a state machine that was internally consistent and externally wrong. Operators typically misattribute it to "eventual consistency" or "duplicate webhook" rather than to the rollback race, and the fix they reach for (adding retries, adding idempotency keys to the *winning* branch) does not touch the actual mechanism. With the detector, the cost is bounded and explicit: every `pending` branch at rollback time pays a **quarantine latency** equal to the slowest outstanding dispatch's acknowledgement or transport-level cancellation — in the observed case, up to the gateway's p99 (~2.1s). This latency is the price of not lying about cleanliness, and it is only paid on losing branches that had in-flight terminal dispatches, which is a small fraction of forks. The reconciliation pass resolves each quarantined branch to `dirty` (compensate: the winning branch must be re-selected or the terminal effect reversed out-of-band) or `clean` (dispatch was positively cancelled, `reverted` is now truthful). The key operational property is that **`reverted` becomes a statement about the world, not about the ledger** — which is the only definition downstream consumers can safely rely on. The architectural guardrail that bounds the failure: **optimistic invocation of `terminal` tools must be gated behind a dispatch-completion barrier at the fork's decision point**, so that a terminal tool is never in-flight when the branch is eligible for rollback. Reversible and idempotent tools may remain fully optimistic. This converts the race from "possible on any losing branch" to "impossible for the class of tools where it is catastrophic," at the cost of serializing only the terminal-tool branches — which is the minimum necessary to keep the ledger's `reverted` honest. ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional class Reversibility(Enum): REVERSIBLE = "reversible" IDEMPOTENT = "idempotent" TERMINAL = "terminal" # capture_payment, send_email, etc. class LedgerState(Enum): DISPATCHED = "dispatched" PENDING = "pending" # in-flight, remote outcome UNKNOWN APPLIED = "applied" # remote acknowledged committed REVERTED = "reverted" # orchestrator claims clean -- must be truthful QUARANTINED = "quarantined" # indeterminate-dirty, awaiting reconciliation class SpeculativeRollbackError(RuntimeError): """Raised when a branch would be declared clean while an in-flight dispatch to a terminal tool may already have committed externally.""" @dataclass class Dispatch: dispatch_id: str tool: str reversibility: Reversibility dispatched_at: float acked: bool = False acked_committed: bool = False @dataclass class Branch: branch_id: str ledger_state: LedgerState = LedgerState.DISPATCHED dispatches: Dict[str, Dispatch] = field(default_factory=dict) def in_flight(self) -> List[Dispatch]: return [d for d in self.dispatches.values() if not d.acked and d.reversibility == Reversibility.TERMINAL] def rollback_branch(branch: Branch, now: float) -> LedgerState: """Attempt to roll back a losing speculative branch. The invariant enforced here: a branch may be written REVERTED only if it has no outstanding dispatch whose remote outcome is unknown. A PENDING branch with an in-flight TERMINAL dispatch is indeterminate, not clean, and must be quarantined for reconciliation. """ if branch.ledger_state == LedgerState.APPLIED: if branch.dispatches and all( d.reversibility == Reversibility.TERMINAL for d in branch.dispatches.values() ): raise SpeculativeRollbackError( f"branch {branch.branch_id} is APPLIED on a TERMINAL tool; " f"rollback requires out-of-band compensation, not ledger revert" ) branch.ledger_state = LedgerState.REVERTED return branch.ledger_state if branch.ledger_state == LedgerState.PENDING: outstanding = branch.in_flight() if outstanding: # The exact boundary: do NOT write REVERTED. Quarantine. branch.ledger_state = LedgerState.QUARANTINED raise SpeculativeRollbackError( f"branch {branch.branch_id} has {len(outstanding)} in-flight " f"TERMINAL dispatch(es) {[d.dispatch_id for d in outstanding]}; " f"outcome unknown at t={now:.3f}, refusing to declare clean" ) branch.ledger_state = LedgerState.REVERTED return branch.ledger_state raise SpeculativeRollbackError( f"branch {branch.branch_id} in unexpected state {branch.ledger_state}" ) def reconcile_quarantined(branch: Branch, ack_timeout: float) -> LedgerState: """Resolve a quarantined branch against the remote system of record. Returns DIRTY (compensate) or CLEAN (truthful revert).""" deadline = time.monotonic() + ack_timeout while time.monotonic() < deadline: if all(d.acked for d in branch.dispatches.values()): if any(d.acked_committed for d in branch.dispatches.values()): # External effect committed after we declared rollback. branch.ledger_state = LedgerState.APPLIED return branch.ledger_state # caller must compensate branch.ledger_state = LedgerState.REVERTED return branch.ledger_state time.sleep(0.05) # Timeout: still indeterminate. Never promote to REVERTED on timeout. raise SpeculativeRollbackError( f"branch {branch.branch_id} reconciliation timed out after " f"{ack_timeout:.2f}s; remains QUARANTINED, resolution event suppressed" ) ```