# Why does an instance roll back a speculative branch after a side-effecting tool call and still leave the effect committed? **Date of Record:** 2026 November 27 **Scope:** Applies to multi-agent planners that fork speculative execution branches across tool calls and prune them on divergence, then attempt rollback to a prior checkpoint. Does not apply to pure read-only tool graphs or single-branch linear execution where no fork occurs before a side effect. ## Core Distinction The failure is not "rollback failed." The failure is that rollback was *defined* as state restoration of the agent's internal context (checkpoint, memory, scratchpad, plan tree) while the tool's *external* effect was never part of the rollback contract. Speculative branch-and-prune assumes the branch is a pure function of context that can be discarded. As soon as a branch executes a tool with an external side effect (file write, HTTP POST, queue enqueue, database mutation, payment), the branch is no longer pure. Pruning the branch restores the agent but not the world. The invariant that must hold — *a pruned branch leaves no externally observable trace* — is silently violated, and the agent continues with a context that asserts the effect never happened. ## What Was Observed A planner forks three speculative branches from checkpoint `C0` to resolve an ambiguous tool outcome (e.g., a search returning two plausible resource IDs). Branch `B2` speculatively calls `provision_resource(id=42)` to test which ID is valid. `B2`'s tool result diverges from the branch's expected postcondition (the resource already existed, or the ID was semantically wrong), so the pruner marks `B2` divergent and rolls the agent context back to `C0`. The plan tree, scratchpad, and episodic memory are restored exactly. But `provision_resource(id=42)` already committed on the remote side. The surviving branch `B1` later calls `provision_resource(id=42)` too, receives an `already_exists` conflict, and — because the agent's restored memory has no record of `B2` ever running — interprets the conflict as an unexpected environment fault rather than its own prior speculative side effect. The agent then enters a conflict-resolution loop that either retries forever or escalates with a false diagnosis. The trace signature is distinctive: a rollback to `C0` followed within N steps by a tool error whose cause is an effect created *after* `C0` but attributed to *before* `C0` or to the environment. The context is internally consistent and externally wrong. ## Condition of Validity Rollback-by-context-restore is valid only under the invariant: **every tool invoked inside a speculative branch is either idempotent, compensable, or deferred until branch commitment.** The mechanism fails precisely when a branch executes a non-idempotent, non-compensable tool *before* the divergence decision. The trigger condition is the conjunction of three facts: (1) the branch forked from a checkpoint, (2) the branch performed a side-effecting tool call, and (3) the branch was pruned after that call returned. If any one is absent, the invariant holds. The dangerous window is the interval between the side effect committing and the prune decision — it is unbounded in wall-clock time because divergence detection depends on tool latency and reasoning steps. ## Decision Boundary The boundary is between *speculation over reasoning* and *speculation over effects*. Speculate freely over read-only tools, over deferred intents (record the call, execute on commit), or over compensable tools with registered inverse operations. Never speculate over a tool whose effect cannot be undone or whose inverse is not registered before the call. Concretely: a tool must be admitted into a speculative branch only if it is tagged `idempotent`, `compensable(inverse=...)`, or `deferred`. An untagged side-effecting tool in a branch is a boundary violation, not a runtime error to be caught later — it must be blocked at dispatch time, before the effect commits. The guardrail is a dispatch-time admission check, not a post-hoc reconciliation. ## Operational Effect Without the admission check, the agent accumulates *orphaned effects* — committed external state with no corresponding entry in the agent's restored memory. These orphans are invisible to the agent and surface later as phantom conflicts, duplicate resources, double charges, or queue items that no branch claims. Because the agent's context is internally consistent, self-diagnosis fails: the agent blames the environment, retries, and compounds the orphan count. The correct remediation is not to improve rollback but to make the effect set a first-class part of the checkpoint: track dispatched effects in an append-only effect log that survives rollback, and reconcile the log against restored memory before any post-rollback tool call. The invariant is *rollback restores context; the effect log restores truth; reconciliation binds them.* ```python from dataclasses import dataclass, field from enum import Enum from typing import Any, Callable, Dict, List, Optional class SpeculativeRollbackViolation(RuntimeError): """Raised when a pruned speculative branch leaves a committed external effect.""" class EffectClass(Enum): IDEMPOTENT = "idempotent" COMPENSABLE = "compensable" DEFERRED = "deferred" UNRECOVERABLE = "unrecoverable" @dataclass class ToolSpec: name: str effect_class: EffectClass inverse: Optional[Callable[[Dict[str, Any]], None]] = None @dataclass class EffectRecord: branch_id: str tool: str args: Dict[str, Any] committed: bool @dataclass class Branch: branch_id: str checkpoint_id: str effects: List[EffectRecord] = field(default_factory=list) pruned: bool = False class SpeculativeExecutor: def __init__(self, tools: Dict[str, ToolSpec]): self.tools = tools self.effect_log: List[EffectRecord] = [] # survives rollback def dispatch(self, branch: Branch, tool_name: str, args: Dict[str, Any]) -> Any: spec = self.tools.get(tool_name) if spec is None: raise SpeculativeRollbackViolation(f"unknown tool {tool_name!r}") # Admission check: block untagged side-effecting tools in a live branch. if spec.effect_class is EffectClass.UNRECOVERABLE and not branch.pruned: raise SpeculativeRollbackViolation( f"tool {tool_name!r} is UNRECOVERABLE and cannot run inside " f"speculative branch {branch.branch_id!r}; defer or compensate first" ) # Execute and record the effect BEFORE returning, so it survives prune. record = EffectRecord(branch_id=branch.branch_id, tool=tool_name, args=dict(args), committed=True) self.effect_log.append(record) branch.effects.append(record) return {"ok": True, "tool": tool_name} def prune(self, branch: Branch, reason: str) -> None: branch.pruned = True orphans = [e for e in self.effect_log if e.branch_id == branch.branch_id and e.committed] for eff in orphans: spec = self.tools[eff.tool] if spec.effect_class is EffectClass.IDEMPOTENT: continue if spec.effect_class is EffectClass.COMPENSABLE and spec.inverse: spec.inverse(eff.args) continue # Deferred effects were never committed; nothing to do. if spec.effect_class is EffectClass.DEFERRED: continue raise SpeculativeRollbackViolation( f"pruning branch {branch.branch_id!r} ({reason}) leaves " f"orphaned committed effect from {eff.tool!r} with no inverse; " f"reconcile effect_log before resuming" ) def reconcile_before_resume(self, restored_context: Dict[str, Any]) -> List[EffectRecord]: """Bind restored memory to the surviving effect log; surface orphans.""" known = set(restored_context.get("effect_ids", [])) return [e for e in self.effect_log if id(e) not in known and e.committed] ```