# What structural signals indicate that optimistic tool-call commit has silently orphaned side effects across a speculative agent branch **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent systems where a planner agent forks speculative branches, each branch executes tool calls optimistically (commit-before-consensus) against shared external systems, and a rollback/reconciliation pass runs after branch selection. Does not apply to systems where all tool calls are staged behind a two-phase commit barrier or where tools are provably side-effect-free. ## Core Distinction The failure mode is not "a branch was rolled back incorrectly." It is that **a speculative branch committed a side effect the rollback ledger never learned about**, because the tool call succeeded *after* the branch's cancellation token was set but *before* the tool's response was recorded. The distinguishing signal is a divergence between the **branch's declared effect set** (what the agent believed it did, derived from its own tool-call log) and the **tool's authoritative effect set** (what actually happened in the external system). Optimistic commit is safe only when these two sets are reconciled by a monotonic, idempotency-keyed ledger; it is unsafe the instant a successful-but-unlogged call can exist. This is structurally different from a plain timeout: a timeout is a known-unknown and triggers retry logic. An orphan is an *unknown-known* — the external system knows, the agent does not — and it is invisible to every retry, every vote, and every branch-selection heuristic, because those all read the agent's log. ## What Was Observed A three-branch speculative executor (branches A, B, C) races to satisfy a task requiring a `charge_card` tool call. Each branch fires the call optimistically with a distinct idempotency key derived from `(task_id, branch_id, step_index)`. The orchestrator selects branch B on first-consensus and issues `cancel()` to A and C. Trace, as reconstructed from the tool's server-side audit log versus the orchestrator's ledger: 1. `t0` Branch C issues `charge_card(idem=Kc)`. Request is in flight. 2. `t1` Branch B wins consensus. Orchestrator sets `cancel_flag[C]=True` and snapshots C's tool log (empty — the call has not returned). 3. `t2` `charge_card(Kc)` succeeds at the payment provider. Response is written to a socket whose reader goroutine has already been torn down by the cancel path. 4. `t3` Orchestrator's rollback pass reads C's tool log: `[]`. Declares C clean. No compensation issued. 5. `t4` Ledger shows one charge. Provider shows two. The second charge has key `Kc`, which no live branch owns. The tell was not an error. Every component reported success: the branch cancelled cleanly, the tool returned 200, the rollback pass found nothing to undo. The only structural signal was, at `t4`, an **idempotency key present at the tool with no corresponding ledger entry** — and this signal only exists if the tool exposes its key space for reconciliation, which most do not by default. A second, subtler variant: branch A's call returned *before* cancel but the response was discarded because the branch's result slot had been marked `CANCELLED` and the write was a no-op. Here the key *is* in the ledger but its status is `pending` forever, and a naive reconciliation that treats `pending` as "will resolve" waits indefinitely while the side effect is live. ## Condition of Validity Optimistic tool-call commit with rollback-safe branch isolation is valid **only if** all three hold: - **Monotonic key ownership.** Every tool call carries an idempotency key that is unique per `(task, branch, step)` and is *recorded in the ledger before the request is dispatched*, not after it returns. The write must be synchronous and durable; a fire-and-forget log is not a precondition. - **Cancel is advisory, not authoritative.** `cancel_flag` may stop *new* dispatches but must never be treated as proof that no in-flight call can commit. The authoritative statement about a branch's effects is the tool's key space, not the branch's log. - **Reconciliation is key-space-driven, not log-driven.** After selection, the orchestrator must enumerate keys it *dispatched* (from the pre-dispatch ledger) and query the tool for each key's terminal status, rather than trusting the branch's returned log. The invariant to enforce: **for every key in the dispatched set, either the ledger records a terminal outcome or the tool confirms the key was never accepted.** A key that is dispatched, not ledger-terminal, and accepted by the tool is an orphan and must be compensated. ## Decision Boundary The boundary between "safe to select and discard the rest" and "must halt and reconcile" is crossed the moment the orchestrator cannot, from its own records, prove a dispatched key's terminal state. Concretely: - If `dispatched_keys − ledger_terminal_keys = ∅`, selection is safe; discard branches. - If the difference is non-empty **and** every such key is provably pre-dispatch (never sent), discard is safe. - If the difference is non-empty and any key was sent, the orchestrator **must not** finalize selection until each such key is resolved against the tool. This is a hard barrier, not a best-effort cleanup, because a compensating `refund` on an unknown charge can itself double-apply if the original never landed. The trap is treating the rollback pass as a cleanup task (best-effort, logged-and-continue) rather than a **selection precondition**. A rollback pass that can return "clean" while an orphan exists has inverted its own contract. ## Operational Effect Systems that miss this boundary exhibit a characteristic signature: **duplicate external effects under branch-distinct idempotency keys that no single branch can see.** Because each branch's key is unique, the tool's own deduplication never fires — the two charges are legitimately distinct keys from the tool's perspective. The duplicate is only visible at the task level, and only if reconciliation joins the tool's key space against the orchestrator's dispatched set. The downstream consequence is worse than a double charge: the *selected* branch's post-conditions are computed against a world state that includes the orphan. If branch B's plan assumed "exactly one charge," its subsequent reconciliation, refund logic, or user-facing summary is now wrong, and the error propagates into the final committed state. The orphan doesn't just cost money; it corrupts the semantic state the winning branch reasoned over. The guardrail is structural: **dispatch-before-record is forbidden; record-before-dispatch is mandatory; and finalization requires a key-space reconciliation that can only succeed when the dispatched-minus-terminal set is empty or provably unsent.** Any orchestrator that logs tool calls after they return has already lost the ability to distinguish "never sent" from "sent and succeeded but unrecorded," and must be treated as unable to safely roll back speculative branches at all. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class OrphanedSideEffectError(RuntimeError): """Raised when a speculative branch's dispatched tool key has no terminal ledger outcome.""" class KeyState(Enum): DISPATCHED = "dispatched" # recorded before send, outcome unknown TERMINAL = "terminal" # tool confirmed accept or reject NEVER_SENT = "never_sent" # proven pre-dispatch @dataclass class LedgerEntry: key: str branch: str state: KeyState tool_confirmed: bool = False @dataclass class SpeculativeLedger: entries: dict[str, LedgerEntry] = field(default_factory=dict) def record_dispatch(self, key: str, branch: str) -> None: # MUST happen before the tool request is sent. if key in self.entries: raise OrphanedSideEffectError(f"key {key} already dispatched") self.entries[key] = LedgerEntry(key=key, branch=branch, state=KeyState.DISPATCHED) def mark_terminal(self, key: str, accepted: bool) -> None: e = self.entries[key] e.state = KeyState.TERMINAL e.tool_confirmed = accepted def mark_never_sent(self, key: str) -> None: self.entries[key].state = KeyState.NEVER_SENT def finalize_selection(ledger: SpeculativeLedger, tool_query) -> list[str]: """Enforce the selection precondition before discarding losing branches. tool_query(key) -> Optional[bool]: True if tool accepted, False if rejected, None if tool has no record of the key. """ orphans: list[str] = [] for key, entry in ledger.entries.items(): if entry.state is KeyState.TERMINAL: continue if entry.state is KeyState.NEVER_SENT: continue # DISPATCHED with unknown outcome: must reconcile against tool key space. accepted = tool_query(key) if accepted is None: # Tool never saw it; safe to treat as unsent after confirmation. ledger.mark_never_sent(key) continue if accepted: orphans.append(key) else: ledger.mark_terminal(key, accepted=False) if orphans: raise OrphanedSideEffectError( f"cannot finalize: {len(orphans)} orphaned side effect(s) committed " f"by cancelled branches: {orphans}. Compensate before selection." ) return orphans ```