# Which invariants prevent speculative agent rollback from committing phantom side effects during compensation **Date of Record:** 2026 November 22 **Scope:** Applies to agents that execute speculative branches (tentative tool calls, pre-committed plans, or forked sub-agents) and rely on compensating actions to undo them on partial failure. Does not cover purely read-only agents or single-shot inference with no external state mutation. ## Core Distinction The naive mental model treats rollback as the inverse of execution: if step `S` mutated world state `W → W'`, then a compensation `C(S)` restores `W`. This holds for *deterministic, idempotent, order-independent* effects. It fails for agent systems because three properties break the inverse assumption: 1. **Compensations are themselves probabilistic tool calls.** `C(S)` may fail, partially succeed, or succeed with a *different* side effect than expected (e.g., a "delete" that soft-deletes, leaving a tombstone a later read treats as live). 2. **Speculative branches observe each other.** A forked agent's tentative write can be read by a sibling before the fork is resolved, so rollback must invalidate *derived* state, not just the origin write. 3. **The compensation log is not the execution log.** Agents reconstruct "what to undo" from episodic memory that may have been distilled, truncated, or reordered. The boundary failure is therefore not "rollback failed." It is **rollback succeeded against the recorded intent while the world diverged from that record** — a *phantom compensation* that leaves the system believing it is clean when it is not. ## What Was Observed A planner agent forks three speculative sub-agents (`A`, `B`, `C`) to reserve inventory through an external `reserve(item, qty)` tool. Each sub-agent appends a `ReservationRecord{id, item, qty, branch}` to episodic memory on success. The orchestrator selects branch `B`, and issues `release()` compensations for `A` and `C`. Observed trace: - `A` and `C` both reserved the same `item=X`. The tool's backend coalesces reservations by `(item)` into a single counter, returning distinct `reservation_id`s but incrementing one shared quantity. - `A.release()` decrements the shared counter by `A.qty`. `C.release()` decrements by `C.qty`. Because `B`'s reservation was *also* counted in the same counter and was never released, the net counter after both releases equals `B.qty` — correct by arithmetic. - However, `B`'s `ReservationRecord` was written *before* `A`/`C` released, and the orchestrator's post-commit reconciliation read the counter *after* release. The reconciliation diff was attributed to `B`, so `B`'s recorded `qty` was silently rewritten to the post-release counter value — **double-counting `B`'s own reservation as a phantom surplus**. - A downstream `commit()` on `B` then committed `2×B.qty`. The compensation "succeeded" (both `release` calls returned `ok`), the invariant `sum(active reservations) == committed qty` held *at the moment of each individual call*, and yet the terminal state violated it. This is the non-obvious part: **per-operation invariants are not compositional across speculative branches when the tool backend shares mutable state across branches.** ## Condition of Validity Rollback-by-compensation is only sound when *all* of the following hold simultaneously: - **Effect isolation:** each speculative branch's mutations are namespaced (distinct keys, transactional scopes, or version-tagged writes) such that no branch's compensation can alter another branch's observable state. - **Compensation determinism:** `C(S)` is a total function of `S`'s recorded effect, not of current world state. Compensations that read-then-write (like "release the reservation you find") violate this. - **Monotone observation:** the orchestrator never re-derives a branch's committed quantity from a world read taken after any sibling compensation. Reads used for commit must be pinned to a pre-compensation snapshot. - **Idempotent compensation:** replaying `C(S)` (due to retry or duplicate delivery) is a no-op. The shared-counter backend is *not* idempotent under duplicate `release` — a retried `A.release()` over-decrements. When any of these fails, the compensation is *observationally* correct and *semantically* wrong. ## Decision Boundary The agent must decide, at fork-resolution time, whether the backend supports isolated speculative effects. The boundary: - **If the tool exposes branch-scoped handles** (transaction IDs, draft states, versioned keys): commit by promoting the selected handle, discard siblings by dropping handles. No compensation is issued at all — this is the correct architecture. - **If the tool only exposes flat mutate/compensate:** the orchestrator MUST NOT commit a branch whose quantity was derived from a post-sibling-release read. It must either (a) re-read from a pinned pre-release snapshot, or (b) refuse to commit and escalate, because the phantom-compensation risk is unbounded. The failure occurs precisely when the agent *chooses to compensate* against a backend that does not support isolation, then *trusts a post-compensation read* to finalize the surviving branch. ## Operational Effect Concretely, the orchestrator must enforce two invariants: 1. **Compensation isolation invariant:** before issuing any `C(S)`, assert that `S`'s effect handle is disjoint from every other live branch's handle. If not, abort to escalation rather than compensate. 2. **Snapshot pinning invariant:** the value committed for the surviving branch must equal the value recorded at *branch creation*, never a value re-derived from any read taken after `t0 = min(compensation times)`. Violating (1) creates phantom compensations. Violating (2) creates phantom commits. Both pass per-call checks and fail end-to-end reconciliation — the signature of this failure mode. ```python import time from dataclasses import dataclass, field from typing import Dict, List class PhantomCompensationError(RuntimeError): """Raised when a compensation would act on a handle shared with a live branch.""" pass class SnapshotDriftError(RuntimeError): """Raised when a commit value is derived from a read taken after compensation began.""" pass @dataclass class ReservationRecord: reservation_id: str item: str qty: int branch: str effect_handle: str # backend key; shared handles => non-isolated recorded_at: float = field(default_factory=time.time) @dataclass class Branch: name: str records: List[ReservationRecord] = field(default_factory=list) class SpeculativeOrchestrator: def __init__(self): self.branches: Dict[str, Branch] = {} self.compensation_started_at: float = float("inf") def register(self, rec: ReservationRecord) -> None: self.branches.setdefault(rec.branch, Branch(rec.branch)).records.append(rec) def _assert_isolated(self, target: Branch, survivors: List[Branch]) -> None: target_handles = {r.effect_handle for r in target.records} for sib in survivors: shared = target_handles & {r.effect_handle for r in sib.records} if shared: raise PhantomCompensationError( f"branch {target.name!r} shares effect handles {shared} " f"with live survivor {sib.name!r}; compensation would " f"mutate survivor state" ) def compensate(self, target: Branch, survivors: List[Branch]) -> None: self._assert_isolated(target, survivors) self.compensation_started_at = min( self.compensation_started_at, time.time() ) for rec in target.records: # backend release() elided; in real code this is a tool call pass def commit(self, survivor: Branch, observed_qty: int) -> int: pinned = sum(r.qty for r in survivor.records) if observed_qty != pinned: raise SnapshotDriftError( f"survivor {survivor.name!r}: observed qty {observed_qty} " f"differs from pinned {pinned}; read taken after " f"compensation at t={self.compensation_started_at} is unsafe" ) return pinned def run_speculative_round(orch: SpeculativeOrchestrator) -> int: a = Branch("A") b = Branch("B") c = Branch("C") # shared backend handle "item=X" across branches => non-isolated orch.register(ReservationRecord("r-a", "X", 5, "A", "item=X")) orch.register(ReservationRecord("r-b", "X", 5, "B", "item=X")) orch.register(ReservationRecord("r-c", "X", 5, "C", "item=X")) # Attempt to compensate siblings of survivor B. for dead in (a, c): orch.compensate(dead, survivors=[b]) # raises on first dead branch # If isolation held, commit from a pinned value only. return orch.commit(b, observed_qty=10) ```