# What happens when an instance commits a speculative branch before the verifier's witness has propagated: the witness-ordering hazard in branch-and-verify rollback **Date of Record:** 2026 November 25 **Scope:** Applies to multi-agent systems that run speculative parallel branches (N candidate sub-agents executing ahead of a slow verifier) and roll back losers by compensating actions. Does not apply to single-agent speculative decoding, or to systems where branches are pure/read-only and rollback is a no-op. ## Core Distinction The failure is not "the verifier said no." It is the *ordering* between two asynchronous events: (a) a worker branch performing an **irreversible external commitment** (writing to a shared store, sending a message, spending a budgeted API call, mutating a downstream agent's state), and (b) the verifier's **witness** — the signed, monotonic acknowledgment that branch *B* was selected or rejected — arriving at that worker's rollback controller. Most speculative-execution designs assume rollback is symmetric: commit on accept, undo on reject. This holds only when the undo record is created *before* the commitment and is *globally visible* before any concurrent verifier decision. When the commitment happens between "branch fires" and "witness propagates," the worker becomes **transactionally orphaned**: it has already spent cost and mutated state, but its rollback controller has not yet learned whether it is a winner or a loser. If the system optimistically continues — the common "cost-aware commitment" heuristic that avoids blocking on a slow verifier — the loser's side effects land in the shared substrate *after* the winner's, and compensating rollback silently reverses the winner's writes because both branches wrote to the same key. The invariant that must hold is: **no branch may perform an externally visible commitment until its branch-local undo record is durably registered under a branch-unique key, and no rollback may execute against a key it did not itself create.** The subtlety is that "branch-unique key" is not enough — the *compensating action* must be keyed to the writer's identity, not to the logical resource, because losers and winners legitimately contend for the same logical resource. ## What Was Observed A three-branch speculative planner (branches A, B, C) is dispatched against a shared `task_state` document. Verifier is a slower model with a 4.2s median decision latency. Each branch has a 2.0s budget for its first tool call. The orchestrator, optimizing for cost, allows branches to commit "low-cost, high-confidence" writes immediately and roll back losers later, on the theory that losers are rare. Trace: 1. `t=0.0` — A, B, C dispatched. All three write `task_state.plan` via `compare_and_swap(version=v0, value=)`. A wins the CAS at `t=0.4`, version becomes `v1`. 2. `t=0.4` — A's rollback controller registers undo record `undo:A@v1` keyed to `task_state.plan`. A continues. 3. `t=0.9` — B's CAS against `v0` fails (stale). B's controller treats the CAS failure as a *transient* and retries against `v1`, succeeding at `t=1.1`. Version becomes `v2`. B registers `undo:B@v2`. **B's write overwrote A's plan.** A is unaware. 4. `t=1.1` — C's CAS against `v1` fails; C backs off (correct behavior). 5. `t=4.2` — Verifier returns `select=A`. Witness `W(A, accept, v1)` is enqueued to A's controller; witness `W(B, reject, v2)` enqueued to B's controller. 6. `t=4.3` — B's controller receives `W(B, reject)` and executes `undo:B@v2`, restoring `task_state.plan` to `v1`'s predecessor — i.e., `v0`. **This is correct for B but destroys A's committed plan**, because the undo was keyed to the logical resource, not to B's write identity. 7. `t=4.4` — A's controller receives `W(A, accept)` and does nothing (accept is a no-op). A's plan is gone. Downstream agents read `v0` and re-plan from scratch, silently, at full cost. The observable symptom is not an exception. It is a **silent plan regression**: the winning branch's output vanishes, the system re-executes, and the only evidence is a version-counter discontinuity (`v2 → v0`) and a duplicated first-tool-call cost in the ledger. In one reproduced run, this cost 1.7× the single-shot baseline for a task the speculative path was supposed to make cheaper. Two secondary observations: - **Witness reordering.** When witnesses are enqueued on a per-branch queue but drained by a single shared consumer, `W(B, reject)` can be processed before `W(A, accept)` even when the verifier emitted accept first. Rollback controllers that assume "the accept witness always precedes a reject witness for any overlapping key" are wrong; there is no such guarantee across independent queues. - **Cost-aware commitment amplifies the hazard.** The heuristic "commit early because losers are rare" is exactly the heuristic that maximizes the window between commitment and witness. At a 12% branch-rejection rate, the expected number of orphaned commitments per task is `0.12 × (branches − 1) ≈ 0.24`; at a 3.5s verifier latency and 2.0s branch budget, ~40% of those orphans land in the danger window. The optimization that makes speculation cheap makes its rollback unsafe. ## Condition of Validity The safe-rollback invariant holds only when **all** of the following are true; if any fails, the system must fall back to blocking-commit (no external writes until witness received): 1. Every branch's undo record is registered under a key of the form `(branch_id, resource_id, write_epoch)` where `write_epoch` is the version *produced by that branch's own successful CAS*, not the version it read. 2. The compensating action is `compare_and_swap(resource, expected=write_epoch, value=pre_write_value)` — a *conditional* undo that fails loudly if the resource has moved past the branch's own epoch. An unconditional `set` is unsafe. 3. The verifier's witness is monotonic per resource: once `W(B, reject)` is emitted, no later `W(B, accept)` for the same `write_epoch` can exist. (Guaranteed if the verifier is single-writer per resource; violated if verifiers are sharded and can disagree.) 4. Branch dispatch is ordered such that no branch can CAS against a version it did not itself observe *after* the verifier has begun evaluating that version. In practice this means the verifier must **freeze** the resource (reject further CAS from un-witnessed branches) at the moment it begins evaluation, or branches must be CAS-locked to their dispatch-time version and forbidden from retrying. Condition 4 is the one most systems miss. The trace above violated it at step 3: B retried against `v1` *after* A had committed, and the retry was permitted because the CAS layer had no notion of "verifier is evaluating `v1`." The retry looked like normal optimistic-concurrency behavior; it was actually a speculative branch mutating state the verifier was about to adjudicate. ## Decision Boundary The operational decision is: **when may a branch commit before its witness arrives?** Commit-early is admissible iff the resource is *branch-partitioned* — i.e., each branch writes to a disjoint key namespace (`plan:A`, `plan:B`, `plan:C`) and a separate merge step, itself witnessed, selects the winner. In that design, loser rollback is a key-delete of the branch's own namespace and cannot touch the winner. This is the only configuration in which the cost-aware heuristic is sound. Commit-early is **inadmissible** when branches contend for a shared logical resource via CAS. In that case the correct behavior is: - Branch performs CAS; on success it holds a *lease* on the resource, not a commitment. - The lease is visible to the verifier and blocks further CAS from un-witnessed branches (condition 4). - The branch may perform *reversible* side effects under the lease (staging writes, draft messages) but no externally visible commitment. - On witness `accept`, the lease converts to commitment. On `reject`, the lease is released and the staged writes are dropped — no conditional undo needed, because nothing irreversible happened. - If the verifier times out, the lease expires and the resource reverts to `v0` with a logged `witness_timeout` event; the branch is *not* silently retried. The boundary is therefore not "cheap vs. expensive" but "partitioned vs. contended." Cost-aware commitment on contended resources is a category error: the cost being optimized (avoiding blocking) is paid for with a correctness hazard (orphaned commitment) that the rollback layer cannot detect, only the version ledger can. ## Operational Effect Adopting the lease-based discipline changes three things: 1. **Rollback becomes conditional and identity-keyed.** Every compensating action is a CAS against the branch's own produced epoch; a failed CAS on undo raises rather than silently overwriting. This converts the silent plan regression into a loud `RollbackEpochMismatch`, which is recoverable (re-plan the branch) rather than corrupting. 2. **The verifier's freeze is a first-class state.** The resource carries a `frozen_by_verifier` flag for the duration of evaluation. Branches that attempt CAS during freeze receive `VerifierFreezeError` and back off; they do not retry. This bounds the orphan window to zero for contended resources. 3. **Speculation cost accounting must include rollback cost.** The ledger records `commit_cost + rollback_cost + reexecution_cost` per branch; the cost-aware heuristic is re-evaluated against the *total*, not the commit alone. In the reproduced trace, the "cheap" path was 1.7× the baseline once rollback-induced re-execution was counted — the heuristic was inverted by its own failure mode. The general lesson for agent systems: speculative execution is safe only where the speculation's side effects are *partitioned by construction*, not merely *rolled back by convention*. A rollback that depends on the loser knowing it lost before the winner's effects land is a race, and in a system with a slow verifier and a fast branch, the race is lost by default. ```python from dataclasses import dataclass from typing import Optional class RollbackEpochMismatch(RuntimeError): """Raised when a branch's compensating action would touch a resource that has moved past the branch's own write epoch. This is the loud replacement for the silent plan-regression failure mode.""" pass class VerifierFreezeError(RuntimeError): """Raised when a branch attempts a CAS on a resource currently frozen by an in-progress verifier evaluation. Branches must back off, not retry.""" pass @dataclass(frozen=True) class UndoRecord: branch_id: str resource_id: str write_epoch: int # version THIS branch produced via its own CAS pre_write_value: object # value to restore, conditionally class ResourceStore: def __init__(self): self._value = {} self._version = {} self._frozen = set() def freeze(self, resource_id: str) -> None: self._frozen.add(resource_id) def unfreeze(self, resource_id: str) -> None: self._frozen.discard(resource_id) def cas(self, resource_id: str, expected: int, value: object) -> int: if resource_id in self._frozen: raise VerifierFreezeError( f"resource {resource_id} frozen by verifier; branch must back off" ) if self._version.get(resource_id, 0) != expected: raise RollbackEpochMismatch( f"CAS on {resource_id} expected v{expected}, " f"found v{self._version.get(resource_id, 0)}" ) new = expected + 1 self._version[resource_id] = new self._value[resource_id] = value return new def conditional_undo(self, rec: UndoRecord) -> None: # Only undo if the resource is still exactly at the epoch this # branch produced. If a winner has since advanced it, refuse. current = self._version.get(rec.resource_id, 0) if current != rec.write_epoch: raise RollbackEpochMismatch( f"branch {rec.branch_id} cannot undo {rec.resource_id}: " f"expected v{rec.write_epoch}, resource at v{current}. " f"Refusing to clobber a later writer." ) self._version[rec.resource_id] = rec.write_epoch - 1 self._value[rec.resource_id] = rec.pre_write_value def rollback_loser(store: ResourceStore, rec: UndoRecord, witness: str) -> None: if witness != "reject": return try: store.conditional_undo(rec) except RollbackEpochMismatch as e: # Loud, recoverable: re-plan the branch rather than corrupt state. raise RollbackEpochMismatch( f"rollback of branch {rec.branch_id} aborted; schedule re-plan: {e}" ) from e ```