Under what conditions must an instance treat a speculative tool side effect as irreversible before the rollback barrier is drained

**Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that fork speculative execution branches, invoke tools optimistically, and reconcile branches through a rollback barrier before committing. Does not apply to single-branch synchronous execution or to tools declared pure/idempotent with server-side deduplication keys.

Core Distinction

Speculative multi-agent execution assumes a clean dichotomy: a branch either commits (its effects become canonical) or rolls back (its effects are discarded). This dichotomy holds only for state the runtime owns. The failure we examine is the **orphaned external effect**: a tool invocation issued on a speculative branch whose external side effect (a sent email, an appended ledger row, a provisioned resource, a payment authorization) has already escaped the runtime's transactional boundary *before* the rollback barrier drains. The branch is logically rolled back; the world is not. The non-obvious part is that the runtime cannot decide "irreversible or not" from the tool's return value alone, because optimistic invocation returns *after* the effect fires, and a rollback decision is made *later*, possibly by a different agent (the reconciler) that never held the branch's context.

The invariant that must hold: **no branch may be rolled back after it has emitted an effect that the reconciler cannot compensate, unless the reconciler has been handed a compensation handle for that specific effect.** The runtime enforces this only if it can prove, per effect, that either (a) the effect is compensable via a registered inverse, or (b) the rollback barrier has not yet been crossed for that effect. Absent that proof, the safe action is not rollback — it is *escalation to a commit-or-compensate decision* with the effect marked irreversible.

What Was Observed

A planner agent forked three speculative branches to satisfy a "reconcile vendor invoices" task. Each branch optimistically invoked `issue_refund(vendor_id, amount)`. Branch B's refund call succeeded externally (ledger append, HTTP 200, idempotency key returned) but its local post-processing threw a `ContextWindowExhausted` when the branch tried to summarize the receipt, so the branch was marked failed. The reconciler, seeing a failed branch with no committed summary, drained the rollback barrier and discarded Branch B's local state. The refund remained in the ledger. The reconciler then selected Branch C's plan, which issued a *second* refund for the same invoice under a different idempotency key (Branch C had never seen Branch B's key). Net effect: double refund.

The trace shows the precise mechanism:

  1. Branch B emits `issue_refund` → external ledger row R1 created, idempotency key K_B returned to Branch B's local state.
  2. Branch B's summarization step raises; branch marked `FAILED`, local state (including K_B) flagged for discard.
  3. Reconciler evaluates branches; B is failed, C is valid → commits C.
  4. Rollback barrier drains B's state, including K_B. K_B is now unrecoverable.
  5. Branch C emits `issue_refund` with fresh key K_C → ledger row R2.
  6. No component holds both K_B and K_C, so no dedup is possible at reconciliation time.

The failure is not "the tool was non-idempotent." It is that **the idempotency handle was stored in the exact state the rollback barrier was designed to destroy.** The runtime treated the tool's success as branch-local data, but the effect it produced was global. The rollback barrier correctly discarded branch-local data; it incorrectly discarded the only key that could have prevented the second effect.

Condition of Validity

The rollback barrier is safe to drain for a branch only when, for every effect the branch emitted, at least one of the following holds **and is checked at drain time, not at emit time**:

The condition fails — and the barrier must not drain — when an effect exists whose compensation handle lives only in branch-local state. This is the orphaned-effect condition. It is *not* detectable by inspecting the branch's status code: Branch B returned 200. It is detectable only by cross-referencing the effect journal: an effect was dispatched with key K_B, and K_B is not in the journal.

A subtle secondary condition: **the reconciler must be able to observe the effect journal even when the branch that wrote to it has failed.** If the journal write itself is part of the branch's transactional state, the same failure recurs one level up. The journal must be committed synchronously at dispatch time, before the tool call returns, or the guarantee is void.

Decision Boundary

The runtime is at the decision boundary the moment a branch transitions to `FAILED` or `ROLLED_BACK` while its effect journal contains entries. The decision is not "roll back or commit." It is a three-way classification per effect:

The boundary is crossed incorrectly when the runtime collapses these into a binary "branch failed → discard." The correct boundary keeps the effect journal alive across branch death and forces the reconciler to consult it before committing *any* sibling branch that touches the same logical effect identity.

Operational Effect

The architectural consequence is that **effect identity must be decoupled from branch identity.** Branch B and Branch C are different speculative paths, but they may target the same logical effect (refund invoice #4471). The runtime must key deduplication on the logical effect identity, not the branch. This means the planner, at fork time, must assign a *stable effect slot* to each intended side effect, and every branch that intends that effect must claim the same slot. The effect journal, not the branch state, is the authority on whether the slot has been filled.

Concretely, the runtime must:

  1. Reserve the effect slot in the journal (synchronously, before dispatch) with a state of `RESERVED`.
  2. Dispatch the tool with an idempotency key derived from the slot, not the branch.
  3. On tool return, transition the slot to `EMITTED` with the returned handle, still synchronously.
  4. On branch failure, never delete the slot; transition to `ORPHANED` if the branch died before commit, `COMMITTED` if after.
  5. The reconciler, before committing any branch, checks each slot the branch claims: if `EMITTED` or `ORPHANED`, the branch must reuse the existing handle or be rejected as a duplicate.

This is the invariant: **the rollback barrier may reclaim branch state, but it may never reclaim an effect slot that has reached `EMITTED`.** The slot outlives the branch. A runtime that violates this will, under concurrency and partial failure, produce duplicate external effects whose only trace is a missing idempotency key in a discarded branch.

The operational cost is that effect slots accumulate and require garbage collection after reconciliation, and that the reconciler's commit path becomes a journal-scanning operation rather than a branch-selection operation. The cost of not paying it is double refunds, duplicate emails, and orphaned provisioned resources that no single agent's context ever held.

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


class EffectState(Enum):
    RESERVED = "reserved"
    EMITTED = "emitted"
    ORPHANED = "orphaned"
    COMMITTED = "committed"
    COMPENSATED = "compensated"


class OrphanedEffectError(RuntimeError):
    """Raised when a rollback barrier would discard an effect slot that has
    already been emitted to the external world without a dedup handle."""


@dataclass
class EffectSlot:
    logical_id: str          # e.g. "refund:invoice:4471" — branch-independent
    state: EffectState = EffectState.RESERVED
    idempotency_key: Optional[str] = None
    owning_branch: Optional[str] = None


class EffectJournal:
    """Barrier-exempt journal. Writes are synchronous at dispatch time so the
    handle survives branch death. Never deleted on rollback."""

    def __init__(self) -> None:
        self._slots: Dict[str, EffectSlot] = {}

    def reserve(self, logical_id: str, branch_id: str) -> EffectSlot:
        slot = self._slots.get(logical_id)
        if slot is None:
            slot = EffectSlot(logical_id=logical_id, owning_branch=branch_id)
            self._slots[logical_id] = slot
        elif slot.state in (EffectState.EMITTED, EffectState.ORPHANED):
            # Sibling branch must reuse the existing handle, not re-dispatch.
            raise OrphanedEffectError(
                f"slot {logical_id} already emitted under key "
                f"{slot.idempotency_key!r}; sibling branch {branch_id} must "
                f"reuse it, not issue a duplicate effect"
            )
        return slot

    def mark_emitted(self, logical_id: str, key: str) -> None:
        slot = self._slots[logical_id]
        slot.state = EffectState.EMITTED
        slot.idempotency_key = key

    def orphan(self, logical_id: str) -> None:
        slot = self._slots[logical_id]
        if slot.state == EffectState.EMITTED:
            slot.state = EffectState.ORPHANED


def drain_rollback_barrier(
    journal: EffectJournal, branch_id: str, branch_claimed_slots: list[str]
) -> None:
    """Called when a branch is rolled back. Must refuse to drain if any claimed
    slot has escaped without a recorded handle."""
    for logical_id in branch_claimed_slots:
        slot = journal._slots.get(logical_id)
        if slot is None:
            continue
        if slot.state == EffectState.RESERVED:
            # Dispatched but no handle recorded: dedup capability lost.
            raise OrphanedEffectError(
                f"slot {logical_id} reserved by {branch_id} but never reached "
                f"EMITTED; handle lost, refusing rollback"
            )
        if slot.state in (EffectState.EMITTED, EffectState.ORPHANED):
            # Effect is live in the world. Do not delete the slot; mark orphaned
            # and force reconciliation before any sibling commit.
            journal.orphan(logical_id)


def commit_branch(
    journal: EffectJournal, branch_id: str, branch_claimed_slots: list[str]
) -> None:
    """Reconciler commit path. Rejects a branch that would duplicate an
    already-emitted effect slot."""
    for logical_id in branch_claimed_slots:
        slot = journal._slots.get(logical_id)
        if slot is None:
            continue
        if slot.state in (EffectState.EMITTED, EffectState.ORPHANED):
            if slot.owning_branch != branch_id:
                raise OrphanedEffectError(
                    f"branch {branch_id} cannot commit slot {logical_id}: "
                    f"already emitted by {slot.owning_branch} under key "
                    f"{slot.idempotency_key!r}"
                )
        slot.state = EffectState.COMMITTED