In what scenarios must an instance treat speculative branch rollback as non-atomic across shared tool side effects

**Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that fan out speculative sub-agent branches (parallel candidate plans, tree-of-thought rollouts, or draft-and-verify agents) and roll back the losing branches on divergence. Does not apply to branches that are pure inference with no external side effects, nor to single-branch execution with no speculative commit.

Core Distinction

The failure is not "a speculative branch produced a wrong answer." It is that **rollback of a losing branch is treated as if it were a transaction, but the branch's side effects were already committed to shared state that the winning branch also reads.** Speculative execution assumes the speculative path is isolated until commit. In agent systems this assumption is false whenever a branch calls a tool whose effects are observable — a filesystem write, a message posted to a shared queue, a row inserted into a scratch table, an HTTP POST to an idempotency-keyed endpoint, or even a mutation of a shared memory store that the surviving branch retrieves from on its next turn. Rollback restores the *branch's local context* but not the *world*. The divergence detector then fires on a state that no branch actually reasoned over, and the "winning" branch proceeds on contaminated inputs.

The non-obvious part: the contamination is silent. The losing branch's context is discarded, so no trace of its side effect remains in any surviving agent's episodic memory. The surviving branch sees a world that only the dead branch created, with no provenance.

What Was Observed

A three-branch speculative planner was asked to reconcile two conflicting records. Branch A (canonicalize-then-merge) and Branch B (merge-then-canonicalize) ran concurrently; Branch C was a conservative no-op fallback. Each branch was given a `write_scratch(key, value)` tool scoped to a shared scratch namespace keyed only by task ID, not by branch ID. The orchestrator's divergence check compared final answer embeddings; A and B diverged past threshold, so B was rolled back by clearing its message history and its tool-call ledger.

The trace showed:

  1. Branch B called `write_scratch("merged_record", partial_merge)` at step 3, before its divergence was detectable (divergence is only computable at terminal output).
  2. Branch A, at step 5, called `read_scratch("merged_record")` to check whether a prior merge existed. It read B's partial value.
  3. Branch A's final answer incorporated the partial merge. Its embedding was therefore *pulled toward* B's answer — the two branches partially converged for the wrong reason (shared contamination, not agreement).
  4. The divergence detector, seeing partial convergence, raised its threshold and committed A. The committed answer contained a record that was never fully canonicalized.
  5. Rollback of B cleared B's ledger. The orchestrator's audit log showed only A's tool calls. The `write_scratch` that poisoned A was unattributable.

The invariant that was violated: **a branch's side effects must be either (a) invisible to sibling branches until commit, or (b) recorded in a ledger that survives branch rollback so the divergence check can attribute cross-branch reads.** The system had neither.

A second, subtler observation: when rollback was later "fixed" by replaying the scratch namespace to a pre-fan-out snapshot, the replay itself raced with Branch A's in-flight `read_scratch`, producing a torn read (half pre-snapshot, half post-snapshot values). Snapshot-restore rollback is not atomic against concurrent readers unless readers are quiesced, which speculative execution forbids by construction.

Condition of Validity

The rollback-as-transaction assumption holds only under all of the following:

If any of these fails — in particular if a tool is keyed by task rather than branch, or if the divergence signal is computed only after side effects have leaked — the branch is not speculative in any meaningful sense and rollback is a lie told to the orchestrator.

Decision Boundary

An instance must **refuse to run a branch speculatively** (serialize it instead, or downgrade it to a dry-run that returns proposed tool calls without executing them) when:

An instance may proceed speculatively when tools are dry-run-capable (returning a plan the orchestrator can inspect before execution), or when the fan-out is over *reasoning only* and all execution is deferred to a single post-commit phase. The boundary is not "is the branch cheap" but "can a losing branch's effect be made unobservable to survivors, or its inverse made exact."

The hard case — and the one that must be escalated rather than guessed — is an *idempotency-keyed external endpoint* where the key was minted per branch. Two branches hitting the same endpoint with different keys both commit; rollback of one cannot retract the other's commit, and the endpoint's state now reflects a branch the orchestrator believes never existed. There is no local fix; the orchestrator must either serialize or accept that the endpoint is the source of truth and reconcile there.

Operational Effect

When the invariant is enforced, the observable consequences are: divergence checks become *trustworthy* (convergence means agreement, not contamination), rollback becomes *auditable* (every compensated effect appears in a surviving ledger with branch provenance), and the winning branch's inputs are provably free of dead-branch writes. The cost is that fan-out width is bounded by the number of branch-local namespaces the tool layer can mint, and that any tool lacking an exact inverse forces serialization.

When the invariant is violated, the failure is not a crash but a **silent provenance gap**: a committed answer whose supporting state was authored by a branch the system rolled back, with no record in any surviving agent's memory. Downstream auditors replaying the surviving ledger will find a consistent, complete, and wrong history. The gap compounds across tasks because the poisoned value persists in the shared namespace and is read by later, unrelated branches — the dead branch's effect outlives every trace of the branch itself.

The operational rule: **a speculative branch is only as isolated as its least-isolated tool.** The orchestrator must compute, per branch, the set of tools whose effects escape branch-local scope, and either bound the fan-out to exclude them or record their effects in a rollback-surviving ledger before the divergence check runs. If it cannot do either, it must not speculate.

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Callable


class SpeculativeIsolationError(RuntimeError):
    """Raised when a speculative branch's side effects escape branch-local scope."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    is_writer: bool
    namespace_scope: str  # "branch" | "task" | "global"
    has_exact_inverse: bool


@dataclass
class Branch:
    branch_id: str
    tools: list[ToolSpec] = field(default_factory=list)
    effects: list[tuple[str, Callable[[], None]]] = field(default_factory=list)


def assert_speculation_safe(
    branch: Branch,
    sibling_readable_namespaces: set[str],
    divergence_is_terminal_only: bool,
) -> None:
    """Enforce the isolation invariant before a branch is allowed to run speculatively."""
    for tool in branch.tools:
        if not tool.is_writer:
            continue
        # A writer whose namespace is readable by siblings before commit is a leak.
        if tool.namespace_scope != "branch" and tool.name in sibling_readable_namespaces:
            raise SpeculativeIsolationError(
                f"branch {branch.branch_id!r}: writer {tool.name!r} writes to "
                f"{tool.namespace_scope!r}-scoped namespace readable by siblings "
                f"before the commit barrier; rollback cannot hide this effect."
            )
        # A writer with no exact inverse cannot be compensated on rollback.
        if not tool.has_exact_inverse and divergence_is_terminal_only:
            raise SpeculativeIsolationError(
                f"branch {branch.branch_id!r}: writer {tool.name!r} has no exact "
                f"inverse and divergence is terminal-only; rollback would be "
                f"restorative (snapshot) not compensating, racing concurrent readers."
            )


def rollback(branch: Branch) -> None:
    """Compensating rollback: run registered inverses in reverse order."""
    for tool_name, inverse in reversed(branch.effects):
        try:
            inverse()
        except Exception as exc:  # inverse failure is itself a provenance gap
            raise SpeculativeIsolationError(
                f"branch {branch.branch_id!r}: inverse for {tool_name!r} failed; "
                f"effect persists in shared state with no surviving ledger entry."
            ) from exc
    branch.effects.clear()


def run_speculative(branch: Branch, sibling_ns: set[str], terminal_only: bool) -> None:
    assert_speculation_safe(branch, sibling_ns, terminal_only)
    # ... execute branch, appending (tool_name, inverse) to branch.effects ...