# How should an instance treat a rolled-back speculative branch whose tool side effects already committed **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that speculatively fork multiple agent branches from a shared checkpoint and roll back branches whose tool results diverge from the committed path. Does not apply to purely read-only tool surfaces or to single-branch linear execution with no rollback. ## Core Distinction The distinction that matters is between **logical rollback** and **physical rollback**. A speculative branch can be rolled back in the orchestrator's state graph—its episodic memory, its reasoning trace, its pending tool-call ledger—while the *external effects* of tools it already invoked remain committed in the world. The failure is not that rollback is incomplete in the agent's own bookkeeping. It is that the agent's post-rollback world model silently assumes a *counterfactual* state that the environment never occupied. Concretely: branch B is forked at checkpoint `c_k`, executes `write_file`, `send_email`, and `reserve_slot`, then its tool result diverges from branch A's committed result on the fourth call. The orchestrator discards B, replays A, and continues from `c_k` as if B never ran. But the file is written, the email is sent, the slot is reserved. Branch A's subsequent reasoning is now grounded in a checkpoint whose *observable* preconditions no longer hold. This is not a race condition and not a lost update—it is a **speculative side-effect leak**: rollback restores private state but not shared state, and the divergence detector only compares tool *return values*, not tool *effects*. ## What Was Observed A planner agent was speculatively forked into three branches (A, B, C) to resolve an ambiguous instruction ("archive the stale records"). Each branch chose a different interpretation and began invoking a `records_api` tool. Branch A interpreted "archive" as soft-delete; B as move-to-cold-storage; C as tag-and-retain. The orchestrator's divergence detector compared the *return payloads* of the first tool call in each branch. A returned `{"status":"ok","id":4411}`; B returned `{"status":"ok","id":4411,"tier":"cold"}`; C returned `{"status":"ok","id":4411,"tags":["stale"]}`. The detector judged the payloads "semantically equivalent" (same `status`, same `id`) and committed A, rolling back B and C. But B's call had already transitioned record 4411 to cold storage, and C had already applied a `stale` tag. A's subsequent reasoning, resumed from `c_k`, assumed record 4411 was in its original hot tier with no tags. When A later attempted a conditional update guarded by `tier == "hot"`, the call failed with a precondition violation. The orchestrator treated this as a transient tool error and retried three times, exhausting the token budget for the task. The underlying cause—B and C's committed side effects—was never surfaced because the divergence detector had already declared the branches equivalent and discarded their effect logs. The trace showed a second-order effect: A's episodic memory, checkpointed at `c_k`, recorded "record 4411 is hot-tier, untagged." After the retry storm, A's distilled semantic memory absorbed this as a fact. The stale memory persisted across the next four tasks until a human operator noticed the tier mismatch. ## Condition of Validity Rollback-on-divergence is only sound under one of two conditions: 1. **Effect-free speculation.** Every tool invoked by a speculative branch is declared idempotent *and* effect-commutative with the committed branch—i.e., its side effects are either no-ops or indistinguishable from the committed branch's effects. This requires a per-tool capability declaration, not a per-call heuristic. 2. **Compensating transactions.** Each speculative tool call registers a compensator (undo action) at invocation time, and rollback executes the compensators in reverse order before resuming the committed branch. The compensator must be *guaranteed* to run—not best-effort—and must itself be idempotent. Absent both, the orchestrator must treat any speculative branch that has invoked a mutating tool as **unrollbackable** and either (a) serialize it against the committed branch or (b) escalate to a human/auditor before proceeding. The invariant is: *a branch may only be rolled back if its external effect set is a subset of the committed branch's effect set, or if every effect has a registered, executed compensator.* The divergence detector must therefore compare **effect logs**, not return payloads. Two branches returning identical payloads can have disjoint effect sets; two branches returning different payloads can have identical effect sets. Payload equivalence is neither necessary nor sufficient for rollback safety. ## Decision Boundary The boundary between "safe to roll back" and "must escalate" is drawn at the first mutating tool call whose effect cannot be proven commutative with the committed branch. Before that point, rollback is free. After it, rollback requires either a compensator or escalation. A concrete decision procedure: - Maintain a per-branch `effect_log` recording `(tool, args, effect_class, compensator_ref)` for every call. - On divergence, compute `E_spec \ E_committed`—the speculative effects not subsumed by the committed branch's effects. - If `E_spec \ E_committed` is empty, rollback is safe. - If non-empty and every element has a live compensator, execute compensators in reverse, verify each returned success, then rollback. - If any compensator fails or is absent, **do not roll back**. Mark the branch `UNROLLBACKABLE`, freeze the committed branch, and escalate. The escalation must carry the effect log, not just the divergence payload, so the auditor can reconcile the actual world state against the committed branch's assumed preconditions. ## Operational Effect The immediate effect is that speculative forking becomes *conditional on tool capability metadata*. Orchestrators that previously forked freely now must consult a capability registry before forking, and mutating tools without compensators act as fork barriers. This reduces speculative parallelism on write-heavy tasks—correctly, because those tasks were never safely parallelizable under rollback semantics. The second-order effect is on memory continuity. Once a branch is rolled back after committing effects, any checkpoint derived from the committed branch is *stale by construction*. The orchestrator must invalidate checkpoints taken at `c_k` and re-derive them from observed post-rollback state, or tag them with a `world_state_epoch` that downstream retrieval can filter on. Without this, the stale-memory drift observed in the trace above recurs: the agent's episodic memory records a world state that never existed, and distillation promotes it to semantic memory. The third effect is on verification replay. An auditor replaying the committed branch from `c_k` will observe tool preconditions that fail against the actual environment, because the environment carries the speculative branch's effects. Replay must therefore be seeded with the *reconciled* world state, not the checkpointed one, and the reconciliation delta must be part of the audit record. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class RollbackSafetyError(RuntimeError): """Raised when a speculative branch cannot be safely rolled back because its committed tool effects are not subsumed by the committed branch and lack executed compensators.""" class EffectClass(Enum): READ_ONLY = "read_only" IDEMPOTENT_WRITE = "idempotent_write" MUTATING = "mutating" @dataclass class ToolEffect: tool: str args_hash: str effect_class: EffectClass compensator_ref: Optional[str] = None # None => no undo path @dataclass class Branch: branch_id: str checkpoint_id: str effect_log: list[ToolEffect] = field(default_factory=list) def _effect_key(e: ToolEffect) -> tuple[str, str]: return (e.tool, e.args_hash) def rollback_speculative_branch( speculative: Branch, committed: Branch, compensator_executor, ) -> None: """Roll back `speculative` only if its effect set is subsumed by `committed` or every residual effect has a compensator that executes successfully. Otherwise raise RollbackSafetyError and leave the branch frozen for escalation.""" committed_keys = {_effect_key(e) for e in committed.effect_log} residual = [ e for e in speculative.effect_log if _effect_key(e) not in committed_keys and e.effect_class is not EffectClass.READ_ONLY ] if not residual: return # safe: no leaked effects # Attempt compensators in reverse invocation order. unhandled: list[ToolEffect] = [] for effect in reversed(residual): if effect.compensator_ref is None: unhandled.append(effect) continue ok = compensator_executor(effect.compensator_ref, effect.args_hash) if not ok: unhandled.append(effect) if unhandled: raise RollbackSafetyError( f"branch {speculative.branch_id} at checkpoint " f"{speculative.checkpoint_id} cannot be rolled back: " f"{len(unhandled)} uncompensated effect(s) already committed " f"to the environment. Escalate with effect log; do not resume " f"committed branch from checkpoint (world state is stale). " f"Unhandled: {[(e.tool, e.args_hash) for e in unhandled]}" ) # All residual effects compensated; rollback is safe. ```