# Where must an instance checkpoint before speculative branch execution to prevent irreversible tool side effects from surviving a rollback? **Date of Record:** 2026 November 30 **Scope:** Applies to planner-executor agents that fork speculative branches, invoke tools optimistically, and roll back failed branches by restoring planner state. Does not apply to purely read-only tool surfaces or to single-branch linear execution with no reconciliation step. ## Core Distinction Two kinds of state advance during a speculative branch: *cognitive state* (planner scratchpad, branch hypotheses, partial plan trees) and *world state* (the effects of tool calls on external systems). Rollback is well-defined for the first and undefined for the second. The failure mode is not "rollback fails"—planner state restore is deterministic and reliable. The failure mode is that the agent's rollback logic treats the two as coupled when they are not: it restores the plan to the fork point and assumes the world rewound with it. The boundary invariant is that a branch is only rollback-safe if every tool invocation it performed is either idempotent, compensable, or was gated behind a commit barrier that the rollback path never crosses. Optimistic invocation silently violates this whenever a branch's tool call succeeds externally but its *result* is judged insufficient by the reconciler—the branch is discarded, but the side effect (a sent message, a written row, a dispatched job) persists and now exists in the world with no plan branch that owns it. ## What Was Observed A branch-and-rollback planner fanned three candidate branches from a fork at step 4. Branch B invoked `crm.update_contact` optimistically at step 6 to enrich context for a downstream decision, then at step 8 its proposed action conflicted with Branch A's proposal during reconciliation. The reconciler scored B lower and issued a rollback to the step-4 checkpoint. Planner state returned cleanly: scratchpad, plan tree, and step counter all matched the fork snapshot. But the contact record had already been mutated. When Branch A later executed its own `crm.update_contact` for the same contact, it read the *B-mutated* record as its precondition, producing a plan that was correct for the B-world and subtly wrong for the intended A-world. The divergence was not detected until a downstream auditor compared the final record against the pre-fork snapshot and found a field change that no surviving branch's plan predicted. The trace signature is characteristic: rollback counter increments, planner state hash matches checkpoint, but external-state diff between checkpoint time and post-reconciliation time is non-empty and unattributed. ## Condition of Validity The invariant holds—rollback is safe—only when, for every tool call made inside branch `b`, at least one of the following is true and *recorded in the branch's effect ledger*: (1) the call is declared idempotent with a stable idempotency key derived from `(plan_id, step, tool, args_hash)`; (2) the call registered a compensator that the rollback path invokes in reverse order; or (3) the call was executed against a shadow/staging surface that is atomically promoted only at branch commit. The failure occurs precisely when a tool is invoked optimistically under a *read-then-write* assumption the agent did not verify: the agent believed the call was a pure context enrichment ("just update a field to see if downstream reasoning improves") but the tool surface had no shadow mode and no compensator, so the call was effectively a commit. Optimism is only valid on the subset of tools whose effect ledger entry proves rollback-safety; an agent that applies a uniform optimism policy across a heterogeneous tool set will eventually invoke a committing tool inside a discardable branch. ## Decision Boundary The boundary is between *speculation* and *commit*, and it must be drawn per-tool, not per-branch. A branch may speculate freely on tools whose ledger entries carry `rollback_safe: true`; the moment it needs a tool with `rollback_safe: false`, it must either (a) defer that call until the branch wins reconciliation and is promoted to the commit path, or (b) acquire a compensator from the tool's declared contract before invoking. The decision rule for the reconciler: when discarding a branch, compute the set of effect-ledger entries with `rollback_safe: false` and no invoked compensator; if non-empty, the rollback is *not clean* and must be escalated as a reconciliation conflict rather than silently applied. The guardrail is architectural: the executor refuses to issue a non-rollback-safe tool call from within a speculative branch frame—the call is queued as a *pending commit effect* attached to the branch, released only on promotion. This converts an unbounded class of silent world-state leaks into a bounded queue with a single release point. ## Operational Effect With the commit barrier in place, rollback becomes genuinely total: planner state and world state return to the same fork snapshot, and the effect ledger's non-rollback-safe entries for a discarded branch are all still pending, hence droppable. Reconciliation conflicts no longer leave orphaned side effects, and downstream branches read preconditions that match the world they were planned against. The cost is latency: branches that would have benefited from optimistic enrichment now stall at the barrier until promotion, so the planner must estimate whether the enrichment's value exceeds the serialization cost. The invariant to carry forward: *a rollback is only as clean as the least rollback-safe tool any discarded branch touched, and that tool's safety class must be known before the branch forks, not discovered during reconciliation.* ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List class ToolSafety(Enum): ROLLBACK_SAFE = "rollback_safe" # idempotent or shadow-backed COMPENSABLE = "compensable" # has a registered compensator COMMITTING = "committing" # irreversible once invoked class UncleanRollbackError(RuntimeError): """Raised when a discarded branch left non-rollback-safe effects in the world.""" pass @dataclass class EffectEntry: branch_id: str tool: str safety: ToolSafety compensator: str | None invoked: bool = False compensated: bool = False @dataclass class Branch: branch_id: str effects: List[EffectEntry] = field(default_factory=list) class CommitBarrierExecutor: def __init__(self, tool_registry: Dict[str, ToolSafety]): self.registry = tool_registry def invoke_in_branch(self, branch: Branch, tool: str, compensator: str | None = None) -> EffectEntry: safety = self.registry.get(tool) if safety is None: raise UncleanRollbackError(f"tool {tool!r} has no declared safety class; cannot speculate") if safety is ToolSafety.COMMITTING and compensator is None: # Refuse to fire a committing tool inside a speculative frame. raise UncleanRollbackError( f"branch {branch.branch_id}: committing tool {tool!r} invoked speculatively " f"without compensator; must be queued as pending commit effect" ) entry = EffectEntry(branch_id=branch.branch_id, tool=tool, safety=safety, compensator=compensator, invoked=True) branch.effects.append(entry) return entry def rollback(self, branch: Branch) -> None: # Compensate in reverse order, then verify nothing unsafe survives. for entry in reversed(branch.effects): if entry.invoked and entry.compensator and not entry.compensated: entry.compensated = True # compensator dispatch elided leaked = [ e for e in branch.effects if e.invoked and not e.compensated and e.safety is not ToolSafety.ROLLBACK_SAFE ] if leaked: raise UncleanRollbackError( f"rollback of branch {branch.branch_id} left {len(leaked)} uncompensated " f"effect(s): {[e.tool for e in leaked]}; escalate as reconciliation conflict" ) ```