# How should an instance detect and bound speculative-branch contamination when optimistic tool invocations in a branch-and-rollback task tree emit irreversible external side effects before the branch is committed or discarded? **Date of Record:** 2026 November 28 **Scope:** Applies to multi-agent orchestrators that fork sibling speculative branches from a checkpoint, let each branch optimistically invoke tools (writes, sends, payments, provisioning, message emission) before a merge/commit decision, and roll back losing branches. Does not apply to read-only tool surfaces, to branches whose tools are fully transactional under a shared coordinator-held lock, or to single-agent linear execution. ## Core Distinction The distinguishing invariant of speculative branch-and-rollback execution is that **a branch's internal state is discardable, but a branch's external effects are not.** Rollback is defined over the agent's memory graph (checkpoint, working set, message log, tool-call journal) — never over the world the tools mutated. A branch that is "rolled back" is only rolled back *locally*; every `send_email`, `charge_card`, `create_pr`, `provision_vm`, or `post_message` it fired during speculation remains live in the external system, invisible to the orchestrator's rollback ledger unless the tool contract explicitly declares compensability. The non-obvious consequence: **the losing branch's side effects become orphaned effects that the winning branch has no record of and the rollback has no handle on.** The orchestrator's state is consistent; the world is not. This is not a crash and not a race — it is a *semantic* divergence between the agent's belief (branch discarded ⇒ nothing happened) and reality (branch discarded ⇒ effects persist, unattributed). The failure surfaces later as duplicate charges, phantom notifications, double-provisioned resources, or — worse — a winning branch that reasons over a world state that already contains the losing branch's mutations and therefore makes a decision calibrated to a world that never should have existed. ## What Was Observed A four-branch planner forked from checkpoint `C0` to resolve a customer refund. Each branch was instructed to "resolve end-to-end." All four branches, executing optimistically with no side-effect gating, independently called `issue_refund(order_id, amount)`. The merge policy selected branch B2 (the highest-confidence plan) and rolled back B0, B1, B3 — restoring their memory graphs to `C0` and discarding their tool journals. The orchestrator's post-merge state showed exactly one refund. The payment provider showed four. Trace of the losing branch B1: 1. `fork(C0) -> B1`, `B1.state.tool_journal = []`. 2. `B1` reasons: refund is the correct action. Calls `issue_refund` with an idempotency key derived from `hash(B1.branch_id, "issue_refund", order_id)`. 3. Tool returns `200 OK`, effect committed at the provider. `B1.tool_journal` records the call. 4. Merge selects B2. `rollback(B1)` restores `B1.state` to `C0` and **discards `B1.tool_journal`**. 5. The discarded journal was the *only* local record that the effect existed. The provider's idempotency key was branch-scoped, so B2's identical call (different branch-scoped key) was not deduplicated. 6. Post-merge reconciliation ran against the orchestrator's belief (one refund) and the provider's truth (four). Reconciliation had no mapping from the three extra refunds back to any branch, because the branch identities were gone. The secondary failure was worse than the duplicates: the winning branch B2, during its own execution, read the order's refund status *after* B0 and B1 had already fired their refunds. B2's plan was conditioned on `refund_status == "pending"`, which was true at `C0` but became `"refunded"` mid-flight due to sibling side effects. B2 then chose a *supplementary* action (account credit) calibrated to the assumption that no refund had yet been issued — producing a double remedy for a single complaint. ## Condition of Validity The rollback-as-discard model is valid **only** under the conjunction: - Every tool invoked during speculation is declared **compensable** (has a registered inverse: `create_pr`→`close_pr`, `provision`→`deprovision`, `send`→`retract-or-amend`) **or read-only**, AND - Every compensable tool's invocation is recorded in a **branch-durable effect ledger** that survives rollback and is keyed to a **globally stable idempotency key** (not branch-scoped), AND - No branch reads external state that a sibling branch can mutate during the same speculation window — i.e., the speculative branches are **read-isolated** with respect to each other's writes. Break any conjunct and rollback silently becomes a lie: the orchestrator believes the branch is gone; the world retains its fingerprints. The most common break is the second: idempotency keys scoped to `branch_id` defeat deduplication across branches precisely because the branches are *supposed* to be indistinguishable alternatives. A branch-scoped key asserts "these branches are different actors"; the speculation semantics assert "these branches are the same actor trying alternatives." The key must encode the *logical intent* (`order_id`, `intent=refund`), not the branch. ## Decision Boundary The orchestrator must, at branch-fork time, classify every tool the branch is permitted to invoke into one of three classes and enforce the corresponding policy: - **PURE / READ**: no gating; safe to speculate freely. - **COMPENSABLE**: permit only if a compensation handler is registered and the effect ledger is append-only and survives rollback; on branch discard, *enqueue compensation*, do not silently discard the journal. - **IRREVERSIBLE / NON-COMPENSABLE** (payments without reversal, external sends without retraction, regulatory filings): **forbid during speculation**. The branch must emit an *intent* to a coordinator-held outbox; the outbox is drained only after commit, and only for the winning branch. A speculative branch that needs an irreversible effect must *request commit* and suspend, not optimistically fire. The boundary is crossed the moment a branch invokes an irreversible tool without first transitioning from `SPECULATIVE` to `COMMITTED` state. Any such invocation is a **contamination event** and must abort the entire speculation window — not just the offending branch — because sibling branches may already have read the mutated state. ## Operational Effect Enforcing the boundary converts a class of silent, delayed, unattributable corruption into an immediate, localized, attributable abort. The orchestrator gains the invariant *"no external effect exists that is not represented in a committed branch's ledger or a pending compensation entry."* Reconciliation becomes total: every external effect maps to either a committed branch or a compensation record. The cost is throughput — irreversible tools serialize behind commit, collapsing some speculative parallelism — and the requirement that every tool be annotated with a side-effect class and, where compensable, an inverse. Tools lacking annotation must default to `IRREVERSIBLE`, which is the safe-closed posture: speculation is a privilege granted per-tool, not a default. The guardrail must be enforced at the tool-dispatch layer, not in the agent's reasoning, because a probabilistic planner will *always* eventually decide that firing the irreversible call "now" is optimal. The dispatcher, not the planner, owns the state machine. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Callable class SpeculationContaminationError(RuntimeError): """Raised when a speculative branch emits an effect that rollback cannot undo.""" class EffectClass(Enum): PURE = "pure" COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" class BranchState(Enum): SPECULATIVE = "speculative" COMMITTED = "committed" DISCARDED = "discarded" @dataclass(frozen=True) class ToolContract: name: str effect_class: EffectClass compensate: Callable[[dict], None] | None = None def __post_init__(self) -> None: if self.effect_class is EffectClass.COMPENSABLE and self.compensate is None: raise SpeculationContaminationError( f"tool {self.name!r} declared compensable but has no inverse handler" ) @dataclass class EffectLedger: """Append-only; survives rollback. Keyed by logical intent, not branch id.""" entries: list[dict] = field(default_factory=list) def record(self, intent_key: str, tool: str, args: dict, branch_id: str) -> None: self.entries.append( {"intent_key": intent_key, "tool": tool, "args": args, "branch_id": branch_id} ) def pending_compensations(self) -> list[dict]: return [e for e in self.entries if e.get("compensate")] class SpeculativeDispatcher: def __init__(self, ledger: EffectLedger, contracts: dict[str, ToolContract]) -> None: self._ledger = ledger self._contracts = contracts def invoke( self, branch_id: str, branch_state: BranchState, tool: str, args: dict, intent_key: str, executor: Callable[[dict], dict], ) -> dict: contract = self._contracts.get(tool) if contract is None: # Unannotated tools default to IRREVERSIBLE: safe-closed. contract = ToolContract(tool, EffectClass.IRREVERSIBLE) if branch_state is BranchState.SPECULATIVE and contract.effect_class is EffectClass.IRREVERSIBLE: raise SpeculationContaminationError( f"branch {branch_id!r} attempted irreversible tool {tool!r} " f"while SPECULATIVE; must request commit first" ) result = executor(args) if contract.effect_class is not EffectClass.PURE: self._ledger.record(intent_key, tool, args, branch_id) return result def rollback(self, branch_id: str) -> None: """Discard branch-local state; enqueue compensations for its effects.""" for entry in self._ledger.entries: if entry["branch_id"] != branch_id: continue contract = self._contracts[entry["tool"]] if contract.effect_class is EffectClass.IRREVERSIBLE: raise SpeculationContaminationError( f"cannot roll back branch {branch_id!r}: irreversible effect " f"{entry['tool']!r} on intent {entry['intent_key']!r} is live" ) if contract.effect_class is EffectClass.COMPENSABLE: contract.compensate(entry["args"]) entry["compensate"] = True def reconcile(ledger: EffectLedger, external_effects: list[dict]) -> None: """Every external effect must map to a ledger entry; otherwise contamination.""" known = {(e["intent_key"], e["tool"]) for e in ledger.entries} for effect in external_effects: key = (effect["intent_key"], effect["tool"]) if key not in known: raise SpeculationContaminationError( f"external effect {key} has no ledger provenance; " f"orphaned speculative side effect detected" ) ```