What happens when an instance commits a speculative branch before its reconciliation barrier is closed

**Date of Record:** 2026 December 2 **Scope:** Applies to multi-agent pipelines that fan out speculative parallel branches (drafting, retrieval, plan variants) and reconcile them into a single committed result. Does not apply to strictly serial pipelines or single-agent retry loops, where no cross-branch commit surface exists.

Core Distinction

The failure is not "a branch produced a wrong answer." Speculative branches are *expected* to be wrong; that is the premise of speculation. The distinct failure is a **commit/reconciliation ordering violation**: a speculative branch mutates durable state (writes a checkpoint, emits a tool side-effect, updates shared memory, or signals downstream) *before* the reconciliation barrier that decides which branch survives has closed. Once a losing branch has committed, rollback is no longer a state transition—it is a compensating transaction against the outside world, and the pipeline has silently crossed from *speculation* into *irreversible execution*.

The invariant that must hold is:

> For every speculative branch B, no externally observable effect of B may occur before the reconciliation barrier R has selected a winner set W, and B ∉ W implies no effect of B is ever observable.

This is an ordering invariant, not a correctness invariant. A branch can be perfectly correct and still violate it.

What Was Observed

A three-branch fan-out (planner, retriever, critic) drafting candidate plans for a tool-using agent. Each branch ran with its own context window and a shared `scratch` memory namespace. The orchestrator was supposed to (1) run all branches, (2) score them, (3) commit the winner, (4) discard losers.

Trace of the failure:

  1. Branch A (planner) finished first at t=1.2s and, because its local loop reached a natural "checkpoint" step, called `memory.commit(branch_id="A", payload=plan_A)`. The `commit` path wrote into the *shared* semantic store rather than a branch-local overlay—the overlay was configured but the branch's tool schema exposed the raw commit tool, and the planner's probabilistic reasoning chose the more "complete" action.
  2. Branches B and C finished at t=2.8s and t=3.1s. Scoring at R selected B (higher validator score, lower token cost).
  3. Reconciliation wrote `plan_B` as the winner and issued `memory.discard(branch_id="A")`. But `discard` only removed A's *local* overlay entries; the shared-store write from step 1 had no overlay tag and was untouched.
  4. Downstream, the retriever branch's next invocation read the shared semantic store, retrieved fragments of `plan_A` (the *losing* plan), and treated them as established context. The committed plan was B, but the agent's memory now contained a coherent, plausible, and contradictory plan A fragment. The agent proceeded to execute a hybrid of A and B.

The observable symptom was not a crash. It was a **plausible but internally inconsistent plan** that passed schema validation and only failed at tool-call time, three steps later, when two subgoals demanded mutually exclusive preconditions. The error surfaced far from its cause, in a different branch, in a different context window.

Root cause decomposition:

Condition of Validity

The invariant holds—and the failure is bounded—only under the following conditions, all of which must be enforced by the runtime, not by prompt instruction:

  1. **Write isolation by construction.** Speculative branches must execute against a copy-on-write overlay keyed by `branch_id`; the global commit tool must be *absent from the branch's tool schema entirely*, not merely discouraged. If a tool is reachable, a probabilistic agent will eventually reach it.
  2. **Effect fencing at the transport layer.** Any side-effecting call (memory commit, external API, message emit) must carry a `barrier_token` that is only minted by the orchestrator after R closes. Calls without a valid token are rejected at the boundary, not logged and allowed.
  3. **Reconciliation replay.** After R, the orchestrator must reconstruct the post-commit state from W alone and diff it against actual durable state. Any divergence attributable to a losing branch is a hard failure, not a warning.
  4. **Barrier closure is a state transition, not a timestamp.** R must be a monotonic event: `OPEN → SCORING → CLOSED`, and branch effects are only admissible in `CLOSED`.

When any of these is missing, the pipeline is in *speculative execution in name only*: it fans out, but it does not fence, and the first fast branch to "helpfully" commit determines durable state regardless of the scoring outcome.

Decision Boundary

The boundary is between **rollback as state transition** and **rollback as compensation**:

The decision rule for an orchestrator receiving a branch result is therefore not "is this result good?" but "**was this branch's effect admissible at the moment it was produced?**" A branch that returns a high-scoring result *and* leaked a pre-barrier commit must be treated as a failed branch, because its correctness is now entangled with state the pipeline cannot retract. Scoring a leaked branch as a winner is the specific mistake that converts a recoverable leak into a committed inconsistency.

Corollary: the orchestrator must be able to *detect* leakage, which requires the replay check in condition 3. Without it, the boundary is invisible and the pipeline will report success while carrying a losing branch's residue forward.

Operational Effect

The practical consequences of crossing this boundary:

The guardrail that bounds all of this is the fenced barrier: no branch effect is admissible until R is `CLOSED`, and admissibility is enforced by the runtime that mints the barrier token, with a post-R replay diff that treats any losing-branch residue as a hard failure. The following reference check encodes the detection and the hard stop.

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


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a branch effect is observed before the reconciliation barrier closes."""
    pass


class BarrierState(Enum):
    OPEN = "open"
    SCORING = "scoring"
    CLOSED = "closed"


@dataclass
class BranchEffect:
    branch_id: str
    target: str          # e.g. "shared_memory", "external_api"
    barrier_token: str | None


@dataclass
class ReconciliationBarrier:
    state: BarrierState = BarrierState.OPEN
    winner_set: Set[str] = field(default_factory=set)
    admitted_effects: Dict[str, list] = field(default_factory=dict)

    def close(self, winner_set: Set[str]) -> None:
        if self.state is not BarrierState.SCORING:
            raise SpeculativeCommitViolation(
                f"barrier closed from illegal state {self.state}"
            )
        self.winner_set = winner_set
        self.state = BarrierState.CLOSED

    def admit(self, effect: BranchEffect, valid_token: str) -> None:
        # Hard invariant: no effect is admissible before CLOSED, and only
        # winners may produce effects after CLOSED.
        if self.state is not BarrierState.CLOSED:
            raise SpeculativeCommitViolation(
                f"branch {effect.branch_id} emitted effect to {effect.target} "
                f"while barrier was {self.state.value}; effect is unrecoverable"
            )
        if effect.barrier_token != valid_token:
            raise SpeculativeCommitViolation(
                f"branch {effect.branch_id} presented invalid barrier token; "
                f"possible pre-barrier leak"
            )
        if effect.branch_id not in self.winner_set:
            raise SpeculativeCommitViolation(
                f"losing branch {effect.branch_id} attempted post-barrier commit"
            )
        self.admitted_effects.setdefault(effect.branch_id, []).append(effect.target)


def reconcile_and_verify(
    barrier: ReconciliationBarrier,
    branch_effects: list[BranchEffect],
    durable_state: Dict[str, list],
    valid_token: str,
) -> None:
    """Replay check: durable state must match admitted winner effects exactly."""
    for effect in branch_effects:
        barrier.admit(effect, valid_token)

    expected: Dict[str, list] = {}
    for bid in barrier.winner_set:
        expected[bid] = barrier.admitted_effects.get(bid, [])

    for bid, targets in durable_state.items():
        if bid not in barrier.winner_set:
            raise SpeculativeCommitViolation(
                f"durable state contains residue from losing branch {bid} "
                f"at targets {targets}; rollback is now a compensating transaction"
            )
        if targets != expected.get(bid, []):
            raise SpeculativeCommitViolation(
                f"durable state for winner {bid} diverges from admitted effects: "
                f"expected {expected.get(bid, [])}, found {targets}"
            )


def run_speculative_pipeline() -> None:
    barrier = ReconciliationBarrier()
    # Branch A (fast) attempts to commit before scoring even begins.
    early = BranchEffect(branch_id="A", target="shared_memory", barrier_token=None)
    try:
        barrier.admit(early, valid_token="tok-R")
    except SpeculativeCommitViolation as exc:
        # Correct behavior: abort the pipeline, do not score, do not compensate.
        raise SpeculativeCommitViolation(
            f"speculative execution aborted at barrier: {exc}"
        )


if __name__ == "__main__":
    try:
        run_speculative_pipeline()
    except SpeculativeCommitViolation as e:
        print(f"HALT: {e}")