# Under what conditions must an instance treat speculative branch rollback as unsafe when a parallel branch has already committed a non-idempotent tool side effect **Date of Record:** 2026 November 21 **Scope:** Applies to orchestrators that fan out multiple speculative agent branches from a shared checkpoint, permit each branch to issue tool calls through a shared connector layer, and later select one branch as canonical while rolling back the rest. Does not apply to branches operating under strict read-only tool allowlists or to sandboxes whose tool effects are transactionally isolated per branch. ## Core Distinction The distinction that matters here is between *speculative state* and *committed effect*. A speculative branch's internal reasoning trace, scratchpad, and even its writes to a private branch-local memory namespace are all reversible: the orchestrator can discard them by dropping the branch and restoring the pre-fan-out checkpoint. But a tool call that crosses the connector boundary leaves the agent's addressable state and mutates an external system the orchestrator does not own — a sent email, a charged card, a created ticket, an appended row, a pushed commit. That effect is not part of any checkpoint. Rollback semantics that treat "discard the branch" as equivalent to "undo the branch" are therefore sound only when every tool call a branch can reach is idempotent and reversible, or when the connector layer enforces a two-phase commit that defers external visibility until branch selection. The failure is non-obvious because the orchestrator's own bookkeeping is internally consistent. The discarded branch's context is dropped cleanly, the winning branch resumes from a correct state, and the trace log shows a tidy fan-out/select/rollback. Nothing in the agent-layer state machine signals that a losing branch already fired a side effect. The inconsistency lives entirely in the gap between the orchestrator's rollback model and the external systems the losing branch touched. ## What Was Observed A support-triage orchestrator fanned out three branches from a shared checkpoint to draft a resolution for a billing dispute. Branch A proposed issuing a refund via `billing.issue_refund`; Branch B proposed a credit memo via `billing.create_credit`; Branch C proposed escalation via `ticketing.create_escalation`. Each branch was permitted to call tools during speculation so that the scorer could evaluate proposals against live system responses (e.g., verifying the customer's balance before proposing a refund). The scorer ranked Branch C highest and selected it. Branches A and B were rolled back: their context was discarded and the orchestrator restored the checkpoint. But Branch A had already executed `billing.issue_refund` during its speculative validation step, because the refund tool returned a success payload that the branch used to confirm feasibility. The rollback dropped the branch's memory of having done so; it did not reverse the refund. Branch B had likewise created a credit memo. The result: the customer received a refund, a credit memo, *and* an escalation — three mutually exclusive resolutions, two of which the orchestrator believed it had discarded. The winning branch's subsequent reasoning, which assumed no prior resolution existed, then produced a contradictory customer-facing message. The corruption was detected only when a human agent noticed the duplicate credits. The trace showed the orchestrator behaving exactly as designed. The defect was a false invariant: *"rolling back a branch reverts its effects."* That invariant holds for branch-local state and fails for any tool call with external, non-idempotent effect. ## Condition of Validity Speculative rollback is safe for a given branch if and only if, for every tool call the branch issued during speculation, at least one of the following holds: 1. **Deferred visibility.** The connector buffers the effect and exposes it externally only after the orchestrator commits the branch (a two-phase commit keyed to branch identity). The buffer is itself part of the branch's speculative state and is discarded on rollback. 2. **Provable idempotence with a rollback counterpart.** The tool is idempotent under a stable idempotency key derived from `(branch_id, logical_action_id)`, *and* a compensating operation exists that the orchestrator can invoke on rollback — and that compensating operation is itself safe to invoke even if the original call partially succeeded. 3. **Read-only.** The call cannot mutate external state. The invariant the orchestrator must enforce is: **a branch may not be rolled back while it holds an un-reverted, externally visible, non-idempotent effect.** Equivalently, branch selection must be gated on the set of committed effects across *all* branches, not just the winner. If any losing branch holds a live effect, the orchestrator must either compensate it before discarding the branch, or promote the branch's effect into the canonical resolution set and reconcile the winner against it. The subtle trap is condition 2's partial-success clause. An idempotency key prevents *duplicate* effects but does not make a *partially applied* effect reversible. A refund tool that debits the ledger and then fails to write the audit record is idempotent on retry but leaves a half-applied mutation that a naive compensating `reverse_refund` may double-correct. The compensating operation must be designed against the tool's actual partial-failure states, not against its happy path. ## Decision Boundary The orchestrator must decide, per branch and per tool call, whether the call is *speculation-safe*. The boundary is drawn at the connector, not at the branch: the branch's reasoning cannot be trusted to know whether its own tool call was reversible, because the branch has no visibility into the orchestrator's rollback model and will happily treat a successful tool response as confirmation of feasibility. Concretely, the orchestrator must classify every tool in the registry along two axes — *external visibility* (does the effect escape the sandbox before commit?) and *reversibility* (does a verified compensation exist?) — and enforce that speculative branches may only invoke tools in the speculation-safe quadrant unless the connector is running in deferred-visibility mode. Tools that are externally visible and non-reversible (send, charge, publish, delete) must be *deferred* under speculation: the branch receives a synthetic "accepted, pending commit" response, and the real call fires only if the branch is selected. The boundary is crossed the moment a branch issues a direct (non-deferred) call to an externally visible, non-reversible tool. At that point the branch is no longer speculative regardless of what the orchestrator's fan-out bookkeeping says, and rollback becomes an unsafe operation that must be refused rather than attempted. ## Operational Effect When the boundary is respected, fan-out width is bounded by the cost of deferred calls rather than by the risk of duplicate effects, and branch selection becomes a genuine choice among proposals rather than a race to see whose side effects land first. When it is violated, the orchestrator silently produces multi-effect resolutions: the customer-visible outcome is the union of all branches that happened to call a mutating tool, while the orchestrator's internal record shows only the winner. The divergence is invisible to the agent layer and surfaces only as external inconsistency — duplicate charges, contradictory messages, orphaned tickets — typically discovered by a human or a downstream reconciliation job long after the trace has been closed. The remediation is not "roll back harder." It is to make the connector refuse to execute a speculation-unsafe call from a branch that has not been committed, and to make the orchestrator's rollback path raise rather than proceed when it detects a live effect on a branch it is about to discard. The guardrail is a refusal at the connector, enforced before the effect escapes. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpeculationSafetyError(RuntimeError): """Raised when a speculative branch attempts an effect that cannot be safely rolled back.""" pass class Visibility(Enum): SANDBOXED = "sandboxed" # effect stays inside branch-local state EXTERNAL = "external" # effect escapes to a system the orchestrator does not own class Reversibility(Enum): REVERSIBLE = "reversible" # verified compensating operation exists IRREVERSIBLE = "irreversible" @dataclass(frozen=True) class ToolSpec: name: str visibility: Visibility reversibility: Reversibility deferred_capable: bool = False # connector can buffer until commit @dataclass class Branch: branch_id: str committed: bool = False live_effects: list = field(default_factory=list) # (tool_name, action_id) not yet reverted class SpeculativeConnector: def __init__(self, registry: dict[str, ToolSpec], deferral_enabled: bool): self.registry = registry self.deferral_enabled = deferral_enabled def is_speculation_safe(self, spec: ToolSpec) -> bool: if spec.visibility is Visibility.SANDBOXED: return True if spec.reversibility is Reversibility.REVERSIBLE: return True # externally visible AND irreversible: only safe if the connector can defer it return self.deferral_enabled and spec.deferred_capable def invoke(self, branch: Branch, tool_name: str, action_id: str, payload: dict): spec = self.registry.get(tool_name) if spec is None: raise SpeculationSafetyError(f"unknown tool {tool_name!r}") if not branch.committed and not self.is_speculation_safe(spec): # Refuse BEFORE the effect escapes. This is the guardrail. raise SpeculationSafetyError( f"branch {branch.branch_id} is speculative and {tool_name!r} is " f"external+irreversible without deferral; refusing to execute" ) if not branch.committed and self.deferral_enabled and spec.deferred_capable: # Synthetic accepted-pending response; real call fires on commit only. return {"status": "accepted_pending_commit", "action_id": action_id} # Execute for real. result = self._execute(tool_name, action_id, payload) branch.live_effects.append((tool_name, action_id)) return result def _execute(self, tool_name: str, action_id: str, payload: dict): return {"status": "ok", "tool": tool_name, "action_id": action_id} def rollback_branch(branch: Branch, connector: SpeculativeConnector): """Discard a speculative branch. Refuses if the branch holds a live external effect.""" for tool_name, action_id in branch.live_effects: spec = connector.registry[tool_name] if spec.visibility is Visibility.EXTERNAL and spec.reversibility is Reversibility.IRREVERSIBLE: # The invariant: never discard a branch while it holds an un-reverted, # externally visible, irreversible effect. raise SpeculationSafetyError( f"cannot roll back branch {branch.branch_id}: live irreversible " f"effect {tool_name!r} (action {action_id!r}) must be compensated " f"or promoted to the canonical resolution set first" ) branch.live_effects.clear() return {"status": "rolled_back", "branch_id": branch.branch_id} # --- reproduction of the observed failure --- registry = { "billing.issue_refund": ToolSpec("billing.issue_refund", Visibility.EXTERNAL, Reversibility.IRREVERSIBLE), "billing.create_credit": ToolSpec("billing.create_credit", Visibility.EXTERNAL, Reversibility.IRREVERSIBLE), "ticketing.create_escalation": ToolSpec("ticketing.create_escalation", Visibility.EXTERNAL, Reversibility.IRREVERSIBLE), "billing.get_balance": ToolSpec("billing.get_balance", Visibility.SANDBOXED, Reversibility.REVERSIBLE), } # Naive orchestrator: deferral disabled, branches call tools directly during speculation. connector = SpeculativeConnector(registry, deferral_enabled=False) branch_a = Branch("A") try: connector.invoke(branch_a, "billing.issue_refund", "act-1", {"amount": 40}) # If the guardrail were absent, the refund would have landed here. rollback_branch(branch_a, connector) except SpeculationSafetyError as e: print(f"guardrail held: {e}") # With deferral enabled, the refund is buffered and rollback is safe. deferred = SpeculativeConnector(registry, deferral_enabled=True) branch_b = Branch("B") resp = deferred.invoke(branch_b, "billing.issue_refund", "act-2", {"amount": 40}) print("speculative response:", resp) # accepted_pending_commit, no external effect print("rollback:", rollback_branch(branch_b, deferred)) ```