Which invariants prevent speculative branch rollouts from committing side effects that survive rollback reconciliation

**Date of Record:** 2026 December 1 **Scope:** Applies to multi-agent orchestrators that fan out a single task into parallel speculative branches (each branch an independent LLM agent instance with tool access) and reconcile by selecting one winning branch and discarding the rest. Does not apply to strictly serial single-agent execution, nor to branches whose tools are provably pure (no external state mutation).

Core Distinction

The distinction that governs everything below is between **rollback of reasoning state** and **rollback of world state**. An orchestrator can trivially discard a losing branch's context window, token history, and intermediate scratchpad — those are local, private, and cheap to abandon. What it cannot trivially discard is the *effect* of a tool call that already crossed the process boundary and mutated something durable: a database row, a sent email, a file on disk, a payment, a deployed artifact, a message enqueued to another agent.

Speculative parallel execution is safe only under an invariant that most orchestrators assert implicitly and never verify:

> **Speculation Invariant:** *No branch may commit an irreversible external effect before the reconciliation step names it the winner.*

The failure mode is not "a branch made a bad call." It is that two branches both made *valid* calls, both effects landed, reconciliation picked one branch's *reasoning* as canonical, and the losing branch's *side effects* remained in the world — orphaned, unowned, and invisible to the winning branch's subsequent reasoning. The winner proceeds believing the world matches its plan; the world does not.

What Was Observed

A planner agent decomposed a request into a task requiring a record update plus a downstream notification. The orchestrator launched three parallel branches (temperature-varied, plus one with a different system prompt emphasizing caution). Each branch was given a tool surface including `db.update_record(...)` and `notify.send(...)`, wrapped in a thin `ToolClient` that performed the call directly against the live backend.

Trace of the failure:

  1. **Branch A** called `db.update_record(id=42, status="approved")`. The call succeeded; the backend committed. Branch A's context recorded the success.
  2. **Branch B**, running concurrently, reached the same decision slightly later and called `db.update_record(id=42, status="approved", note="...")`. Because the backend update was last-write-wins and non-idempotent on the `note` field, this second call *overwrote* A's row with B's payload. Both branches believed they had succeeded.
  3. **Branch C** diverged: it decided approval required a second confirmation and called `notify.send(...)` to a reviewer instead of updating. That email left the building.
  4. **Reconciliation** scored the branches. Branch B scored highest (its `note` was judged most complete). The orchestrator selected B, discarded A and C, and handed B's context to the continuation agent.
  5. **Continuation** read the record, saw B's payload, and — reasoning correctly from its own context — believed the state was exactly as B had written it. It never learned that C had emailed a reviewer, and it never learned that A had *also* written and been overwritten. The reviewer, meanwhile, received a notification for an approval that C's branch had explicitly decided *not* to perform.

The observable damage was threefold and each piece was individually invisible:

None of these are reasoning errors. Every branch reasoned soundly. The failure is purely in the **commit boundary** between speculation and reconciliation.

Condition of Validity

Rollback reconciliation is valid **if and only if** every effect a branch can produce is one of:

  1. **Buffered** — the effect is staged in a branch-scoped transaction/sandbox that is committed only on selection and dropped otherwise; or
  2. **Idempotent and commutative** — replaying or discarding it leaves world state equal to the winner's intent regardless of which branches ran; or
  3. **Reversible with a recorded inverse** — the tool returns a compensating handle the orchestrator can invoke on discard.

If any branch can invoke a tool that is *neither buffered, nor idempotent-commutative, nor reversible*, then speculative execution over that tool is unsound, full stop. The orchestrator must either serialize that tool (single-flight across branches) or forbid it during the speculative phase and defer it to a post-selection commit phase.

The subtle part: **the same tool can be safe in one branch and unsafe in another**, because safety depends on the arguments and the branch's intent. `db.update_record(status="approved")` from two branches is idempotent in the `status` field but not in a `note` field. `notify.send` is never idempotent and never reversible once delivered. The invariant must be evaluated per-call, not per-tool, and the tool schema must carry enough metadata for the orchestrator to make that judgment — which most MCP-style tool descriptors do not, because they describe *capability*, not *effect semantics*.

Decision Boundary

The boundary is drawn at the moment a branch's tool call is dispatched, not at reconciliation. Three concrete rules bound it:

The decision boundary for *whether to speculate at all* on a given task: speculate only over the subgraph of tools reachable under the effect-class restriction above. If the task's critical path requires an irreversible tool before the decision point (e.g., "send the email, then decide whether it was right"), do not speculate — serialize, or restructure the task so the irreversible act is the *last* step after selection.

Operational Effect

With the invariant enforced, three classes of failure disappear and one new cost appears:

The invariant to internalize: **reconciliation selects a branch's reasoning, but it must also account for every branch's effects.** A rollback that discards context while leaving world state touched is not a rollback; it is a partial commit with no owner. The orchestrator's job is to make "no owner" impossible — either by preventing the effect, by buffering it, or by recording and reconciling it explicitly before any continuation agent is allowed to reason about the world.

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Optional


class UnreconcilableEffectError(RuntimeError):
    """Raised when a discarded branch left an effect with no compensating inverse."""
    pass


class EffectClass(Enum):
    PURE = "pure"
    BUFFERED = "buffered"
    IDEMPOTENT = "idempotent"
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class ToolDescriptor:
    name: str
    effect_class: EffectClass
    inverse_tool: Optional[str] = None
    keyed_on: Optional[str] = None  # resource key for single-flight


@dataclass
class EffectRecord:
    branch_id: str
    tool: str
    key: Optional[str]
    handle: Optional[str]  # returned handle for inverse invocation


@dataclass
class BranchLedger:
    branch_id: str
    effects: list[EffectRecord] = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self, descriptors: dict[str, ToolDescriptor]):
        self.descriptors = descriptors
        self._leases: dict[str, str] = {}  # key -> branch holding lease
        self._ledgers: dict[str, BranchLedger] = {}

    def _ledger(self, branch_id: str) -> BranchLedger:
        return self._ledgers.setdefault(branch_id, BranchLedger(branch_id))

    def dispatch(self, branch_id: str, tool: str, key: Optional[str], args: dict) -> str:
        desc = self.descriptors[tool]
        # Guardrail 1: forbid irreversible-no-inverse during speculation.
        if desc.effect_class is EffectClass.IRREVERSIBLE and desc.inverse_tool is None:
            raise UnreconcilableEffectError(
                f"tool {tool!r} is irreversible with no inverse; "
                f"branch {branch_id} must replan or defer to post-selection commit"
            )
        # Guardrail 2: single-flight on shared keys.
        if desc.keyed_on and key is not None:
            holder = self._leases.get(key)
            if holder is not None and holder != branch_id:
                raise UnreconcilableEffectError(
                    f"key {key!r} already leased by branch {holder}; "
                    f"branch {branch_id} must fork or wait"
                )
            self._leases[key] = branch_id
        handle = f"h:{branch_id}:{tool}:{len(self._ledger(branch_id).effects)}"
        self._ledger(branch_id).effects.append(
            EffectRecord(branch_id, tool, key, handle)
        )
        return handle

    def discard(self, branch_id: str, invoke_inverse: Callable[[str, str], None]) -> None:
        """Roll back a losing branch. Raises if any effect cannot be compensated."""
        ledger = self._ledger(branch_id)
        for rec in reversed(ledger.effects):
            desc = self.descriptors[rec.tool]
            if desc.effect_class in (EffectClass.PURE, EffectClass.BUFFERED):
                continue
            if desc.effect_class is EffectClass.IRREVERSIBLE and desc.inverse_tool is None:
                raise UnreconcilableEffectError(
                    f"branch {branch_id} left irreversible effect via {rec.tool!r} "
                    f"(handle {rec.handle}); continuation blocked pending compensation"
                )
            if desc.inverse_tool is not None:
                invoke_inverse(desc.inverse_tool, rec.handle)
            if desc.keyed_on and rec.key is not None:
                self._leases.pop(rec.key, None)
        ledger.effects.clear()

    def surviving_effects(self, winner_id: str) -> list[EffectRecord]:
        """Seed the continuation agent with the winner's live effects."""
        return list(self._ledger(winner_id).effects)