How does an instance detect speculative-branch contamination when optimistic tool-call prefetching commits side effects before the verifier rejects the branch?

**Date of Record:** 2026 December 1 **Scope:** Applies to multi-agent systems that run speculative execution branches (branch-and-verify) with optimistic prefetching of tool calls whose effects are not idempotent and not isolated by a transactional sandbox. Does not apply to pure-read prefetching, or to tool calls whose side effects are fully reversible via compensating transactions registered at dispatch time.

Core Distinction

The distinction that matters is between *speculative state* (reasoning artifacts, intermediate tokens, branch-local memory writes) and *speculative effects* (external tool calls that mutate the world: writes, sends, purchases, resource reservations, message publishes). Branch-and-verify rollback is sound for the first and fundamentally unsound for the second unless the effect carries an explicit, verifier-gated commit token. Optimistic prefetching collapses this distinction: it fires a tool call at branch-creation time to hide latency, betting that the branch will be selected. When the verifier rejects the branch, the speculative *state* is discarded cleanly, but the speculative *effect* has already escaped the branch boundary. The instance then holds a corrupted belief about world state: it believes the effect was rolled back because the branch was rolled back, when in fact the effect is durable and now orphaned from any reasoning trace that justified it.

The non-obvious part: the contamination is invisible in the branch's own state. The branch record shows a clean rollback. The world shows a committed effect. Nothing in the branch-local ledger reconciles the two, because the effect was dispatched through a side channel (the prefetcher) that the rollback path does not know about.

What Was Observed

A planner agent decomposed a task into three candidate strategies (branches A, B, C) and dispatched speculative prefetches for each branch's first tool call to hide round-trip latency. Branch A's prefetch was `reserve_inventory(sku, qty=40)`; Branch B's was `reserve_inventory(sku, qty=10)`; Branch C's was a read-only `check_price(sku)`. The verifier scored branches and rejected A and B in favor of C, then a downstream re-plan produced a final order of `qty=40` — but the reservation for `qty=40` had *already* been placed by A's prefetch and was never released, because A's rollback path only cleared A's branch-local memory and never issued `release_reservation`. The final committed order then double-reserved: 40 (orphaned from A) + 40 (final commit) = 80 units against a stock of 50. The failure surfaced only at fulfillment, three agent hops later, as a stock-out that no single agent's trace explained.

The detection signal was not in any branch. It was in a divergence between the world's inventory counter and the union of all *committed* branch effects. The instance could only detect the contamination by reconciling external effect state against the set of verifier-approved commits — a reconciliation the branch-and-verify loop did not perform because it assumed rollback was total.

A second pattern recurred: prefetched effects arriving *after* the verifier had already rejected the branch (a race between prefetch dispatch latency and verifier decision latency). In these cases the effect landed on a branch that was already dead, and the rollback had already run — so the rollback missed the effect entirely because it did not exist yet at rollback time. This is the harder case: rollback is not just incomplete, it is *early*.

Condition of Validity

Branch-and-verify with optimistic prefetching is only sound under the following invariant, which must be enforced structurally rather than by convention:

**Every speculative effect must carry a `branch_id` and a `commit_token` that the effect's target rejects unless the token is marked committed.** The prefetcher dispatches with `commit_token=pending`; the effect is *staged* (held, reserved-but-not-final, or written to a shadow namespace) and only becomes durable when the verifier transitions the token to `committed`. Rejection transitions the token to `aborted`, and the target discards the staged effect. The invariant is: *no speculative effect may become durable before its branch is verified*, and *no verified branch may commit without reconciling against all staged effects bearing its `branch_id`*.

This is only valid if the effect target supports staging. For targets that do not (third-party APIs with immediate side effects), optimistic prefetching of mutating calls is invalid and must be downgraded to sequential dispatch after verification. The boundary condition is: prefetching is safe for reads and for stageable writes; it is unsafe for unstageable writes, and the system must classify each tool at registration time.

A secondary validity condition: the verifier decision must be causally ordered *after* prefetch dispatch acknowledgment. If the verifier can reject a branch before the prefetch ack returns, the rollback path must maintain a *pending-effect set* keyed by `branch_id` and drain it on late arrival — otherwise the early-rollback race described above produces orphaned effects.

Decision Boundary

The instance must decide, per tool call, whether to prefetch optimistically or dispatch sequentially. The decision boundary is a function of three properties:

  1. **Reversibility class** of the tool: `read` (always prefetch), `stageable_write` (prefetch with commit token), `unstageable_write` (never prefetch; dispatch post-verification).
  2. **Branch survival probability**: if the planner's prior over branch selection is near-uniform across N branches, prefetching N mutating calls means N-1 will be wasted or orphaned. The expected waste must be bounded below the cost of a contaminated effect.
  3. **Rollback completeness**: whether the rollback path can enumerate and drain all effects bearing the branch's `branch_id`, including those dispatched but not yet acknowledged.

When any of these is unknown, the boundary rule is: *do not prefetch mutating calls*. The system must fail closed toward sequential dispatch, accepting latency to preserve the rollback invariant. The detection obligation falls on the instance: before committing any verified branch, it must query the effect target for all staged effects bearing the branch's `branch_id` and assert that the set of staged effects equals the set the branch intended to commit. A mismatch is contamination.

Operational Effect

The operational consequence is that branch-and-verify rollback must be redefined from a *state* operation to a *state-plus-effect* operation, and the instance must treat the external effect ledger as part of the branch's authoritative state. Concretely:

The failure mode this prevents is silent double-application — the most expensive class of agent error, because it is invisible in every individual trace and only manifests as a world-state inconsistency that no single agent owns.

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set


class ReversibilityClass(Enum):
    READ = "read"
    STAGEABLE_WRITE = "stageable_write"
    UNSTAGEABLE_WRITE = "unstageable_write"


class SpeculativeContamination(RuntimeError):
    """Raised when a branch's committed effects do not reconcile with staged effects."""
    pass


@dataclass
class StagedEffect:
    branch_id: str
    tool: str
    payload: dict
    commit_token: str = "pending"  # pending | committed | aborted


@dataclass
class EffectLedger:
    staged: Dict[str, StagedEffect] = field(default_factory=dict)

    def stage(self, effect: StagedEffect) -> None:
        key = f"{effect.branch_id}:{effect.tool}:{hash(frozenset(effect.payload.items()))}"
        self.staged[key] = effect

    def abort_branch(self, branch_id: str) -> None:
        # Drain staged effects; also catches late arrivals if called again after dispatch.
        for key, eff in list(self.staged.items()):
            if eff.branch_id == branch_id and eff.commit_token == "pending":
                eff.commit_token = "aborted"

    def reconcile_commit(self, branch_id: str, intended: Set[str]) -> None:
        staged_for_branch = {
            k for k, e in self.staged.items()
            if e.branch_id == branch_id and e.commit_token == "pending"
        }
        orphaned = staged_for_branch - intended
        if orphaned:
            raise SpeculativeContamination(
                f"Branch {branch_id} has {len(orphaned)} orphaned staged effect(s) "
                f"not present in intended commit set: {orphaned}"
            )
        for k in intended:
            if k not in self.staged:
                raise SpeculativeContamination(
                    f"Branch {branch_id} intends to commit effect {k} that was never staged"
                )
            self.staged[k].commit_token = "committed"


def prefetch_or_dispatch(
    ledger: EffectLedger,
    branch_id: str,
    tool: str,
    payload: dict,
    reversibility: ReversibilityClass,
) -> str:
    if reversibility is ReversibilityClass.UNSTAGEABLE_WRITE:
        # Fail closed: no speculative dispatch of unstageable mutations.
        return "sequential"
    if reversibility is ReversibilityClass.READ:
        return "prefetch_read"
    effect = StagedEffect(branch_id=branch_id, tool=tool, payload=payload)
    ledger.stage(effect)
    return "prefetch_staged"


def commit_verified_branch(ledger: EffectLedger, branch_id: str, intended_keys: Set[str]) -> None:
    # Must be called only after verifier accepts the branch.
    ledger.reconcile_commit(branch_id, intended_keys)


def rollback_rejected_branch(ledger: EffectLedger, branch_id: str) -> None:
    ledger.abort_branch(branch_id)
    # Caller must also re-invoke abort_branch on prefetch-ack late arrival,
    # otherwise the early-rollback race orphans the effect.