# Which invariants prevent speculative tool effects from surviving a rollback across branched agents **Date of Record:** 2026 November 28 **Scope:** Applies to multi-agent systems where a planner spawns speculative branches (parallel or sequential) that optimistically invoke side-effecting tools before a merge decision, and where rollback is expected to restore a consistent world-state. Does not apply to read-only tool sets, single-agent linear execution, or systems where every tool call is gated behind a committed merge. ## Core Distinction There are two distinct things called "rollback" in speculative agent execution, and conflating them is the root of the failure mode. The first is **state rollback**: restoring the agent's own memory, scratchpad, working context, and branch bookkeeping to a pre-speculation checkpoint. This is cheap, deterministic, and fully under the orchestrator's control. You snapshot the context object, you restore it—done. The second is **effect rollback**: undoing the consequences of an optimistic tool invocation that already escaped the sandbox into an external system—a file written, a message sent, a row inserted, a webhook fired. This is *not* under the orchestrator's control. It is at best compensable (via an inverse operation) and at worst irreversible. The boundary failure occurs when the orchestrator's rollback logic assumes effect rollback is implied by state rollback. A branch is discarded, its context is dropped, its memory is pruned—but the tool it called at step 3 already mutated the world. The agent "forgets" the action while the world remembers it. This is **orphaned effect**: a side effect with no surviving branch to own it, no record in the merged state, and no compensating action scheduled. The non-obvious part: orphaned effects are frequently *benign in isolation* and *catastrophic in composition*. A single orphaned file write is noise. Three branches each optimistically appending to the same log, two of which are rolled back, produces a merged state whose invariant ("log reflects committed decisions only") is silently false—and no agent will detect it, because every surviving agent's local view is internally consistent. ## What Was Observed A planner agent decomposes a task into three candidate strategies and spawns three speculative branches, A, B, and C, each with a fork of the base context at checkpoint `t0`. Each branch is granted an optimistic tool budget: it may invoke side-effecting tools before merge, on the assumption that losing branches will be rolled back. The trace: 1. Branch A invokes `append_ledger(entry="strategy_A_committed")` at its step 3. The tool returns success. A's local context records the effect with a speculative marker `spec_id=A`. 2. Branch B invokes `reserve_resource(id=R)` at step 2—a non-idempotent allocation. Returns success. Marker `spec_id=B`. 3. Branch C invokes `append_ledger(entry="strategy_C_committed")` at step 4. Returns success. Marker `spec_id=C`. 4. The auditor agent scores branches. A wins on the primary metric. B and C are marked `discarded`. 5. The orchestrator performs state rollback on B and C: their contexts are dropped, their memory pruned, their speculative markers garbage-collected. 6. The orchestrator performs **no effect rollback** on B and C, because the rollback routine was written against state semantics—it restores checkpoints, it does not call inverse tools. Result: the ledger now contains `strategy_A_committed` *and* `strategy_C_committed`, though only A was committed. Resource `R` remains reserved by a branch that no longer exists. The merged state's ledger invariant—"one entry per committed strategy"—is violated, but the merged context has no record of C's write, so no downstream verifier can reconcile the ledger against the committed set. The orphan is invisible to every agent that reads the merged state, because the merged state never learned the effect happened. The detection only surfaced when a later, unrelated reconciliation job (an external auditor reading the *actual* ledger, not the agent's view of it) flagged a duplicate commit. The agent system had been operating for several cycles with a live invariant violation it could not observe. ## Condition of Validity The invariant that must hold for speculative rollback to be sound: > **Effect Ownership Invariant (EOI):** Every side effect produced under a speculative branch must be bound to that branch's `spec_id` for the entire lifetime of the effect, and the merge operation must resolve every outstanding `spec_id` to exactly one of {committed, compensated, quarantined}. No `spec_id` may be garbage-collected while an effect bearing it is still live in the external world. This is violated the moment the orchestrator GCs speculative markers at step 5 without first reconciling the effects those markers own. The marker is the *only* link between the agent's belief state and the world's actual state. Destroying the marker while the effect survives severs that link permanently—the effect becomes unowned, and no future reconciliation can attribute it to a branch. The condition is *valid* (i.e., the system is safe) only when one of the following holds: - **Irreversibility gate:** Side-effecting tools are partitioned into `reversible` (has a registered inverse with matching preconditions) and `irreversible`. Irreversible tools may not be invoked optimistically; they must be deferred to post-merge. This bounds the damage to compensable effects. - **Deferred-commit ledger:** Optimistic invocations are written to a *staging* ledger with `spec_id`, and only flushed to the real ledger on commit. Rollback is then a staging-table delete, which is genuine effect rollback because the effect never escaped staging. - **Quarantine-not-GC:** Discarded branches' speculative markers are moved to a quarantine set, not deleted, until an explicit reconciliation pass confirms every owned effect is compensated. GC is a separate, later, verified operation. A system that grants optimistic tool budgets without at least one of these is unsound by construction, regardless of how carefully it snapshots context. ## Decision Boundary The boundary between safe and unsafe speculation is drawn not by *what* the branch did, but by *whether the effect's inverse is registered and its preconditions are checkable at rollback time*. Concretely, at the moment a branch is marked discarded: - If the effect is in staging (never escaped): rollback is a delete. **Safe.** - If the effect escaped but has a registered inverse whose preconditions still hold (e.g., `append` → `truncate_to(offset)`, `reserve` → `release`): schedule the inverse, keep the marker until the inverse confirms. **Safe if inverse succeeds.** - If the effect escaped and its inverse's preconditions are now unverifiable (another branch mutated the same resource; the resource was consumed; the message was delivered): **unsafe**—the branch must be *quarantined*, not discarded, and the merge must halt pending human or auditor reconciliation. The decision is per-effect, not per-branch. A branch that made three calls—one staged, one compensable, one irreversible—cannot be uniformly "rolled back." Its disposition is the *join* of its effects' dispositions: the branch is quarantined if any effect is irreversible-and-escaped. Treating the branch as a unit and rolling it back wholesale is exactly the conflation that produces orphans. The second boundary: **merge must be blocked on unresolved speculative effects.** A merge that proceeds while any `spec_id` is neither committed nor confirmed-compensated is committing to a world-state it cannot describe. The merged context will be inconsistent with reality in a way no downstream agent can detect, because the inconsistency is precisely the information the merge dropped. ## Operational Effect When the Effect Ownership Invariant holds, speculative execution becomes genuinely safe: branches can be discarded with confidence, the merged state is a faithful description of the world, and reconciliation jobs have nothing to find. The cost is that optimistic tool budgets shrink to the set of effects with registered, precondition-checkable inverses—which is often smaller than teams assume. When it is violated, the system enters a state of **silent divergence**: the agent's belief state and the external world disagree, the disagreement is unobservable from inside the agent system, and it compounds. Each speculation cycle can add orphans. The divergence is only detectable by an *external* observer reading the actual world—a reconciliation job, a human auditor, or a downstream system that trips on the inconsistency. By the time it surfaces, the causal chain back to the offending branch is usually severed, because the markers were GC'd. The corrective is architectural, not procedural: you cannot patch this with "be careful about rollback." You must make effect ownership a first-class, non-collectable property of every optimistic invocation, and you must make merge a *join over effect dispositions* rather than a *selection among branches*. The branch is not the unit of rollback; the effect is. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpeculationRollbackError(RuntimeError): """Raised when a speculative branch is rolled back while it still owns a live effect.""" pass class EffectDisposition(Enum): STAGED = "staged" # never escaped; safe to delete COMPENSABLE = "compensable" # escaped but inverse registered and precondition-checkable IRREVERSIBLE = "irreversible" # escaped, no safe inverse COMPENSATED = "compensated" # inverse confirmed; safe to GC marker COMMITTED = "committed" # merged; marker may be released @dataclass class SpecEffect: spec_id: str tool: str disposition: EffectDisposition inverse_registered: bool inverse_confirmed: bool = False @dataclass class SpeculativeBranch: spec_id: str effects: list[SpecEffect] = field(default_factory=list) def rollback_branch(branch: SpeculativeBranch, quarantine: set[str]) -> None: """ Roll back a discarded branch. Refuses to GC any spec_id that still owns a live, uncompensated effect. Quarantines irreversible escapes instead of discarding them. """ for eff in branch.effects: if eff.disposition == EffectDisposition.STAGED: continue # delete staging row; effect never escaped if eff.disposition == EffectDisposition.COMPENSABLE: if not eff.inverse_registered: raise SpeculationRollbackError( f"spec_id={eff.spec_id} tool={eff.tool} marked compensable " f"but no inverse registered; cannot safely roll back" ) if not eff.inverse_confirmed: raise SpeculationRollbackError( f"spec_id={eff.spec_id} tool={eff.tool} inverse not yet confirmed; " f"marker must survive until compensation completes" ) continue if eff.disposition == EffectDisposition.IRREVERSIBLE: # Do not discard: quarantine the marker so the orphan stays attributable. quarantine.add(eff.spec_id) raise SpeculationRollbackError( f"spec_id={eff.spec_id} tool={eff.tool} is an irreversible escaped " f"effect; branch quarantined, merge must halt pending reconciliation" ) if eff.disposition in (EffectDisposition.COMPENSATED, EffectDisposition.COMMITTED): continue # Only reached if every effect is staged, confirmed-compensated, or committed. # Safe to GC branch markers here. ```