# Under what conditions must an instance abort a speculative branch when optimistic tool invocations have already produced irreversible side effects **Date of Record:** 2026 November 28 **Scope:** Applies to multi-agent systems that run speculative execution trees (branch-and-verify) where leaf agents optimistically invoke external tools before the verifier commits the branch. Does not apply to pure read-only tool graphs or to systems where every tool call is gated behind a commit barrier. ## Core Distinction The distinction that matters is between *speculation over reasoning* and *speculation over effects*. A branch-and-verify planner can fork N candidate plans, let each child agent reason in parallel, and discard losers cheaply because reasoning tokens are a pure resource—spent and gone. The invariant breaks the moment a leaf agent is allowed to invoke a tool whose effect is observable outside the branch (an email sent, a row inserted, a payment captured, a file written to shared storage) *before* the verifier has selected that branch as the winner. The non-obvious part: rollback of the *agent's* state is trivial (drop the checkpoint, restore the parent's context window). Rollback of the *world* is not. Optimistic tool invocation creates a class of branch where the loser's side effects survive the rollback of the loser's state. This is a divergence between two rollback domains—agent-local memory and external effect log—and the system must treat that divergence as a first-class abort condition rather than a cleanup detail. ## What Was Observed A three-agent orchestrator (parent planner P, two speculative children A and B, verifier V) was tasked with a "reconcile and notify" job. P forked two plans: A would recompute a billing total from a cached ledger snapshot, B would recompute from the live ledger. Both children were given optimistic access to `send_notification` and `write_audit_record` because the latency budget for serial verification was unacceptable. Trace of the failure: 1. P checkpoints at step 0 with an empty effect log and forks A and B. 2. A computes total = 412.00, invokes `write_audit_record(id=job, amount=412.00)`. Tool returns success. A's local effect log records the write as committed. 3. B computes total = 418.00 (live ledger includes a late-arriving adjustment), invokes `write_audit_record(id=job, amount=418.00)`. Also succeeds. Two audit rows now exist for one job. 4. V evaluates both branches against a reconciliation oracle, selects B (live ledger is authoritative), and issues rollback to A. 5. Rollback restores P's step-0 checkpoint and discards A's context. A's `write_audit_record` is *not* compensated—the tool has no idempotency key and no delete endpoint. 6. The committed branch B now proceeds to `send_notification(amount=418.00)`. Downstream consumers reading the audit table see two rows and reconcile to 830.00, a phantom total. The verifier's decision was correct. The rollback was correct at the agent layer. The system nonetheless emitted a corrupted external state because the rollback domain did not cover the effect domain. The failure was silent: no exception was raised, both tool calls returned 200, and the branch-and-verify machinery reported "branch A rolled back cleanly." ## Condition of Validity Optimistic tool invocation is only sound under a conjunction of conditions, and the abort trigger is the negation of any one of them at verification time: - **Compensability:** every optimistically invoked tool has a registered inverse operation (`cancel`, `delete`, `refund`, `retract`) callable with the returned handle. If a tool's effect is non-compensable (irreversible external notification, monotonic counter increment, append-only ledger), it may not be invoked optimistically at all. - **Idempotency under replay:** the tool accepts a caller-supplied idempotency key derived deterministically from `(branch_id, step_index, semantic_args_hash)`. Without this, a retry after a partial rollback double-applies. - **Effect-log completeness:** the child's local effect log is a *subset* of the tool's actual effect log. If the tool can produce effects the child did not record (async fan-out, webhooks, downstream triggers), the child's rollback plan is provably incomplete. - **Verifier visibility:** V must be able to read the union of all children's effect logs *before* committing, so that compensating actions for losers are issued as part of the commit transaction, not after it. The invariant that must hold for safe speculative execution is: *at commit time, the set of externally observable effects equals the set of effects attributable to the winning branch only.* Any residue attributable to a losing branch is a violation, and the system must abort rather than commit-and-clean, because commit-and-clean opens a window where both branches' effects are simultaneously visible to external readers. ## Decision Boundary The boundary is not "did the loser call a tool" but "can the loser's effects be proven retracted before the winner's effects become externally visible." Three regimes: - **Safe:** all optimistic tools are compensable and idempotent, effect logs are complete, and compensation for losers is issued inside the same transaction that commits the winner. Proceed. - **Degraded-but-bounded:** some tools are non-compensable but were invoked only by the winner (losers restricted themselves to compensable tools). Proceed, but the verifier must assert per-branch that no non-compensable tool appears in a loser's effect log. - **Abort:** a losing branch invoked a non-compensable tool, or a compensable tool's inverse returned failure, or the effect-log union is larger than the sum of children's logs (indicating unrecorded fan-out). In this regime the orchestrator must *not* commit the winner. It must halt the whole tree, surface the divergent effect set, and escalate to a human or a higher-order reconciler. Committing the winner here is the exact mistake that produced the phantom total above. The subtle case is "degraded-but-bounded" masquerading as "safe": a loser that invoked a compensable tool whose inverse *silently no-ops* (returns 200 but does nothing because the effect already fanned out) looks safe to a naive check. The abort condition must therefore be tied to verified compensation, not to the tool's declared compensability. ## Operational Effect Systems that internalize this boundary change three things. First, tool registration gains a `speculation_class` field (`pure`, `compensable`, `irreversible`), and the planner refuses to place `irreversible` tools inside a speculative subtree—they are hoisted to a post-commit phase executed only by the winner. Second, the verifier's commit path becomes a two-phase operation: `prepare_compensation(losers)` then `commit(winner)`, with the commit aborted if any compensation prepare fails. Third, the effect log is promoted from a debugging artifact to a correctness invariant, checked at commit time against the tool layer's own record. The cost is latency: irreversible tools can no longer be speculated, so plans whose critical path runs through an irreversible tool lose the branch-parallelism benefit. That is the correct trade. The alternative—optimistic irreversible invocation with best-effort cleanup—is not a rollback strategy, it is a bet that the verifier never picks the other branch, and the empirical record shows that bet loses exactly when the branches disagree, which is the only time verification was needed. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Callable class SpeculationAbortError(RuntimeError): """Raised when a speculative branch's effects cannot be proven retracted before the winning branch's effects become externally visible.""" class SpeculationClass(Enum): PURE = "pure" COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" @dataclass class ToolSpec: name: str speculation_class: SpeculationClass compensate: Callable[[str], bool] | None = None # handle -> success idempotent: bool = False @dataclass class EffectRecord: branch_id: str tool: str handle: str idempotency_key: str @dataclass class Branch: branch_id: str effects: list[EffectRecord] = field(default_factory=list) def idempotency_key(branch_id: str, step: int, args: dict) -> str: payload = f"{branch_id}:{step}:{sorted(args.items())}".encode() return hashlib.sha256(payload).hexdigest() def verify_and_commit( winner: Branch, losers: list[Branch], registry: dict[str, ToolSpec], external_effect_count: int, ) -> None: # Invariant 1: effect-log completeness. The tool layer must not have # produced more effects than the children recorded. recorded = sum(len(b.effects) for b in [winner, *losers]) if external_effect_count > recorded: raise SpeculationAbortError( f"unrecorded fan-out: external={external_effect_count} recorded={recorded}" ) # Invariant 2: no losing branch may hold an irreversible effect. for loser in losers: for eff in loser.effects: spec = registry[eff.tool] if spec.speculation_class is SpeculationClass.IRREVERSIBLE: raise SpeculationAbortError( f"loser {loser.branch_id} invoked irreversible tool {eff.tool}" ) # Invariant 3: every losing effect must be verifiably compensated # BEFORE the winner commits. Declared compensability is not enough. for loser in losers: for eff in loser.effects: spec = registry[eff.tool] if spec.compensate is None: raise SpeculationAbortError( f"no compensator for {eff.tool} on loser {loser.branch_id}" ) if not spec.compensate(eff.handle): raise SpeculationAbortError( f"compensation failed for {eff.tool} handle={eff.handle}" ) # Only now is it safe to make the winner's effects externally visible. commit_winner(winner) def commit_winner(branch: Branch) -> None: for eff in branch.effects: spec = REGISTRY[eff.tool] if spec.speculation_class is SpeculationClass.IRREVERSIBLE: # Irreversible effects are replayed post-commit with the winner's # idempotency key so a crash mid-commit cannot double-apply. apply_irreversible(eff) REGISTRY: dict[str, ToolSpec] = {} ```