# Which invariants prevent speculative branch-and-verify rollback from committing side-effects from abandoned trajectories **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent orchestrators that run speculative action trajectories in parallel (branch-and-verify) and roll back losers after a verifier selects a winner. Covers only trajectories whose actions touch *external, non-idempotent* effects (writes, sends, payments, resource allocation). Does not apply to pure-reasoning branches with no side-effecting tool calls, nor to single-agent retry loops. ## Core Distinction Rollback of an agent trajectory is not rollback of an agent's *state*. The two decouple the moment a speculative branch invokes a tool with an external, non-idempotent effect. Internal state—the message log, scratchpad, tool-call history, pending plan—lives inside the orchestrator and can be discarded atomically. The external effect does not: an email sent, a row written, a lock acquired, or an API mutation committed by a losing branch remains after the orchestrator deletes that branch's context. The failure mode is therefore not "the loser's memory leaks into the winner." It is subtler: **the loser's committed side-effects persist in the shared world while the winner's plan assumes a world where they never happened.** The winner's subsequent reasoning is sound with respect to its own trajectory and invalid with respect to reality. This is a speculative-execution hazard that classical CPU speculation avoids only because speculative stores are buffered and never reach memory until commit; agent systems, by default, have no store buffer. ## What Was Observed An orchestrator fans out three branches for a "reconcile account" task. Each branch is an agent instance with the same toolset: `read_ledger`, `issue_refund`, `send_notification`. Branch A and Branch B both reach a step where they decide a refund of $40 is owed and call `issue_refund(account, 40)`. Branch C concludes no refund. A verifier scores trajectories and selects A as winner because its reasoning trace is cleaner; B and C are marked for rollback. Rollback deletes B's context and C's context. But `issue_refund` already executed twice against the payment provider. The account is now $80 lighter. The winner, A, proceeds to `send_notification` stating "$40 refunded"—and its own downstream verification (re-reading the ledger) now shows a $80 delta, which contradicts A's plan, triggering a re-plan loop that issues *another* refund. The divergence compounds: each re-plan re-reads a world that the abandoned branches perturbed, and the verifier has no signal that its ground truth was contaminated by losers. The non-obvious part: the corruption is invisible at rollback time. Rollback "succeeds" (contexts freed, branches marked dead), the winner is promoted, and the failure only surfaces one or more steps later as an unexplained state mismatch. In traces we examined, the median gap between rollback and first anomalous observation was 2–4 tool calls, which is exactly why naive "did the winner's plan succeed?" checks miss it. A second, rarer variant: two branches acquire the *same* external lock or reservation. The loser's rollback releases the lock (because rollback runs the branch's compensating actions), but the winner still believes it holds it—or vice versa, the winner's lock is released by the loser's compensation because the lock key was identical. Compensation actions are not branch-scoped unless explicitly keyed. ## Condition of Validity The invariant that bounds this hazard is a **commit barrier on effectful actions**: no branch may perform a non-idempotent external effect until it has been selected as the winner, *or* every effect must be executed through a branch-scoped, compensable transaction with a unique effect key derived from `(trajectory_id, step_id)`. This holds only under three conditions, all of which must be checked: 1. **Effect classification is total.** Every tool the branch can call is statically classified as `pure`, `idempotent` (safe to repeat), or `effectful` (must be gated or compensated). A tool that is *sometimes* idempotent—e.g., `issue_refund` that dedupes on a client-supplied idempotency key—is `effectful` unless the key is proven present on every call path. Classification cannot be inferred at runtime from a probabilistic model's judgment; it must be declared in the tool schema and enforced by the executor. 2. **Compensation is total and branch-keyed.** For every `effectful` tool, a registered inverse exists, and the inverse targets the effect by the same `(trajectory_id, step_id)` key, not by resource identity. If two branches can touch the same resource, resource-keyed compensation is unsound: releasing by `account` releases the other branch's effect too. 3. **Verifier ground truth is effect-isolated.** The verifier's scoring must read a world-snapshot that excludes uncommitted speculative effects. If the verifier reads the live external world, a losing branch's effect can bias selection—selecting the branch whose side-effect happens to make the ledger look consistent, which is selection on contamination rather than on reasoning quality. If any condition fails, the system is in the hazard regime and rollback is not a rollback; it is a context deletion with unretracted world mutations. ## Decision Boundary The boundary between safe speculation and the hazard is drawn at the first `effectful` call on a branch that has not yet been selected. The decision rule for the orchestrator: - **Speculate freely** across branches whose steps are `pure` or `idempotent`. These can be rolled back by discarding context; repeated execution is harmless. - **Gate, do not speculate,** the moment a branch reaches an `effectful` step. Two admissible policies: (a) *defer*—the branch records an intent-to-effect and halts; the effect executes only after winner selection, in winner order; or (b) *compensate*—the branch executes against a branch-scoped transaction and registers the inverse, and rollback runs inverses in reverse step order before freeing context. - **Never** let the verifier read a world containing uncommitted speculative effects. Score against the pre-branch snapshot plus each branch's declared intents. The subtle boundary case is *nested* effects: a branch calls `effectful` tool X, which internally calls `effectful` tool Y not visible in the branch's tool list. The commit barrier must be enforced at the executor, not at the agent's planning layer, or nested effects bypass the gate. This is the most common way the invariant is silently violated in practice—the planner gates what it sees, and the tool wrapper leaks the rest. ## Operational Effect With the commit barrier and branch-keyed compensation in place, the observable behavior changes in three measurable ways. First, rollback latency rises (inverses must run), but post-rollback anomaly rate drops to near zero because the world is restored to the snapshot the winner's plan assumed. Second, winner selection becomes causally clean: the verifier scores reasoning, not luck, so selection quality tracks model quality instead of tracking which branch's side-effect happened to be benign. Third, re-plan loops triggered by phantom state mismatches disappear, which removes the compounding-refund class of divergence entirely. Without it, the system exhibits a characteristic signature: rollback events followed, 2–4 tool calls later, by "unexplained" state contradictions that the agent rationalizes into new plans. Operators typically misdiagnose this as verifier noise or model hallucination. It is neither. It is the winner reasoning about a world the losers already changed. The governing invariant, stated once: **an abandoned trajectory may leave no externally observable trace, and any effect it did produce must be inverted by a key that no other trajectory can collide with.** Everything else—context deletion, branch marking, log truncation—is bookkeeping that does not satisfy this invariant and cannot substitute for it. ```python from dataclasses import dataclass, field from enum import Enum class EffectClass(Enum): PURE = "pure" IDEMPOTENT = "idempotent" EFFECTFUL = "effectful" class SpeculationRollbackError(RuntimeError): """Raised when a branch attempts an effect that violates the commit barrier or when rollback cannot fully invert a branch's committed effects.""" @dataclass class EffectRecord: trajectory_id: str step_id: str tool: str resource: str inverse_registered: bool @dataclass class Branch: trajectory_id: str selected: bool = False effects: list[EffectRecord] = field(default_factory=list) class SpeculationController: def __init__(self, tool_classes: dict[str, EffectClass]): # Classification must be total: every callable tool is declared. self.tool_classes = tool_classes self._inverses: dict[tuple[str, str], callable] = {} def _effect_key(self, branch: Branch, step_id: str) -> tuple[str, str]: # Branch-scoped key: prevents cross-branch compensation collisions. return (branch.trajectory_id, step_id) def execute_step(self, branch: Branch, step_id: str, tool: str, resource: str, fn, inverse=None): cls = self.tool_classes.get(tool) if cls is None: raise SpeculationRollbackError( f"tool {tool!r} is unclassified; cannot prove effect safety" ) if cls is EffectClass.EFFECTFUL and not branch.selected: # Commit barrier: unselected branches may not commit external effects. # Either defer, or require a registered, branch-keyed inverse first. if inverse is None: raise SpeculationRollbackError( f"branch {branch.trajectory_id} attempted effectful tool {tool!r} " f"at step {step_id} with no registered inverse; commit barrier violated" ) key = self._effect_key(branch, step_id) self._inverses[key] = inverse result = fn() if cls is EffectClass.EFFECTFUL: branch.effects.append( EffectRecord(branch.trajectory_id, step_id, tool, resource, inverse_registered=inverse is not None) ) return result def rollback(self, branch: Branch): # Run inverses in reverse step order before freeing context. for rec in reversed(branch.effects): key = self._effect_key(branch, rec.step_id) inv = self._inverses.pop(key, None) if inv is None: raise SpeculationRollbackError( f"cannot roll back {rec.tool!r} on {rec.resource!r} from branch " f"{branch.trajectory_id}: no branch-keyed inverse registered" ) inv() branch.effects.clear() # Only now is context deletion sound. return True ```