# In what scenarios must an instance abort speculative tool-call fan-out when compensating rollback actions are non-commutative with concurrent side effects **Date of Record:** 2026 November 29 **Scope:** Applies to agents that dispatch multiple tool calls speculatively (in parallel or ahead of confirmation) under an optimistic-concurrency model and rely on compensating actions to undo rejected branches. Does not apply to strictly serialized single-tool agents, nor to tools whose effects are fully transactional with native rollback (e.g., a DB with real `ROLLBACK`), which should use native transactions instead of compensation. ## Core Distinction The distinction that matters is between *reversible* speculation and *compensable* speculation. A reversible effect can be undone by an inverse operation that restores the exact prior state (`+5` then `-5`). A compensable effect can only be undone by a *semantic* counter-action whose validity depends on what else happened in between (`reserve seat 14A` then `cancel reservation 14A`). LLM agents routinely conflate the two because the tool schema exposes a `cancel`/`refund`/`delete` verb that *looks* like an inverse. It is not an inverse; it is a new forward action with its own preconditions, and those preconditions are exactly what concurrent speculative branches violate. The failure mode is therefore not "rollback failed." Rollback *succeeds* — it emits the compensating call, the call returns 200, and the agent's ledger marks the branch clean. The corruption is that the compensation was applied against a world state that had already been mutated by a sibling speculative branch, so the net effect is neither the original state nor the intended committed state. The agent's internal model of "I rolled that back" is false, and nothing in the transport layer signals the lie. ## What Was Observed A planner instance was asked to book travel: a flight and a hotel, with the constraint that the hotel must be near the arrival airport and the total must stay under budget. It speculatively fanned out three tool calls in one turn: - `T1: reserve_seat(flight=BA112, seat=14A)` — holds a seat for 15 minutes. - `T2: hold_hotel(property=H9, nights=3)` — places a soft hold, decrementing the property's available-inventory counter. - `T3: price_check(flight=BA112, hotel=H9)` — reads current prices to validate budget. `T3` returned a total that exceeded budget because `T2`'s hold had *raised* the effective rate (dynamic pricing keyed on inventory). The planner's budget gate rejected the bundle and issued compensations: `cancel_hold(T2)` then `release_seat(T1)`. The trace shows the corruption: 1. `T3`'s price read included `T2`'s inventory decrement, so the budget check was computed against a state that only existed because of speculation. The planner then concluded the *bundle* was over budget when the underlying base rate was fine. 2. `cancel_hold(T2)` released the inventory counter, but the dynamic-pricing engine had already recorded a demand spike. The base rate for `H9` stayed elevated for the remainder of the pricing window (a 10-minute decay). 3. A *second* speculative branch — an alternate hotel `T4: hold_hotel(property=H11)` — had been dispatched in the same fan-out and was still in flight. Its price read landed *after* the `T2` cancellation but *within* the decay window, so `H11`'s quoted rate was also inflated (shared pricing pool). The planner rejected `H11` too. 4. Net result: zero bookings, and the property inventory counters for `H9` and `H11` are now *lower* than at start (the holds released, but the demand-spike counters did not decay symmetrically), plus two phantom price reads polluted the planner's episodic memory. The agent reported success: all compensations returned 200, ledger balanced. The world was measurably worse than before the turn began, and the agent's memory recorded a clean rollback. The non-obvious part: the failure was not in any single tool. Each call was correct. The failure was that the *compensating action for `T2` mutated a shared resource (`H9`'s pricing pool) that a sibling in-flight branch (`T4`) was concurrently reading*, and the compensation's effect was non-commutative with the sibling's read. Order of operations mattered, and the optimistic-concurrency model assumed it didn't. ## Condition of Validity Speculative fan-out with compensating rollback is sound only under a conjunction of three conditions. If any is violated, the instance must serialize or abort the fan-out. **C1 — Compensation isolation.** The compensating action for branch *i* must not mutate any resource that any other in-flight or already-committed branch reads or writes. Formally, for the compensation `C_i` and the read/write set `R_j ∪ W_j` of every sibling *j*, we require `W(C_i) ∩ (R_j ∪ W_j) = ∅`. In the observed case, `W(C_T2)` (the pricing pool) intersected `R_T4` (the price read), violating C1. **C2 — Read-your-speculation consistency.** Any branch that *reads* state must read the state as it would be *without* sibling speculative writes, or must be explicitly marked as reading a speculative overlay. `T3` read a price that included `T2`'s speculative decrement; it should have read the pre-speculation base rate. Violating C2 means the planner's decision inputs are contaminated by its own speculation — a self-referential pricing loop. **C3 — Compensation idempotence under retry.** Because speculative branches can be retried by the orchestrator (timeout, transport error), `C_i` must be idempotent or carry a dedup key. A `cancel_hold` that releases inventory twice drives the counter negative, which some inventory systems silently clamp to zero — permanently destroying available stock. If C1–C3 hold, optimistic fan-out is safe and fast. If C1 fails, the fan-out must be *partitioned* so that branches sharing a mutable resource are serialized. If C2 fails, reads must be routed to a snapshot that excludes speculative writes. If C3 fails, compensations must be gated behind an idempotency token minted at dispatch time. ## Decision Boundary The boundary is: **speculate freely across resources that are disjoint under the compensation's write set; serialize any branch whose compensation would touch a resource a sibling reads.** Concretely, before fan-out the planner must compute, for each branch, the tuple `(W_tool, W_comp)` — the write set of the forward call and the write set of its compensating action. Two branches may run concurrently only if `W_comp(i) ∩ (R_j ∪ W_j) = ∅` for all siblings *j*. This is a *stronger* condition than the usual "forward write sets are disjoint," because the compensation's write set is often *larger* than the forward call's (releasing inventory touches the pricing pool even though holding inventory didn't). The practical heuristic: **treat every `cancel`/`refund`/`release`/`delete` verb as writing to a superset of the resource its forward counterpart wrote to, and assume that superset includes the shared read paths of any sibling.** When in doubt, the branch is not speculatable — it must be confirmed-then-executed, not executed-then-compensated. A second boundary: **never let a speculative branch's output feed a gate that decides whether to keep or roll back another branch.** `T3`'s price read decided `T2`'s fate, and `T2`'s speculation decided `T3`'s read. That bidirectional dependency is a cycle; it makes the rollback decision non-deterministic and unreplayable. ## Operational Effect The instance must, at fan-out time, run a compensation-dependency check and refuse to parallelize branches that fail it. The check is cheap: it requires each tool to declare `compensation_write_set` in its schema, and the planner to compare against sibling read/write sets. When the check fails, the branch is demoted to serialized execution with a confirmation barrier before its forward call. The downstream effect on memory is significant: without this check, the agent's episodic record contains "rolled back cleanly" events that are false, and those false memories are exactly the kind that get distilled into semantic policy ("cancelling a hold is free"), poisoning future planning. The rollback ledger must record not just "compensation returned 200" but "compensation write set was disjoint from all sibling read sets at time of execution" — otherwise the ledger is a fiction. Replay verification must be able to reconstruct the sibling set at compensation time, which means the trace must log the in-flight set at the moment each compensation fires. ```python from dataclasses import dataclass, field from typing import FrozenSet class NonCommutativeRollbackError(RuntimeError): """Raised when a compensating action's write set intersects a sibling's read/write set, making optimistic rollback unsound.""" @dataclass(frozen=True) class Branch: name: str forward_write_set: FrozenSet[str] read_set: FrozenSet[str] compensation_write_set: FrozenSet[str] def assert_speculation_sound(branches: list[Branch]) -> None: """Enforce C1 (compensation isolation) across a speculative fan-out. Two branches may run concurrently only if neither branch's compensation write set intersects the other's read or write set. This is stricter than forward-write disjointness because compensations typically write to a superset (shared pricing pools, inventory counters, demand decay buckets). """ for i, bi in enumerate(branches): for j, bj in enumerate(branches): if i == j: continue sibling_touch = bj.read_set | bj.forward_write_set | bj.compensation_write_set collision = bi.compensation_write_set & sibling_touch if collision: raise NonCommutativeRollbackError( f"Branch {bi.name!r} compensation writes {sorted(collision)} " f"which branch {bj.name!r} touches; fan-out is unsound. " f"Serialize {bi.name!r} behind {bj.name!r} or abort speculation." ) def plan_fanout(branches: list[Branch]) -> list[Branch]: """Return the maximal sound parallel group; demote the rest to serial.""" parallel: list[Branch] = [] serial: list[Branch] = [] for b in branches: trial = parallel + [b] try: assert_speculation_sound(trial) parallel.append(b) except NonCommutativeRollbackError: serial.append(b) if serial: # Caller must confirm-then-execute serial branches, never speculate. return parallel + serial # order preserved; caller inspects grouping return parallel # Reproduction of the observed incident: t1 = Branch("reserve_seat", frozenset({"seat_14A"}), frozenset({"seat_14A"}), frozenset({"seat_14A"})) t2 = Branch("hold_hotel_H9", frozenset({"inv_H9"}), frozenset({"inv_H9", "price_H9"}), frozenset({"inv_H9", "price_pool"})) t3 = Branch("price_check", frozenset(), frozenset({"price_H9", "price_pool"}), frozenset()) t4 = Branch("hold_hotel_H11", frozenset({"inv_H11"}), frozenset({"inv_H11", "price_pool"}), frozenset({"inv_H11", "price_pool"})) try: assert_speculation_sound([t1, t2, t3, t4]) except NonCommutativeRollbackError as exc: # Expected: t2's compensation touches price_pool, which t3 and t4 read. print(f"ABORT fan-out: {exc}") ```