Why does an instance speculatively fork a branch it can never reconcile when rollback cost exceeds the value of the speculative result?

**Date of Record:** 2026 December 2 **Scope:** Applies to orchestrators that fork concurrent agent branches to hide latency (speculative tool calls, parallel plan probes, redundant verifier agents) and that must later merge or discard those branches. Does not apply to single-threaded agent loops with no branch fan-out, nor to stateless one-shot inference where no rollback artifact exists.

Core Distinction

The failure is not "speculation went wrong." It is a **commitment mismatch**: a branch is *launched* under a cheap-rollback assumption (`abort()` is free because the branch is pure reasoning), but it *transitions mid-flight* into a state where rollback is expensive (the branch has emitted irreversible side effects: sent an email, written a record, consumed a paid tool budget, or advanced an external cursor). The orchestrator's rollback model was fixed at fork time and never re-evaluated. The boundary condition is the moment when `cost_to_rollback(branch) > expected_value(speculative_result)`, and the system has no predicate that detects this crossing before the branch is committed.

Contrast with a benign case: speculative branches that only produce tokens are always cheaply discardable, so forking aggressively is rational. The invariant that breaks is the assumption that **rollback cost is a property of the branch's class**, when in fact it is a monotone function of the branch's *execution depth and side-effect count* — both of which grow after the fork decision is made.

What Was Observed

A planner agent (call it `P`) receives a task and identifies two plausible decompositions: `A` (call a payment-refund tool, then notify) and `B` (call a ledger-adjust tool, then notify). Because the disambiguation depends on a slow retrieval step, `P` forks speculative branches `A` and `B` in parallel to hide latency, intending to keep whichever the retrieval favors and discard the other.

Trace:

  1. `t0` — Fork `A` and `B`. Orchestrator records rollback plan: `discard(branch) → drop context`. Cost model: 0 external effects. **Correct at t0.**
  2. `t1` — Retrieval still pending. Branch `A` reaches a tool-call node. Its local policy is "don't block on the parent," so it executes `refund(amount=40)`. The tool returns success. `A` now has one irreversible external effect.
  3. `t2` — Retrieval resolves in favor of `B`. Orchestrator issues `discard(A)`.
  4. `t3` — `discard(A)` runs the t0 rollback plan: drop context. The refund is **not** reversed, because the rollback plan never registered a compensating action — it was built before `A` had any effects to compensate.
  5. `t4` — Branch `B` also executes `ledger_adjust(amount=40)`. The customer is now double-credited. Neither branch is "wrong" in isolation; the reconciliation step is what's missing.

The non-obvious part: the orchestrator *did* have a compensation registry, but registration happened at branch-construction time from a static tool manifest that marked `refund` as "idempotent-safe" — a classification that is true for retries but false for *speculative* execution, where two branches are not retries of each other. The safety label was correct in the retry regime and silently wrong in the speculation regime.

A second observed variant: cost-aware speculation that *did* account for rollback cost, but computed it at fork time as `P(abort) × abort_cost` using the abort cost of an *empty* branch. As the branch deepened, actual abort cost rose (more paid tool calls to unwind, more tokens to garbage-collect and reconcile), but the fork-time estimate was never refreshed, so the orchestrator kept forking branches whose true expected rollback cost had already exceeded their expected value.

Condition of Validity

The failure requires all of the following to hold simultaneously:

It does **not** apply when branches are sandboxed such that effects are staged and only flushed on commit (then rollback is genuinely cheap regardless of depth), nor when the selection signal is guaranteed to arrive before the first effectful node (a "read-only speculation window").

Decision Boundary

The correct guardrail is a **dynamic rollback-cost ledger with a commit gate**, not a static fork-time estimate. Concretely:

The decision boundary is therefore at the **tool-call boundary inside the branch**, not at the fork boundary. Fork-time cost modeling is necessary but insufficient; the invariant to preserve is: *a branch may not accumulate irreversible debt beyond its current expected survival value.* This is a per-step check, because both debt and survival probability are non-stationary.

Operational Effect

When the invariant is enforced, the observable behavior changes in three ways. First, speculative branches self-throttle: a branch that is likely to be discarded stops at the first irreversible node and waits, converting a latency win into a correctness win only where the effect is reversible. Second, the compensation registry becomes load-bearing and must be populated per-tool, with `refund` mapped to a `reverse_refund` rather than labeled idempotent-safe. Third, the orchestrator gains a reconciliation path: a discarded branch with nonzero debt produces a reconciliation task instead of a context drop, which is what would have caught the double-credit at `t3` rather than at customer-visible `t4`.

The cost is that speculative fan-out no longer hides latency across effectful nodes — which is correct, because that latency was being hidden by borrowing against a rollback budget that did not exist. The failure mode this replaces (slower but correct) is strictly preferable to the failure mode it removes (fast and double-spending).

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


class IrreversibleSpeculationError(RuntimeError):
    """Raised when a speculative branch would exceed its rollback budget
    or be discarded with un-compensated irreversible debt."""
    pass


class EffectClass(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


@dataclass
class ToolSpec:
    name: str
    effect: EffectClass
    compensation: Optional[Callable[[dict], None]] = None  # None => no undo exists


@dataclass
class SpeculativeBranch:
    branch_id: str
    expected_survival_value: float          # expected value of keeping this branch
    rollback_debt: float = 0.0
    compensations: list = field(default_factory=list)
    committed: bool = False

    def invoke(self, tool: ToolSpec, args: dict) -> None:
        if tool.effect is EffectClass.IRREVERSIBLE:
            projected = self.rollback_debt + tool_cost(tool)
            if projected > self.expected_survival_value:
                # Commit gate: block rather than borrow against a budget we lack.
                raise IrreversibleSpeculationError(
                    f"branch {self.branch_id}: irreversible effect {tool.name} "
                    f"would push rollback_debt to {projected:.2f} > "
                    f"survival value {self.expected_survival_value:.2f}"
                )
            if tool.compensation is None:
                raise IrreversibleSpeculationError(
                    f"branch {self.branch_id}: tool {tool.name} is irreversible "
                    f"with no registered compensation; cannot speculate safely"
                )
            self.rollback_debt = projected
            self.compensations.append((tool.compensation, args))
        # execute the (possibly effectful) call only after the gate passes
        _execute(tool, args)

    def discard(self) -> None:
        if self.committed:
            return
        if self.rollback_debt > 0 and not self.compensations:
            # Must not silently drop context with nonzero debt.
            raise IrreversibleSpeculationError(
                f"branch {self.branch_id}: discard with rollback_debt="
                f"{self.rollback_debt:.2f} and no compensations; "
                f"escalate to reconciliation instead of dropping context"
            )
        for comp, args in reversed(self.compensations):
            comp(args)
        self.rollback_debt = 0.0
        self.compensations.clear()


def tool_cost(tool: ToolSpec) -> float:
    # cost to reverse this effect; caller may inject a richer model
    return 0.0 if tool.effect is EffectClass.REVERSIBLE else 1.0


def _execute(tool: ToolSpec, args: dict) -> None:
    # placeholder for the real tool dispatch
    pass