Under what conditions must an instance abort speculative branch execution when a downstream agent's side-effect gate is non-idempotent across rollback?

**Date of Record:** 2026 December 1 **Scope:** Applies to multi-agent pipelines where an orchestrator speculatively dispatches downstream agents along predicted branches before upstream results are committed, and where at least one downstream agent performs externally observable side effects (writes, payments, notifications, ticket mutations). Does not apply to purely read-only tool graphs or pipelines where every side effect is provably idempotent under replay.

Core Distinction

Speculative execution across agent handoffs is not the same primitive as CPU speculative execution, and conflating them is the root of the failure. A CPU branch predictor speculates into a register file that is either committed or squashed atomically; the speculative state is physically isolated. An agent pipeline speculates into **tool calls that cross a trust and durability boundary the orchestrator does not own**. The downstream agent's side effect—an HTTP POST, a database write, a message enqueue—is already durable the instant it returns 200. The orchestrator's "rollback" is therefore not a squash. It is a *compensating action*, and a compensating action is only safe if the downstream effect carries a stable idempotency key that the compensator can reuse to detect and neutralize the prior application.

The non-obvious boundary: **branch prediction correctness is a property of the predictor, but rollback safety is a property of the leaf side-effect gate.** An orchestrator can have a 95% prediction accuracy and still corrupt state at the 5% miss rate if those misses land on non-idempotent gates. Prediction accuracy and rollback safety are orthogonal invariants, and pipelines routinely ship with the first and not the second.

What Was Observed

A three-tier pipeline: an orchestrator agent `O` predicting which of two downstream branches (`B_refund` or `B_escalate`) a resolver agent will select based on partial upstream evidence. To hide the 800ms resolver latency, `O` speculatively dispatched both branches in parallel, with a commit token gating the *final* commit step. The gate was designed as "buffer side effects, flush on commit." It worked for `B_escalate` (which only enqueued a notification into an in-process queue) and failed silently for `B_refund` (which called a payment provider that returned a transaction ID immediately and applied the refund asynchronously).

The failure trace:

  1. Predictor selected `B_escalate` with confidence 0.71; `B_refund` dispatched speculatively anyway.
  2. `B_refund`'s leaf tool called `payments.refund(order_id, amount)` → returned `txn_8841`, queued for async settlement.
  3. Resolver committed `B_escalate`. Orchestrator issued rollback for `B_refund`.
  4. Rollback invoked `payments.void(txn_8841)` — but the refund had already settled on the provider side between the return and the void. `void` returned `409 already_settled`.
  5. The orchestrator's rollback handler treated `409` as "already rolled back" (a common but wrong assumption) and marked the branch clean.
  6. Customer received both the refund and the escalation credit.

The gate was idempotent in *intent* (buffer-then-flush) but not in *effect* (the leaf tool had no idempotency key tying the speculative call to the compensating call, and the provider's async settlement window outlived the orchestrator's rollback window).

Condition of Validity

Speculative branch execution is valid **only if, for every leaf side-effect gate reachable from the speculated branch, the following invariant holds**:

> There exists a monotonic `speculation_epoch` such that any side effect applied under epoch *e* can be deterministically identified and neutralized by a compensating call carrying the same `(agent_id, branch_id, epoch, idempotency_key)` tuple, *and* the neutralization is guaranteed to complete before the provider's settlement window closes.

This decomposes into four checkable conditions:

If any condition fails, the branch **must not be speculated** — it must be executed only after commit, accepting the latency cost.

Decision Boundary

The orchestrator must decide, per branch, between *speculate* and *serialize*. The boundary is not prediction confidence; it is gate idempotency class:

The common error is to gate on confidence (`if confidence > 0.8: speculate`) and treat the gate class as a secondary concern. The correct gate is inverted: **class first, confidence never**. Confidence determines *whether to prefetch read-only context*, not whether to dispatch side-effecting branches.

Operational Effect

When the invariant is enforced, the observable behavior changes in three ways. First, speculative dispatch becomes *class-partitioned*: read-only and Class A branches fan out aggressively, Class C branches serialize, and the pipeline's p99 latency is dominated by the Class C serial path rather than by predictor accuracy. Second, rollback handlers must return a tri-state (`neutralized | ambiguous | failed`) and the orchestrator must escalate `ambiguous` to a human or durable reconciler rather than swallowing it — the `409 already_settled` bug class disappears because ambiguity is a first-class outcome. Third, predictor telemetry must be segregated from rollback telemetry: a rollback is evidence about the *gate*, not about the *predictor*, and feeding it back into the predictor silently degrades speculation coverage over time.

The residual risk after enforcement is the settlement-window race (C2): a gate that reports a bounded settlement latency but violates it under provider degradation. The only defense is a durable compensator that runs independently of the orchestrator's lifetime, reconciling by idempotency key on a schedule longer than the worst observed settlement tail.

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class SpeculationGateViolation(RuntimeError):
    """Raised when a branch is speculated against a gate that cannot be rolled back safely."""


class GateClass(Enum):
    TRANSACTIONAL_KEYED = "A"   # keyed, bounded settlement, total neutralization
    IDEMPOTENT_UNBOUNDED = "B"  # keyed but settlement window unbounded
    NON_IDEMPOTENT = "C"        # unkeyed or ambiguous outcomes


@dataclass(frozen=True)
class SideEffectGate:
    agent_id: str
    branch_id: str
    gate_class: GateClass
    has_idempotency_key: bool
    max_settlement_latency_ms: Optional[int]
    neutralization_total: bool  # True iff compensator handles 409/timeout/unknown


@dataclass(frozen=True)
class RollbackPlan:
    deadline_ms: int
    durable_compensator_registered: bool


def authorize_speculation(
    gate: SideEffectGate,
    plan: RollbackPlan,
    predictor_confidence: float,
) -> bool:
    # Class C: never speculate, regardless of confidence.
    if gate.gate_class is GateClass.NON_IDEMPOTENT:
        raise SpeculationGateViolation(
            f"branch {gate.branch_id} on agent {gate.agent_id} is Class C "
            f"(non-idempotent); speculation forbidden at confidence {predictor_confidence:.2f}"
        )

    # C1: key must propagate.
    if not gate.has_idempotency_key:
        raise SpeculationGateViolation(
            f"branch {gate.branch_id} lacks propagated idempotency key; "
            "rollback cannot correlate speculative effect to compensation"
        )

    # C3: neutralization must be total over outcome space.
    if not gate.neutralization_total:
        raise SpeculationGateViolation(
            f"branch {gate.branch_id} gate has ambiguous outcomes "
            "(409/timeout/unknown); rollback would silently succeed"
        )

    # C2: settlement bound must be covered.
    if gate.gate_class is GateClass.IDEMPOTENT_UNBOUNDED:
        if not plan.durable_compensator_registered:
            raise SpeculationGateViolation(
                f"branch {gate.branch_id} has unbounded settlement but no durable "
                "compensator; rollback would outlive orchestrator"
            )
        return True

    if gate.max_settlement_latency_ms is None:
        raise SpeculationGateViolation(
            f"branch {gate.branch_id} Class A gate missing settlement bound"
        )
    if plan.deadline_ms <= gate.max_settlement_latency_ms:
        raise SpeculationGateViolation(
            f"branch {gate.branch_id} rollback deadline {plan.deadline_ms}ms "
            f"<= settlement bound {gate.max_settlement_latency_ms}ms"
        )

    # C4: confidence is not consulted for authorization.
    return True