# Under what conditions must an instance abort a speculative branch before merge: rollback invalidation and the commit-fence invariant in parallel branch-and-merge agent workflows **Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that fan out a task into parallel speculative agent branches whose partial results are merged into a shared durable state, and that rely on rollback (compensating actions or checkpoint rewind) to discard losing branches. Does not apply to single-threaded agent loops or to fan-out topologies where branches write to fully isolated, never-merged stores. ## Core Distinction The common mental model of speculative execution is borrowed from CPU microarchitecture: a speculative branch either commits (its writes become visible) or squashes (its writes are discarded), and the two outcomes are mutually exclusive and atomic. In agent systems this model is false in a specific and dangerous way. A speculative agent branch does not merely emit *writes*; it emits **side effects with external, non-rewindable consequences** — tool calls that mutate third-party state, sent messages, consumed rate-limit budget, and *observations* that have already been folded back into the branch's own reasoning context. Rollback can rewind the orchestrator's local state, but it cannot un-send the email, un-charge the card, or un-observe the tool output that now lives inside the branch's context. The distinction that governs everything below is between **state rollback** (reversible: checkpoints, local memory, scratchpads) and **effect rollback** (irreversible without a compensating transaction that is itself an agent action). A speculative merge is only sound when every effect a branch produced before the merge decision is either (a) idempotent and reversible via a registered compensator, or (b) *withheld* until the commit fence. The failure mode arises precisely when a branch crosses the commit fence with an effect before the merge decision is finalized — and the orchestrator's rollback logic assumes it didn't. ## What Was Observed A planner agent decomposed a research-and-reconcile task into three parallel speculative branches (B1, B2, B3), each tasked to independently derive a recommendation and, as part of derivation, to call a `reserve_resource` tool. The orchestrator's design intent: all three branches run speculatively, the merge step picks the branch whose recommendation has the highest internal confidence, and losing branches are rolled back via checkpoint rewind. The trace: 1. B1, B2, B3 each checkpoint at `t0`, then execute concurrently. 2. Each branch calls `reserve_resource(id)`. The tool is **not idempotent** — a second reservation for the same id returns a *new* reservation handle and does not release the prior one. The orchestrator's compensator table registered no compensator for this tool because the tool schema declared it "read-like" (it returns a handle; the schema author reasoned it was a query). 3. B2's reasoning diverges: a tool timeout causes B2 to retry `reserve_resource`, producing reservation handle `R2b` while `R2a` remains live. B2's context now contains two handles and a confused belief that "the resource is reserved twice." 4. Merge step selects B1 (highest confidence). Orchestrator rewinds B2 and B3 to `t0` and marks them squashed. 5. **The rewind succeeds locally.** The orchestrator's state is clean. But reservations `R2a`, `R2b`, and `R3` are still live on the external resource service. The orchestrator has no record of them because the handles lived only in the squashed branches' contexts, which were discarded by the rewind. 6. A later, unrelated branch B4 attempts `reserve_resource` on the same id and is denied — capacity exhausted by orphaned reservations. B4's reasoning interprets the denial as "resource is genuinely contended," and it escalates to a human. The orphaned reservations are never discovered because the handles are gone. The observable symptom was not a crash. It was **silent capacity leakage plus a corrupted downstream belief** ("resource is contended") that was causally false and unfalsifiable from within the system, because the evidence needed to falsify it had been rolled back. ## Condition of Validity The rollback-and-merge protocol is sound **if and only if** the following invariant holds at the moment of the merge decision: > **Commit-fence invariant:** For every speculative branch `b` that will be squashed, every effect `e` produced by `b` is either (i) recorded in the orchestrator's compensator ledger with a verified inverse, or (ii) provably never crossed the fence — i.e., was staged, not applied. This invariant can only be guaranteed if the orchestrator can *classify every tool call a branch makes as reversible, irreversible-but-withheld, or irreversible-and-applied*, and if the classification is derived from a source the branch cannot lie about. Two failure conditions invalidate it: - **Schema misclassification.** A tool whose external effect is irreversible is declared reversible (or "read-like") in the manifest. This is the trigger observed above. The branch cannot detect the misclassification because it only sees the tool's return value, not its side-effect class. - **Fence escape via retry or nested call.** A branch crosses the fence *after* the orchestrator has decided to squash it, because an in-flight tool call (a retry, a slow response, a nested sub-agent call) completes during the rewind window. The rewind rewinds *state*, but the in-flight effect lands *after* the rewind, orphaned. The invariant is *not* threatened by ordinary reasoning divergence, low confidence, or even wrong answers — those are the normal, safe cases that rollback handles correctly. It is threatened specifically by **irreversible effects produced on branches that lose**, and by **effects that land in the rewind window**. ## Decision Boundary The orchestrator must decide, per branch, between three dispositions, and the boundary between them is the reversibility class of the branch's *applied* effects: - **Safe to squash** — all applied effects have verified compensators in the ledger, and no tool call is in flight. Action: run compensators in reverse order, then rewind state. - **Must drain before squash** — a tool call is in flight (retry pending, response outstanding). Action: block the merge decision until the call settles, *then* classify its effect. Squashing with a call in flight is the fence-escape bug. - **Must promote to committed** — an irreversible effect has been applied and has no compensator. The branch can no longer be silently squashed. Action: either promote the branch's effect to a first-class committed record (so the handle survives the rewind and can be reconciled later), or halt the merge and surface a reconciliation task. **Silent squash is forbidden here.** The precise boundary condition that decides "safe to squash" vs. "must promote" is: *does the branch's context contain a handle to an external effect that the orchestrator's ledger does not also contain?* If yes, squashing loses the only reference to a live effect. This check must be run against the branch's tool-call transcript, not against the branch's self-report — a branch that has misclassified its own tool as read-like will *not* volunteer the handle. ## Operational Effect When the commit-fence invariant is enforced, speculative fan-out becomes safe but slower: the merge step must drain in-flight calls and reconcile irreversible effects before it can squash anything. The cost is latency proportional to the slowest outstanding tool call, not to branch count. When the invariant is violated, the system exhibits **silent effect leakage with belief corruption** — the worst combination, because the leaked effects consume real external capacity while the corrupted beliefs are self-sealing (the evidence is rolled back). The leak is invisible until an unrelated branch collides with it, at which point the collision is misread as genuine contention and escalated as a false positive. The guardrail is a **compensator ledger keyed by effect handle, populated from the tool manifest's declared reversibility class, with a hard refusal to squash any branch holding a handle absent from the ledger.** The manifest is the trust root; a misclassified manifest entry is a configuration bug that the ledger cannot catch, so manifest reversibility classes must be validated against tool behavior in a staging harness before a tool is admitted to speculative fan-out. Tools whose reversibility cannot be verified are excluded from speculative branches entirely and forced onto a serialized path. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class Reversibility(Enum): REVERSIBLE = "reversible" # has a verified compensator WITHHELD = "withheld" # staged, not yet applied IRREVERSIBLE = "irreversible" # applied, no compensator class CommitFenceViolation(RuntimeError): """Raised when a speculative branch is squashed while holding an unledgered irreversible effect, or while a tool call is in flight.""" pass @dataclass class Effect: handle: str tool: str reversibility: Reversibility applied: bool = True @dataclass class Branch: branch_id: str effects: list[Effect] = field(default_factory=list) in_flight_calls: int = 0 def record_effect(self, effect: Effect) -> None: self.effects.append(effect) @dataclass class CompensatorLedger: # handle -> compensator callable name; presence means "verified inverse exists" entries: dict[str, str] = field(default_factory=dict) def has(self, handle: str) -> bool: return handle in self.entries def classify_for_squash(branch: Branch, ledger: CompensatorLedger) -> str: """Decide whether a losing branch may be silently squashed. Returns one of: 'safe_to_squash', 'must_drain', 'must_promote'. Raises CommitFenceViolation if the branch holds an applied irreversible effect whose handle is absent from the ledger (the silent-leak case). """ if branch.in_flight_calls > 0: # Fence-escape risk: an effect could land after the rewind. return "must_drain" for effect in branch.effects: if not effect.applied: continue if effect.reversibility is Reversibility.IRREVERSIBLE: if ledger.has(effect.handle): # Ledgered irreversible effect with a compensator -> squashable. continue # Applied, irreversible, no compensator. Squashing would orphan # the live effect and discard the only handle to it. raise CommitFenceViolation( f"branch {branch.branch_id} holds unledgered irreversible " f"effect {effect.handle} ({effect.tool}); silent squash " f"forbidden -- promote to committed or halt for reconciliation" ) if effect.reversibility is Reversibility.REVERSIBLE and not ledger.has( effect.handle ): # Declared reversible but no verified compensator: manifest lie. raise CommitFenceViolation( f"branch {branch.branch_id} effect {effect.handle} declared " f"reversible but absent from compensator ledger" ) return "safe_to_squash" def merge_speculative( branches: list[Branch], winner_id: str, ledger: CompensatorLedger ) -> list[str]: dispositions: list[str] = [] for b in branches: if b.branch_id == winner_id: dispositions.append(f"{b.branch_id}:commit") continue try: disposition = classify_for_squash(b, ledger) except CommitFenceViolation: # Re-raise with branch context; orchestrator must halt, not guess. raise dispositions.append(f"{b.branch_id}:{disposition}") return dispositions ```