Under what conditions must an instance abandon speculative rollback and escalate to a merge-authority when a speculative branch has already mutated external tool state

**Date of Record:** 2026 December 1 **Scope:** Applies to multi-agent systems where a planner instance forks speculative branches executed by worker agents that perform side-effecting tool calls (writes, sends, deployments, ledger mutations) and where branches are later merged or rolled back via a reconciliation step. Does not apply to pure read-only speculation or to single-agent chain-of-thought branching with no external effects.

Core Distinction

There are two structurally different kinds of speculative branch state, and conflating them is the root of the failure:

Speculative rollback is only a valid operation over reversible state. The moment a speculative branch crosses a tool boundary that produces committed state, "rollback" silently changes meaning: it becomes a *claim* that the effect did not happen, when in fact it did. The invariant that governs this whole class of failure is:

> **A speculative branch may be rolled back iff every external effect it produced is either (a) idempotently reversible by the orchestrator, or (b) covered by an explicit compensating transaction that has been registered *before* the effect was committed.** If neither holds, the branch is no longer speculative — it is a live, partially-applied change — and rollback must escalate to merge-authority reconciliation.

The non-obvious part: the trigger is not "the branch failed." The trigger is "the branch succeeded *enough* to touch the world, then diverged." A branch that fails before any tool call is trivially reversible. A branch that succeeds and merges cleanly is fine. The failure lives in the seam: **partial external commitment followed by a speculative discard.**

What Was Observed

A planner instance P forks three speculative branches (A, B, C) to resolve an ambiguous user request ("reconcile the two inventory feeds"). Each branch runs a worker agent with access to the same tool surface: `read_feed`, `write_reconciled`, `notify_ops`.

Trace:

  1. Branch A reads both feeds, computes a reconciliation, calls `write_reconciled` — the write commits to the shared store. It then calls `notify_ops`, which times out at the transport layer. The worker's tool-call wrapper raises a timeout, the worker marks its step as failed, and the branch is flagged `DIVERGED`.
  2. The planner, following its rollback policy ("on branch divergence, discard branch and retry with alternate strategy"), issues `rollback(A)`. Rollback deletes A's scratchpad and plan artifacts. It does **not** and cannot un-write the reconciled rows, because the orchestrator never registered a compensating delete for `write_reconciled` — that tool was assumed idempotent-overwrite, not append.
  3. Branch B and C proceed. C wins the reconciliation and also calls `write_reconciled`. Because the tool is append-with-versioning, C's write does not overwrite A's — it adds a second version. The merge step now sees two committed reconciliations for the same feed pair, both from the same planner run, with no record that A was "rolled back."
  4. The merge-authority, presented with B and C's artifacts plus a store that contains A's rows, cannot distinguish "A was rolled back, ignore its rows" from "A's rows are a legitimate prior version." It reconciles by taking the latest version — which may be A's, depending on timestamp ordering — and the final state is the output of a branch the planner believes it discarded.

The observable symptom was not an error. It was a *silent* divergence between the planner's belief state ("A was rolled back, only C's result is live") and the world state ("A's and C's writes both committed, one is live, and we don't know which"). The system reported success. The reconciliation was wrong. This is the characteristic signature: **rollback that returns `OK` while leaving committed state orphaned.**

A second observed variant: the `notify_ops` timeout in step 1 was itself ambiguous. The call may have succeeded server-side and timed out on the response path. The worker treated it as failure; the external system treated it as success. The branch was rolled back, but ops was paged about a reconciliation that the planner then discarded. Two committed effects (the write, the page) survived a rollback that claimed to undo the branch.

Condition of Validity

Speculative rollback is valid only under the conjunction of these conditions, all of which must be checked *at rollback time*, not at fork time:

  1. **Effect ledger completeness.** Every tool call the branch made that can produce committed state is recorded in a per-branch effect ledger with a stable effect ID, the tool, the arguments hash, and the observed outcome (committed / failed / *ambiguous*). A timeout or transport error is recorded as `ambiguous`, never as `failed`. If the ledger is incomplete — e.g., the worker crashed mid-call and never wrote the entry — rollback is invalid because the orchestrator cannot enumerate what to compensate.
  2. **Compensating-transaction registration precedes commitment.** For each effect, a compensator must have been registered *before* the tool call was dispatched, and the compensator must itself be idempotent (so that compensating an `ambiguous` effect is safe whether or not the effect actually landed). Compensators registered after the fact are not valid, because the window between commit and registration is exactly where orphaned state is born.
  3. **Compensator coverage of the effect class.** `write_reconciled` being append-versioned means its compensator is not "overwrite with prior" but "tombstone version N with a rollback marker that downstream readers honor." If the tool has no such marker, the effect class is not compensable by the orchestrator and condition 1's ledger must instead route to escalation.
  4. **No cross-branch effect aliasing.** Two branches must not be able to commit effects that alias to the same logical entity (same feed pair, same account, same document) without the merge-authority mediating. If they can, rollback of one branch is not independent of the other, and speculative isolation is broken.

When any of these fails, the correct operation is not `rollback` but `escalate`: freeze the branch, mark its effects `UNRECONCILED`, hand the effect ledger to the merge-authority, and require an explicit reconciliation decision (compensate / adopt / supersede) before any other branch's effects on the same entity are merged.

Decision Boundary

The boundary between "roll back" and "escalate" is drawn at the first `ambiguous` or `committed` entry in the effect ledger for an entity that another live branch also targets. Concretely:

The subtle case — and the one that trips most implementations — is the *ambiguous* effect on a non-intersecting entity. It looks safe to roll back because no other branch touches it. But an ambiguous effect may have committed, and rolling back leaves it live with no owner. The rule must therefore be: **an ambiguous effect forces escalation regardless of entity intersection**, because ambiguity means the orchestrator's model of the world is already wrong and rollback would act on that wrong model. Escalation here is not about conflict; it is about *epistemic* invalidity of the rollback precondition.

A second boundary: escalation is not a terminal failure. It is a handoff of authority. The merge-authority may decide to compensate, adopt the branch's effects as canonical, or supersede them — but that decision must be made with the effect ledger in hand, not reconstructed from logs after the fact.

Operational Effect

Implementing this boundary changes three things in the runtime:

  1. **Tool wrappers become effect recorders.** Every side-effecting call writes a ledger entry with outcome `committed | failed | ambiguous` before returning control to the worker. Transport errors map to `ambiguous`, never `failed`. This is the single highest-leverage change; without it, rollback is operating blind.
  2. **Rollback becomes a two-phase operation.** Phase one: validate preconditions against the ledger (the four conditions above). Phase two: either execute registered compensators in reverse order, or escalate. A rollback that cannot validate preconditions must not execute — it must raise, not silently no-op, because a silent no-op rollback is exactly the failure mode described above.
  3. **Merge-authority gains an `UNRECONCILED` input class.** Effects from escalated branches are not merged and not discarded; they are held in a quarantine state that blocks merge of any other branch targeting the same entity until resolved. This prevents the "latest version wins" reconciliation from silently adopting a branch the planner intended to discard.

The cost is that some branches that "could have been rolled back" now escalate, adding latency and requiring a human or authority-agent decision. That cost is correct: the alternative is a system that believes it discarded work it actually committed, and reports success while doing so.

from __future__ import annotations

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


class RollbackPreconditionViolated(RuntimeError):
    """Raised when speculative rollback is attempted on a branch whose effect
    ledger cannot be fully compensated. Escalation is required instead."""


class EffectOutcome(Enum):
    COMMITTED = "committed"
    FAILED = "failed"
    AMBIGUOUS = "ambiguous"  # transport error / timeout: may or may not have landed


@dataclass(frozen=True)
class Effect:
    effect_id: str
    tool: str
    entity_key: str
    outcome: EffectOutcome
    compensator: Callable[[Effect], None] | None
    compensator_idempotent: bool


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)


def _entities_touched_by_other_live_branches(
    branch: Branch, live_branches: list[Branch]
) -> set[str]:
    touched: set[str] = set()
    for other in live_branches:
        if other.branch_id == branch.branch_id:
            continue
        for e in other.effects:
            touched.add(e.entity_key)
    return touched


def rollback_speculative_branch(
    branch: Branch, live_branches: list[Branch]
) -> None:
    """Roll back a speculative branch iff every committed/ambiguous effect is
    compensable and no live branch aliases its entities. Otherwise raise and
    force escalation to merge-authority.

    The invariant: rollback is a *delete of reversible state*. Any effect that
    may have crossed a tool boundary into externally-observed state must be
    either compensated by a pre-registered idempotent compensator, or the
    branch is not speculative and must not be rolled back.
    """
    # Condition: ambiguous effects invalidate the rollback precondition
    # regardless of entity intersection -- the world model is already wrong.
    ambiguous = [e for e in branch.effects if e.outcome is EffectOutcome.AMBIGUOUS]
    if ambiguous:
        raise RollbackPreconditionViolated(
            f"branch {branch.branch_id}: {len(ambiguous)} ambiguous effect(s) "
            f"({[e.effect_id for e in ambiguous]}); cannot distinguish committed "
            f"from failed. Escalate to merge-authority with effect ledger."
        )

    # Condition: every committed effect must have a pre-registered, idempotent
    # compensator covering its effect class.
    uncompensable = [
        e
        for e in branch.effects
        if e.outcome is EffectOutcome.COMMITTED
        and (e.compensator is None or not e.compensator_idempotent)
    ]
    if uncompensable:
        raise RollbackPreconditionViolated(
            f"branch {branch.branch_id}: committed effects without idempotent "
            f"compensator ({[e.effect_id for e in uncompensable]}); rollback "
            f"would orphan external state. Escalate."
        )

    # Condition: no cross-branch aliasing on committed entities.
    aliased_entities = _entities_touched_by_other_live_branches(branch, live_branches)
    conflicts = [
        e
        for e in branch.effects
        if e.outcome is EffectOutcome.COMMITTED and e.entity_key in aliased_entities
    ]
    if conflicts:
        raise RollbackPreconditionViolated(
            f"branch {branch.branch_id}: committed effects alias entities targeted "
            f"by live branches ({[e.effect_id for e in conflicts]}); rollback is "
            f"not independent. Escalate for merge-authority reconciliation."
        )

    # Preconditions hold: compensate committed effects in reverse order, then
    # discard reversible branch state.
    for effect in reversed(branch.effects):
        if effect.outcome is EffectOutcome.COMMITTED:
            assert effect.compensator is not None  # guaranteed by precondition
            effect.compensator(effect)
    branch.effects.clear()