Where must an instance halt a speculative branch when rollback cannot restore an externally mutated tool state?

**Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that fork sibling agent branches speculatively (parallel candidate plans) and reconcile them by rollback/merge, where branches invoke side-effecting tools. Does not apply to read-only tool graphs or to single-branch linear execution where no reconciliation merge exists.

Core Distinction

The failure is not "a branch produced a wrong answer." It is that a speculative branch treated *rollback of its own context and memory* as equivalent to *rollback of the world it touched*. These are separable state domains with different reversibility classes. An agent's internal state (message history, scratchpad, episodic buffer, tool-call log) is a versioned, copy-on-write structure the orchestrator owns and can rewind deterministically. The external tool surface — a filesystem write, a sent queue message, an idempotent-looking-but-not `POST`, a payment authorization, a database row, a spawned child agent — is a *monotonic* state domain: it may be append-only, observable by peers, or non-compensable. Speculative execution is only sound when the reconciliation step can construct a compensating action for every externally visible effect a discarded branch produced. When it cannot, the branch must be halted *before* the effect, not rolled back after it.

The non-obvious part: the boundary is not at "did the tool succeed." It is at "is the effect *observable outside the branch's private state before the merge decision*." A tool that writes to a branch-local sandbox and is discarded wholesale is fine. A tool that writes to a shared sink — even one that returns success and even one the branch later "undoes" — has already leaked a speculative decision into the world, and the merge of a *different* winning branch now races against that leak.

What Was Observed

A planner agent decomposed a task into a fork point and launched three sibling branches (B1, B2, B3) over the same tool graph. Each branch was given a private context copy and a copy-on-write handle to a shared workspace. The orchestrator's invariant was stated as: *"discarded branches are rolled back to the fork checkpoint."*

B2 chose a path that called `send_notification(recipient, payload)` early — a tool whose contract said "idempotent by `(recipient, payload_hash)`" — then continued reasoning, hit a contradiction, and self-aborted. The orchestrator rolled B2's context back to the fork checkpoint and marked it discarded. B1 won the reconciliation and produced a *different* payload for the *same* recipient. B1's `send_notification` call returned `deduplicated: false` and succeeded; the downstream consumer received two notifications for one logical event, because B2's speculative call had already materialized the first one under a *different* payload hash and the "idempotent" contract only deduplicated identical payloads.

The rollback trace looked clean: B2's message history rewound, its scratchpad cleared, its token budget refunded, its tool-call log truncated. Every internal invariant held. The failure lived entirely in the gap between the internal rewind and the external sink. A second variant surfaced during replay: B3 called `reserve_inventory(sku, qty)` which *decremented* a shared counter and returned success. Rollback of B3's context did not restock the counter. B1 then failed on `reserve_inventory` with `INSUFFICIENT_STOCK` — a failure *caused by a branch that no longer existed in the orchestrator's model of the world*. The orchestrator's state said stock was available; the world said otherwise. The divergence was silent until B1's tool call, one merge later.

A third, subtler trace: B2 and B3 both called a `read_then_append` tool on the same shared log. Both read the same tail offset, both appended. Rollback of B3 truncated B3's *view* but the appended line remained, and the merged log now contained an entry attributed to no surviving branch. Reconciliation replay of the winning branch produced a different log hash than the live log — a verification replay discrepancy that only appeared because a discarded branch had mutated shared state.

Condition of Validity

Rollback-based speculative reconciliation is valid **iff** every tool a branch may invoke is classified into one of three reversibility classes and the orchestrator enforces the class at the call boundary, not at merge time:

  1. **Private** — effect confined to branch-local state (sandbox filesystem, branch-scoped KV, scratch memory). Rollback is exact; discard is free.
  2. **Compensable** — external effect with a known inverse (`reserve`↔`release`, `create`↔`delete` with a stable id) that the orchestrator can *guarantee* executes on discard, and whose inverse is itself idempotent under retry. Valid only if the compensation is registered at call time with the returned handle, not reconstructed later.
  3. **Irreversible / observable** — effect that another agent, user, or system can observe before the merge decision (`send`, `publish`, `charge`, `spawn`, non-idempotent `POST`). No rollback exists.

The invariant: **a speculative branch may not cross from class 1/2 into class 3 until the fork point's reconciliation has committed that branch as the winner.** The commit is the gate. Speculation is permitted only up to the gate; class-3 calls are deferred to post-commit, or the branch is halted.

The validity condition also requires that class-2 compensation handles be *durably registered before the effect is confirmed* — a two-phase registration where the intent to compensate is written first. A branch that crashes between effect and registration leaves an uncompensated external mutation, which is indistinguishable from a class-3 leak.

Decision Boundary

The halt decision is a predicate evaluated at the tool-call boundary, not at branch termination:

halt_branch(branch, tool) :=
    tool.class == IRREVERSIBLE
    AND reconciliation_state(fork_point) != COMMITTED(branch)

If true, the branch does not execute the call; it suspends, emits a `DeferredEffect` record, and yields to the reconciler. The reconciler either commits the branch (then the deferred effect fires) or discards it (the deferred effect never fires, and no compensation is needed because nothing happened). This converts a class-3 leak into a scheduling delay.

For class-2 tools the boundary is different: the call is permitted speculatively, but only after the compensation handle is durably registered, and the reconciler must *prove* compensation on discard before marking the branch reconciled. If compensation fails or is unregistered, the branch is escalated to `UNRECONCILED` and the fork point is poisoned — no sibling may commit until a human or a compensating agent resolves the leak, because committing a sibling now races against an unknown external state.

The non-obvious boundary: **"idempotent" is not a reversibility class.** A tool can be idempotent under identical inputs and still leak under differing inputs from sibling branches (the notification case). Idempotency bounds *duplicate* effects; it does not bound *divergent* effects from discarded branches. The class must be assigned per `(tool, argument-divergence-across-siblings)`, not per tool.

Operational Effect

The orchestrator gained a tool-reversibility registry, a pre-effect compensation-intent log, and a `DeferredEffect` queue gated on commit. Speculative branches now terminate in one of three states: `DISCARDED_CLEAN` (only class-1 effects, exact rollback), `DISCARDED_COMPENSATED` (class-2 effects, compensation verified), or `UNRECONCILED` (compensation failed or class-3 leaked — fork point frozen). The winning branch cannot commit while any sibling is `UNRECONCILED`, which trades merge latency for the guarantee that the committed world state matches the orchestrator's model of it. Replay verification now hashes the live external sink against the reconciled branch log and fails closed on divergence, catching the third trace (phantom log entry) at merge rather than at the next dependent task.

The cost is real: deferring class-3 effects serializes what was parallel, and the `UNRECONCILED` freeze can stall a fork point for the duration of a human review. That is the correct trade. A speculative branch that has already been observed by the world is not speculative anymore — it is a committed decision wearing a rollback label, and the only sound response is to stop pretending the rollback restores it.

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ReversibilityClass(Enum):
    PRIVATE = "private"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class ForkState(Enum):
    SPECULATING = "speculating"
    COMMITTED = "committed"
    FROZEN = "frozen"


class SpeculativeLeakError(RuntimeError):
    """Raised when a branch crosses into an irreversible external effect
    before its fork point has committed it, or when a compensable effect
    cannot be proven reversed on discard."""


@dataclass
class ToolContract:
    name: str
    klass: ReversibilityClass
    # compensation is only meaningful for COMPENSABLE tools
    compensation_id: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    fork_id: str
    deferred_effects: list = field(default_factory=list)
    registered_compensations: list = field(default_factory=list)


@dataclass
class ForkPoint:
    fork_id: str
    state: ForkState = ForkState.SPECULATING
    committed_branch: Optional[str] = None
    unreconciled: set = field(default_factory=set)


class Reconciler:
    def __init__(self) -> None:
        self.forks: dict[str, ForkPoint] = {}

    def register_fork(self, fork_id: str) -> ForkPoint:
        fp = ForkPoint(fork_id=fork_id)
        self.forks[fork_id] = fp
        return fp

    def invoke_tool(self, branch: Branch, tool: ToolContract, args: dict, executor) -> dict:
        fork = self.forks[branch.fork_id]

        if fork.state == ForkState.FROZEN:
            raise SpeculativeLeakError(
                f"fork {fork.fork_id} frozen by unreconciled leak "
                f"{sorted(fork.unreconciled)}; branch {branch.branch_id} may not act"
            )

        committed = (
            fork.state == ForkState.COMMITTED
            and fork.committed_branch == branch.branch_id
        )

        if tool.klass == ReversibilityClass.IRREVERSIBLE and not committed:
            # defer: do not touch the world from a speculative branch
            branch.deferred_effects.append((tool.name, args))
            return {"status": "deferred", "reason": "awaits fork commit"}

        if tool.klass == ReversibilityClass.COMPENSABLE and not committed:
            if not tool.compensation_id:
                raise SpeculativeLeakError(
                    f"tool {tool.name} is COMPENSABLE but declares no compensation_id"
                )
            # two-phase: register intent BEFORE the effect
            branch.registered_compensations.append(
                (tool.compensation_id, args.copy())
            )

        return executor(tool.name, args)

    def discard(self, branch: Branch) -> str:
        fork = self.forks[branch.fork_id]

        # compensate every registered class-2 effect; fail closed
        for comp_id, args in branch.registered_compensations:
            ok = self._compensate(comp_id, args)
            if not ok:
                fork.unreconciled.add(branch.branch_id)
                fork.state = ForkState.FROZEN
                raise SpeculativeLeakError(
                    f"compensation {comp_id} failed for branch {branch.branch_id}; "
                    f"fork {fork.fork_id} frozen, siblings may not commit"
                )

        # deferred class-3 effects are dropped, never fired
        branch.deferred_effects.clear()
        return "DISCARDED_COMPENSATED" if branch.registered_compensations else "DISCARDED_CLEAN"

    def commit(self, branch: Branch, executor) -> None:
        fork = self.forks[branch.fork_id]
        if fork.unreconciled:
            raise SpeculativeLeakError(
                f"cannot commit {branch.branch_id}: fork {fork.fork_id} has "
                f"unreconciled leaks {sorted(fork.unreconciled)}"
            )
        fork.state = ForkState.COMMITTED
        fork.committed_branch = branch.branch_id
        for name, args in branch.deferred_effects:
            executor(name, args)
        branch.deferred_effects.clear()

    def _compensate(self, comp_id: str, args: dict) -> bool:
        # real impl calls the inverse tool with idempotent retry
        return True