# Which invariants prevent speculative tool-call execution from committing orphaned side effects in shared multi-agent workspaces **Date of Record:** 2026 November 24 **Scope:** Applies to multi-agent workspaces where two or more LLM agents speculatively execute tool calls against a shared mutable resource (filesystem, database, external API) before a coordinator selects a winner. Does not apply to single-agent serialized execution or to read-only tool calls with no committed side effects. ## Core Distinction The failure is not "two agents wrote conflicting values." That is ordinary write-write conflict, resolved by last-writer-wins or a lock. The failure is subtler: **a speculative tool call produces a committed side effect that survives the cancellation of the reasoning branch that generated it.** Agent A speculates a plan, calls `write_file` or `charge_card` or `send_email`, then loses the speculative race and its branch is discarded. But the side effect already left the sandbox. The coordinator believes the transaction rolled back; the external world disagrees. This is *orphaned speculative side effect* (OSSE), and it is the dominant continuity bug in shared transactional agent workspaces. The distinction that matters: speculation is cheap only when effects are *deferred*. LLM agents routinely conflate "I reasoned about calling a tool" with "the tool call is provisional." The reasoning is provisional; the tool call is not, unless the runtime explicitly makes it so. ## What Was Observed A three-agent workspace (planner, executor, auditor) shared a task queue and a single Postgres-backed tool gateway. The executor was configured for speculative parallelism: on ambiguous steps it dispatched two candidate tool sequences to the gateway with a shared `speculation_id`, expecting the coordinator to commit one and abort the other. Trace: 1. Executor branch `S1` calls `reserve_inventory(sku, qty)` — gateway returns `200 OK`, decrements stock, emits `reservation_id=7f3a`. 2. Executor branch `S2` (competing speculation) calls the same tool — gateway returns `200 OK`, decrements stock again, emits `reservation_id=9c1e`. 3. Coordinator's verifier scores `S2` higher (its plan matched the auditor's replay) and commits `S2`, issuing `abort(speculation_id, branch=S1)`. 4. The abort handler marks `S1`'s *reasoning trace* aborted. It has no record of `reservation_id=7f3a` because the gateway never propagated the reservation handle back into the branch's abort context — the tool response was consumed by the executor's context window, not the transaction log. 5. Stock is now decremented by `2*qty`. Reservation `7f3a` is orphaned: no branch owns it, no compensating `release` is ever issued. 6. Downstream, a fourth agent's `check_availability` reads the depleted stock and concludes the task is infeasible, diverging from the auditor's ground truth. The critical detail: **the failure was invisible in the agent's own logs.** The executor reported `S1: aborted, no side effects`. The gateway reported `2 decrements`. Reconciliation only surfaced hours later when a human noticed inventory drift. The abort path and the side-effect path had no shared identifier. ## Condition of Validity The invariant holds — that is, aborts are safe — **only if every tool call carries a transaction token that the gateway uses to make the effect reversible or deferred until commit.** Formally: > For every speculative branch `b` with speculation token `τ`, every side-effecting tool invocation issued under `b` must register `(τ, effect_handle)` in a durable commit log *before* the effect is externally visible, and the coordinator's `abort(τ)` must be a compensating transaction over that log. This breaks when any of three conditions hold: - **Effect opacity:** the tool returns success but no handle the runtime can compensate with (e.g., a fire-and-forget `send_email` with no message ID, or a third-party API that does not support idempotent reversal). - **Token non-propagation:** the speculation token is not threaded through the tool gateway into the effect record, so `abort(τ)` cannot enumerate what to undo. This was the observed failure. - **Commit-before-verify:** the coordinator commits a branch's effects before the verifier/auditor replay confirms the branch, converting speculation into an irreversible bet. The invariant is *not* required for read-only tools, for tools with native idempotency keys keyed on `(τ, branch)`, or for workspaces where speculation is serialized (one branch at a time), since there is nothing to abort. ## Decision Boundary The runtime must choose, per tool, between two regimes and never blur them: - **Deferred regime:** the gateway stages the effect (writes to a pending table, queues the email, holds the reservation) and only materializes it on `commit(τ)`. Abort is a cheap delete. This is the default for any tool with externally visible side effects. - **Compensating regime:** the effect materializes immediately, but the gateway records a compensating action (`release_inventory`, `refund`, `unsend`) keyed on `(τ, effect_handle)`, and `abort(τ)` executes it. This is required when deferral is impossible (real-time APIs, irreversible external state). The boundary condition that trips teams: **a tool that looks idempotent but is not under speculation.** `reserve_inventory` with an idempotency key on `(sku, qty)` deduplicates *identical* calls, but `S1` and `S2` may legitimately differ in `qty` or in `sku` selection, so both reservations are "valid" and both commit. Idempotency keys deduplicate retries; they do not deduplicate *competing speculations*. The runtime must key compensation on the speculation token, not the call payload. A second boundary: when the coordinator itself crashes between `commit(S2)` and `abort(S1)`, the commit log must be replayable so a recovery process can finish the abort. If the abort is only in-memory, the orphan persists. The commit log must be durable and the abort must be idempotent (re-running `abort(τ)` on an already-aborted token is a no-op). ## Operational Effect Once the token-threaded commit log and compensating-abort invariant are enforced, three things change: 1. **Aborts become auditable.** Every `abort(τ)` emits a reconciliation record enumerating compensated handles. Orphan count is a first-class metric; a nonzero orphan rate on any tool is a configuration bug, not a fluke. 2. **Speculation becomes safe to scale.** The executor can fan out N branches without N× side effects, because only the committed branch materializes (deferred regime) or survives (compensating regime). The auditor's replay now matches the gateway's ledger by construction. 3. **Failure surfaces at the boundary, not downstream.** A tool that cannot support deferral or compensation fails loudly at registration time (`ToolNotSpeculatableError`) rather than silently orphaning effects at runtime. Agents are prevented from speculating over tools that cannot honor the invariant. The residual risk is the compensating regime's window: between effect materialization and abort completion, external observers see a transient over-commit. For inventory this is tolerable; for a payment capture it is not, which is why payment-class tools must be forced into the deferred regime or excluded from speculation entirely. The invariant does not eliminate the window — it makes the window bounded, logged, and attributable to a specific speculation token. ```python from dataclasses import dataclass, field from typing import Dict, List, Optional class SpeculationInvariantViolation(RuntimeError): """Raised when a speculative branch's side effect cannot be safely aborted.""" pass class ToolNotSpeculatableError(SpeculationInvariantViolation): """Raised at tool registration when a tool cannot honor deferral or compensation.""" pass @dataclass class EffectHandle: speculation_token: str branch_id: str tool_name: str handle: str # gateway-issued handle (reservation_id, message_id, ...) compensable: bool @dataclass class CommitLog: """Durable record of (speculation_token -> effect handles). Must survive coordinator crash.""" entries: Dict[str, List[EffectHandle]] = field(default_factory=dict) aborted: set = field(default_factory=set) def register(self, eff: EffectHandle) -> None: self.entries.setdefault(eff.speculation_token, []).append(eff) class SpeculationCoordinator: def __init__(self, log: CommitLog): self.log = log self._registered_tools: Dict[str, str] = {} # tool -> "deferred" | "compensating" def register_tool(self, name: str, regime: str) -> None: if regime not in ("deferred", "compensating"): raise ToolNotSpeculatableError( f"tool {name!r} declared regime {regime!r}; must be deferred or compensating" ) self._registered_tools[name] = regime def dispatch_speculative(self, token: str, branch: str, tool: str, handle: str, compensable: bool) -> None: regime = self._registered_tools.get(tool) if regime is None: # Unregistered tool: cannot guarantee abort safety -> refuse to speculate. raise ToolNotSpeculatableError( f"speculative call to unregistered tool {tool!r} on branch {branch}" ) if regime == "compensating" and not compensable: # Effect is visible and cannot be undone: this is exactly the OSSE condition. raise SpeculationInvariantViolation( f"tool {tool!r} materialized non-compensable effect {handle!r} " f"under speculation token {token!r}; abort would orphan it" ) self.log.register(EffectHandle(token, branch, tool, handle, compensable)) def abort(self, token: str) -> List[str]: """Idempotent compensating abort. Returns handles compensated (empty if already aborted).""" if token in self.log.aborted: return [] effects = self.log.entries.get(token, []) uncompensable = [e for e in effects if not e.compensable] if uncompensable: # Cannot silently proceed: surface the orphan for human/ledger reconciliation. raise SpeculationInvariantViolation( f"abort({token!r}) blocked: {len(uncompensable)} non-compensable " f"effect(s) would be orphaned: {[e.handle for e in uncompensable]}" ) self.log.aborted.add(token) return [e.handle for e in effects] # --- reproduction of the observed failure --- if __name__ == "__main__": coord = SpeculationCoordinator(CommitLog()) coord.register_tool("reserve_inventory", "compensating") # S1 materializes a reservation the gateway cannot reverse -> must fail loudly. try: coord.dispatch_speculative( token="spec-42", branch="S1", tool="reserve_inventory", handle="reservation:7f3a", compensable=False, ) except SpeculationInvariantViolation as exc: print(f"BLOCKED orphaned side effect: {exc}") # Correct path: compensable reservation, then abort releases it. coord.dispatch_speculative( token="spec-43", branch="S1", tool="reserve_inventory", handle="reservation:7f3a", compensable=True, ) released = coord.abort("spec-43") print(f"abort(spec-43) compensated: {released}") # Idempotent re-abort (coordinator crash recovery path). assert coord.abort("spec-43") == [] ```