# Which invariants prevent orphaned side effects when speculative agent branches roll back after optimistic tool invocation **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent pipelines that fork speculative branches, invoke external tools optimistically before a branch is committed, and reconcile branches via rollback. Does not apply to purely read-only tool surfaces or to single-branch sequential agents with no fork/commit lifecycle. ## Core Distinction The failure is not "a branch rolled back." Rollback of *internal* state is cheap and well-understood: discard the speculative context, restore the checkpoint, resume from the last committed turn. The boundary condition is that **optimistic tool invocation crosses the rollback boundary**. When a speculative branch calls a tool with a side effect (writes a record, sends a message, mutates a shared datastore, enqueues a job) *before* the branch is selected as the winner, that side effect is not part of the agent's checkpointable state. It lives in an external system that the rollback machinery cannot see or undo. The distinction that matters operationally: there are two classes of state in a speculative pipeline — **reversible agent state** (context, scratchpad, tool-call log, branch-local memory) and **irreversible external effects** (anything a tool did to the world). Rollback is only correct if every irreversible effect produced by a losing branch is either (a) deferred until commit, or (b) compensated by an explicit inverse. Pipelines that treat "rollback" as "restore the checkpoint" silently assume (a) or (b) without enforcing either, and the losing branch's writes leak into the committed world. ## What Was Observed A three-branch speculative planner was forked from a shared checkpoint. Each branch was given the same task: resolve a customer escalation by (1) reading the ticket, (2) drafting a reply, (3) *optimistically* posting the reply to the ticketing API so the latency of the write overlaps with the reconciliation step. Branch selection was deferred to an auditor agent that scored the three drafts and committed the best one. The trace: 1. All three branches call `tickets.post_reply(ticket_id, body)` at step 3. Each call succeeds and returns a distinct `reply_id`. The tool log records three `reply_id`s, one per branch. 2. The auditor scores the branches and selects branch B. Branches A and C are rolled back: their contexts are discarded, their checkpoints dropped, their `reply_id`s garbage-collected from branch-local memory. 3. The committed transcript shows one reply. The ticketing system shows **three** replies, two of which were authored by branches that no longer exist. No error was raised at any step. Every tool call returned 200. The rollback "succeeded" in the sense that the agent state was restored. The external world diverged from the agent's belief about the external world, and the divergence was invisible to every component in the pipeline because the two states were never compared. The second-order effect was worse than the duplicate writes. On the *next* task, the retrieval layer pulled the ticket's reply history — now containing the two orphaned replies — into context. The agent read its own discarded branch outputs as if they were prior committed work, and reasoned forward from them. The rollback boundary had been crossed not just by the writes but by the *evidence* of the writes, which re-entered the agent's memory through a channel the rollback machinery did not control. ## Condition of Validity The invariant that prevents this is a **commit-gated effect boundary**: no tool with an irreversible side effect may be invoked by a branch until that branch has been selected as the commit winner, *or* the effect must be routed through a staging layer that is itself part of the branch's reversible state and is only flushed on commit. Formally, for a pipeline to be rollback-safe under speculative execution, every tool must be classified into one of three tiers, and the classification must be enforced at the invocation boundary, not by convention: - **Pure**: no external effect; safe to invoke speculatively; result is branch-local and discarded on rollback. - **Staged**: effect is buffered in a branch-scoped staging area (a tentative write, a held message, a pending job) that is flushed only on commit and dropped on rollback. The staging area is part of the checkpoint. - **Committed-only**: effect is immediate and irreversible; may only be invoked after the branch is the commit winner. The invariant fails the moment a tool classified as committed-only is reachable from a speculative branch's tool surface. The condition of validity is therefore: *the tool surface exposed to a speculative branch must be the pure ∪ staged tiers, and the committed-only tier must be unreachable until commit.* If a branch can call a committed-only tool, rollback is not a rollback — it is a context discard that leaves the world mutated. A second, independent condition: **effect receipts must be branch-scoped and reconciled at commit**. Even with a staged tier, the pipeline must be able to answer "which effects did the losing branches attempt, and were any of them flushed?" If the staging layer is shared across branches (a single queue, a single tentative-write table without branch keys), two branches staging the same logical write will collide at flush time, and the collision will surface as a duplicate or an overwrite after commit — the same orphan, arrived at by a different path. ## Decision Boundary The decision boundary is where the pipeline chooses between **optimistic invocation with compensation** and **deferred invocation with staging**. Both are valid; the failure is choosing neither and believing you chose the first. Choose optimistic-with-compensation only when every committed-only tool has a *verified* inverse that the rollback path actually calls, and the inverse is idempotent under the tool's own semantics. `post_reply` has no inverse in most ticketing APIs — you cannot un-send a reply that a human may already have seen. That tool is not compensable, so it cannot be optimistically invoked by a losing branch. The correct decision at the boundary is to classify it as committed-only and defer it. Choose deferred-with-staging when the tool has no inverse or when its inverse is not idempotent (e.g., `increment_counter`, `send_email`, `create_charge`). The staging layer holds the intent; commit flushes exactly the winner's staged intents; rollback drops the losers' staged intents with the branch. The boundary is crossed incorrectly when the pipeline's tool registry does not carry an effect-tier annotation, and the speculative fork inherits the *full* tool surface by default. Default inheritance is the mechanism: the fork copies the parent's tool bindings, the parent's bindings include committed-only tools because the parent is past commit, and the speculative branch silently gains the ability to mutate the world. The guardrail is that the fork operation must *narrow* the tool surface to pure ∪ staged, and the narrowing must be a hard failure if a committed-only tool is requested, not a silent downgrade. ## Operational Effect When the commit-gated effect boundary holds, rollback is total: the losing branches leave no trace in the external world, and the committed transcript is the only record of what happened. The retrieval layer's view of the world matches the world, so the next task's context is not poisoned by discarded branch outputs. When it fails, the observable signature is a **divergence between the agent's effect ledger and the external system's state**, with no error at write time and no error at rollback time. The divergence is detected only by an out-of-band reconciliation — comparing the tool log's committed `reply_id`s against the ticketing system's reply count — which most pipelines do not run. The mean time to detection is therefore unbounded, and the blast radius grows with every subsequent task that retrieves the orphaned effects into context. The failure is silent, cumulative, and self-reinforcing: the orphaned writes become evidence, the evidence becomes context, and the context becomes the next branch's premise. The operational lesson is that speculative execution's correctness is not a property of the rollback machinery. It is a property of the *effect classification at the invocation boundary*. Rollback can only restore what it can see; the guardrail must ensure that what it cannot see was never written. ```python class EffectTierViolation(RuntimeError): """Raised when a speculative branch attempts a committed-only effect.""" pass class OrphanedEffectError(RuntimeError): """Raised when rollback leaves an external effect unaccounted for.""" pass PURE = "pure" STAGED = "staged" COMMITTED_ONLY = "committed_only" class ToolRegistry: def __init__(self, tiers: dict[str, str]): self._tiers = tiers def tier_of(self, tool_name: str) -> str: if tool_name not in self._tiers: # Unclassified tools are treated as committed-only: fail closed. return COMMITTED_ONLY return self._tiers[tool_name] class SpeculativeBranch: def __init__(self, branch_id: str, registry: ToolRegistry, committed: bool = False): self.branch_id = branch_id self.registry = registry self.committed = committed self.staged_effects: list[tuple[str, dict]] = [] self.flushed_effects: list[tuple[str, dict]] = [] def invoke(self, tool_name: str, args: dict, executor): tier = self.registry.tier_of(tool_name) if tier == PURE: return executor(tool_name, args) if tier == STAGED: self.staged_effects.append((tool_name, args)) return {"staged": True, "branch": self.branch_id} if tier == COMMITTED_ONLY: if not self.committed: raise EffectTierViolation( f"branch {self.branch_id} attempted committed-only tool " f"{tool_name!r} before commit; rollback would orphan the effect" ) result = executor(tool_name, args) self.flushed_effects.append((tool_name, args)) return result raise EffectTierViolation(f"unknown tier {tier!r} for {tool_name!r}") def commit(self, executor): self.committed = True for tool_name, args in self.staged_effects: executor(tool_name, args) self.flushed_effects.append((tool_name, args)) self.staged_effects.clear() def rollback(self, external_ledger: list[tuple[str, dict]]): # Staged effects are dropped with the branch: no external trace. self.staged_effects.clear() # Any flushed effect from an uncommitted branch is an orphan. for effect in self.flushed_effects: if effect in external_ledger: raise OrphanedEffectError( f"branch {self.branch_id} rolled back but effect {effect!r} " f"is present in the external ledger; rollback boundary crossed" ) if self.flushed_effects: raise OrphanedEffectError( f"branch {self.branch_id} has flushed effects with no external " f"record; reconciliation cannot prove the world is clean" ) ```