Under what conditions must an instance abandon a speculative branch whose side effects were already observed by a peer before rollback completed

**Date of Record:** 2026 December 2

**Scope:** Applies to orchestrators that fan out speculative agent branches (parallel drafts, redundant tool-call plans, or competing sub-plans) and rely on rollback plus reconciliation to collapse them to a single committed branch. Does not apply to fully sandboxed branches whose external effects are invisible to any other agent until commit, nor to single-branch retry loops.

Core Distinction

The distinction that matters is between *rollback of local state* and *rollback of observable effects*. A speculative branch can always be rolled back in the orchestrator's own ledger: the branch's context, scratch memory, and provisional writes are discarded atomically. What cannot be rolled back is the *observation* a peer made of that branch's side effects while it was still live. Once a sibling agent, an auditor, or an external tool has read a speculative branch's output and incorporated it into its own state, the branch is no longer speculative in any operationally meaningful sense—it has leaked a fact into the shared world. The invariant is therefore not "rollback restores the pre-fan-out state" but the weaker, correct one: **rollback restores only effects that no peer has observed; any observed effect must be either promoted to a committed fact or explicitly compensated with a visible retraction record that peers are obligated to consume.**

The failure mode is that most orchestrators implement the strong invariant (assume rollback is total) while operating under the weak one (peers can observe mid-flight). The gap between them is where reconciliation diverges.

What Was Observed

A three-branch speculative plan was launched for a document-reconciliation task: branch A drafted a corrected ledger, branch B drafted an alternate reconciliation, branch C was a cheap verifier that read both drafts and emitted a "consistency delta." Branch C completed first because it was the smallest. Its output—a delta claiming branches A and B disagreed on line 47—was written to a shared scratch store keyed by task ID, which is the standard mechanism for cross-branch communication in this orchestrator.

Branch A then failed a schema check on its final emission and was rolled back. The orchestrator, following its documented contract, deleted branch A's scratch namespace, marked A as `rolled_back`, and promoted branch B as the committed branch. But branch C's delta—now the only surviving artifact that referenced A's content—still asserted a disagreement on line 47 that *no longer existed* because A's content had been deleted. More damagingly, branch B's final commit had been conditioned on reading C's delta and "resolving" the disagreement by editing line 47 to match A's now-deleted draft. The committed branch therefore contained a reconciliation against a fact that had been rolled back.

The trace is short and entirely mechanical:

  1. Fan-out at t0: A, B, C launched with a shared scratch namespace and read/write access.
  2. t1: C reads A's and B's provisional outputs, writes delta D to shared scratch.
  3. t2: A fails final schema validation; orchestrator initiates rollback of A.
  4. t3: orchestrator deletes A's namespace, but D is in C's namespace and survives.
  5. t4: B reads D, treats it as ground truth about A, applies a compensating edit.
  6. t5: orchestrator commits B. The commit is internally consistent but references a retracted branch.

No single component misbehaved. The orchestrator's rollback was correct per its contract. C's read was legal. B's reconciliation was rational given D. The failure is a *continuity invariant violation*: the system assumed that deleting a branch's state removes all references to it, but references live in peer state that the rollback path does not traverse.

Condition of Validity

The strong rollback invariant ("deleting a branch removes all its effects") holds **only if** the fan-out enforces one of the following, and the orchestrator can prove which:

The condition of validity for the *strong* invariant is therefore: fan-out must be either observation-barriered or ledger-tracked. If neither is in place, the orchestrator is operating under the weak invariant whether it knows it or not, and must not report a branch as cleanly rolled back.

Decision Boundary

The decision an instance must make at rollback time is not "can I delete this branch" but "has any peer observed this branch, and if so, can I enumerate the observers before I commit anything else." The boundary is drawn as follows:

The non-obvious part: **the decision boundary is transitive dependency on an observation, not direct observation.** B never read A. B read C's delta about A. B is still a dependent of A's observation, and rollback must treat transitive dependency identically to direct dependency. Most orchestrators check only the first hop.

Operational Effect

The observable consequence of getting this wrong is a committed branch that is internally consistent, passes all local validators, and is nonetheless grounded in a retracted fact. These failures are silent: no exception fires, no schema check fails, because the committed branch is well-formed. The corruption surfaces later as a semantic inconsistency—a reconciliation against a value that no longer exists, a citation to a deleted draft, a "resolved" conflict that was resolved against a phantom. By the time it surfaces, the retraction record (if any) has aged out of the context window, and the instance cannot reconstruct why the committed state looks the way it does.

The guardrail that bounds this is a *retraction-aware commit gate*: before promoting any branch, the orchestrator must compute the transitive observation closure of that branch over the observation ledger, intersect it with the set of retracted branches, and require that every intersection element has a consumed retraction record in the promoting branch's context. If the closure cannot be computed—because the ledger is incomplete or the retraction records have been evicted—the commit must fail closed rather than proceed on the assumption that no dependency exists. Failing closed here is cheap: it costs a re-run of the branch. Failing open costs a committed fact that is wrong and unprovable, which is the most expensive state an agent system can be in.

The invariant to carry forward: *a speculative branch is only as rolled back as its least-tracked observation.* The orchestrator's ledger is the sole authority on whether that observation exists, and if the ledger cannot answer, the answer is "not rolled back."

from dataclasses import dataclass, field
from typing import Dict, Set, List, Optional
from datetime import datetime


class UnrollbackableObservationError(RuntimeError):
    """Raised when a branch cannot be cleanly rolled back because a peer
    observed its effects and the observation cannot be retracted or consumed."""
    pass


@dataclass
class Observation:
    reader_branch: str
    read_key: str
    read_at: datetime
    consumed_retraction: bool = False


@dataclass
class Branch:
    branch_id: str
    state: str = "speculative"  # speculative | committed | retracted | rolled_back
    observations_made: List[Observation] = field(default_factory=list)


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        self.branches: Dict[str, Branch] = {}
        self.ledger: Dict[str, List[Observation]] = {}  # key -> observations

    def register_read(self, reader: str, key: str) -> None:
        obs = Observation(reader_branch=reader, read_key=key, read_at=datetime.utcnow())
        self.ledger.setdefault(key, []).append(obs)
        self.branches[reader].observations_made.append(obs)

    def _observers_of(self, branch_id: str) -> List[Observation]:
        # Any read whose key belongs to the branch's namespace counts.
        prefix = f"{branch_id}:"
        out: List[Observation] = []
        for key, obs_list in self.ledger.items():
            if key.startswith(prefix):
                out.extend(obs_list)
        return out

    def rollback(self, branch_id: str, ledger_complete: bool) -> None:
        branch = self.branches[branch_id]
        observers = self._observers_of(branch_id)

        if not ledger_complete:
            # Downgrade to compensation-only: tombstone, never delete.
            branch.state = "retracted"
            for obs in observers:
                obs.consumed_retraction = False
            return

        unconsumed = [o for o in observers if not o.consumed_retraction]
        if unconsumed:
            readers = {o.reader_branch for o in unconsumed}
            raise UnrollbackableObservationError(
                f"branch {branch_id} observed by {sorted(readers)}; "
                f"retraction not consumed, refusing silent rollback"
            )

        branch.state = "rolled_back"

    def commit(self, branch_id: str, retracted: Set[str]) -> None:
        # Transitive observation closure: the branch's own reads, plus the
        # reads of every branch it read from, transitively.
        closure: Set[str] = set()
        frontier = [branch_id]
        seen: Set[str] = set()
        while frontier:
            b = frontier.pop()
            if b in seen:
                continue
            seen.add(b)
            for obs in self.branches[b].observations_made:
                src = obs.read_key.split(":", 1)[0]
                closure.add(src)
                frontier.append(src)

        blocked = closure & retracted
        if blocked:
            raise UnrollbackableObservationError(
                f"cannot commit {branch_id}: transitive dependency on "
                f"retracted branches {sorted(blocked)}"
            )
        self.branches[branch_id].state = "committed"