# How does an instance detect that a speculative branch is unsound before committing its effects: the read-set provenance invariant in parallel branch-and-verify rollback **Date of Record:** 2026 November 25 **Scope:** Applies to orchestrators that fan out several candidate agent plans in parallel, execute them speculatively against shared external state, and roll back all but the winning branch. Does not apply to read-only speculation (no side effects to unwind) or to single-branch execution with no competing plans. ## Core Distinction The failure mode is not "the speculative branch produced a wrong answer." It is that a speculative branch **produced a correct answer whose correctness depended on a read that a sibling branch mutated before the winner was selected.** The branch's local verification passes because its own tool-call trace is internally consistent; the commit fails because the world it verified against no longer exists at commit time. The distinction that matters operationally: **rollback of writes is a solved bookkeeping problem; rollback of reads is not.** An orchestrator can trivially undo the `INSERT`, the `PUT`, the file write, the HTTP `POST` — those are enumerated effects. It cannot undo the *knowledge* a branch acquired from a read that was valid at read time and stale at commit time. That knowledge is baked into the branch's reasoning trace, its distilled plan, and any intermediate artifacts it wrote. When the orchestrator selects branch B over branch A and commits B's effects, A's discarded reads are harmless — but B's reads may have been poisoned by A's *uncommitted speculative writes* that were visible to B during the overlap window. This is the speculative-execution analogue of a memory-ordering violation, except the reordering is across *non-deterministic LLM tool calls* rather than CPU instructions, and the "memory" is a shared MCP resource server whose isolation guarantees are weaker than the orchestrator assumes. ## What Was Observed A three-branch fan-out was launched against a shared inventory service exposed as an MCP tool. Each branch was an independent agent instance with its own context window, given the same task ("reserve capacity for order #4417") and different heuristics for choosing a warehouse. The orchestrator ran all three concurrently with a 90-second wall-clock budget, then selected the branch with the lowest projected cost and rolled back the other two. The observed trace: 1. Branch A calls `inventory.reserve(warehouse=W2, qty=40)` at T+12s. The service applies the reservation immediately — there is no two-phase commit at the MCP layer. A's reservation is a *speculative write visible to all readers.* 2. Branch B calls `inventory.query(warehouse=W2)` at T+13s. It sees 40 units already reserved and concludes W2 has insufficient headroom. B pivots to W3, calls `inventory.reserve(warehouse=W3, qty=40)` at T+18s, and its plan now costs more. 3. Branch C calls `inventory.query(warehouse=W2)` at T+14s, sees the same depleted headroom, and independently pivots to W3 as well, then reserves 40 units at W3. 4. At T+60s the orchestrator compares projected costs. Branch A is cheapest — it grabbed W2 before the contention. A is selected. The orchestrator issues compensating `inventory.release()` calls for B and C's reservations. 5. **The commit is unsound.** Branch A's winning plan was selected on the basis of a cost projection that assumed W2 was uncontended. But A never re-read W2 after its own reservation; its verification step checked "did my reserve succeed" (yes) but not "is my reservation still the cheapest valid allocation given what my siblings did." The orchestrator's selection logic compared stale cost estimates that were computed against *different, mutually inconsistent views of the world.* The subtler failure: Branch B and C both pivoted to W3 based on A's speculative reservation, and both reserved 40 units there. When the orchestrator released B and C, it released 80 units that were never really contended for. The final committed state was correct-by-luck — A's W2 reservation happened to be sufficient — but the *reason* it was selected was contaminated. In a variant run where A's heuristic was slightly worse, the orchestrator would have selected B, committed B's W3 reservation, and released A's W2 reservation — except that C's release would have raced with B's commit on the same W3 row, and the release-then-commit ordering produced a transient negative headroom that tripped a downstream capacity guard. The invariant that was violated: **a branch's verification is only valid over the read-set it actually observed, and that read-set must be proven disjoint from all sibling speculative writes that were live during the branch's execution window.** No component in the stack tracked read-sets. The MCP server tracked reservations but not *who read what when*. The orchestrator tracked branch identity but not provenance of the facts each branch's decision depended on. ## Condition of Validity The guardrail that bounds this failure is a **read-set provenance invariant**, enforced at the orchestrator, not the tool layer: > A speculative branch may be committed only if, for every external read `r` in its decision trace, no sibling branch's speculative write `w` was applied to the same resource and was live at the time of `r`, *or* the branch re-validated `r` after all sibling writes were either committed or rolled back and before commit. Three conditions must hold for the invariant to be checkable: - **Read-set capture.** Every tool call the branch makes must be tagged `read` or `write` with a resource key, and the branch's decision trace must record the resource keys of all reads that fed into its final plan. This requires the agent runtime to propagate a trace context through MCP calls — the branch cannot retroactively reconstruct which reads mattered, because its own reasoning about relevance is non-deterministic. - **Write-visibility windows.** The orchestrator must know, per speculative write, the interval `[apply_time, rollback_or_commit_time]`. A read is contaminated if its `read_time` falls inside any sibling's write-visibility window on the same resource key. - **Re-validation budget.** If contamination is detected, the branch must re-read and re-verify before commit. This costs tokens and wall-clock, so the orchestrator must reserve a re-validation budget *before* fan-out — a branch that exhausts its budget mid-revalidation is uncommittable, not "probably fine." The invariant is *not* satisfiable by simply serializing branches: serialization destroys the latency benefit that motivates speculation. It is also not satisfiable by snapshot isolation at the tool layer alone, because the agent's *reasoning* is the thing that must be re-validated, not just the data — a branch that read a stale value and reasoned correctly about it still holds a stale conclusion. ## Decision Boundary The orchestrator must decide, at commit time, between three outcomes per branch: - **Commit** — read-set is provably disjoint from all live sibling writes, or re-validation succeeded within budget. - **Re-validate then commit** — contamination detected, re-validation budget remains, re-read confirms the decision still holds. - **Discard as uncommittable** — contamination detected and either no budget remains or re-validation flips the decision. This branch's effects are rolled back and it is *excluded from selection*, even if it was the cost winner. The boundary is sharp: a branch is never "committed with a warning." The failure mode this invariant prevents is precisely the one where a contaminated branch is committed because its local verification passed and the orchestrator had no visibility into the contamination. Once contamination is detected, the branch is either clean or it is out — there is no partial-trust commit. The non-obvious corollary: **the cost comparison that selects the winner must be run on re-validated costs, not original costs.** In the observed trace, A's original cost projection was computed against an uncontended W2; B and C's were computed against a contended W2. Comparing them is comparing numbers from different worlds. The orchestrator must force re-validation of the *winner's* read-set before the selection is final, because the winner is the one whose commit will actually land. ## Operational Effect With the invariant enforced, the observed trace changes at step 4: the orchestrator detects that A's cost projection read W2 at T+11s (before A's own write, clean) but that A's *verification* read W2 at T+55s, which falls inside B's and C's write-visibility windows on W2? No — B and C wrote W3, not W2. The contamination is on the *reverse* edge: B and C's decisions read W2 at T+13s and T+14s, which fall inside A's write-visibility window `[T+12s, T+60s]`. B and C are contaminated. Since A is the winner and A's own read-set is clean (its reads on W2 precede its own write and no sibling wrote W2), A commits soundly. B and C are discarded as uncommittable *without* their releases being treated as evidence about W3 contention. The downstream negative-headroom race in the variant run never occurs, because the releases are classified as rollbacks of contaminated branches, not as corrections to a real contention signal. The cost is real: every speculative fan-out now carries a read-set tracing overhead (typically 5–15% token overhead for trace annotation) and a re-validation reserve (one extra read per committed branch, plus a reserve for the winner). The benefit is that the orchestrator's selection is sound under concurrency — it no longer commits a branch whose justification was a world that a sibling had already changed. The invariant degrades gracefully: if read-set capture is unavailable (a tool that doesn't propagate trace context), the orchestrator must treat every read from that tool as contaminated-by-default and force re-validation, which is expensive but safe. The unsafe default is the one that shipped: treating reads as clean because nothing told the orchestrator otherwise. ```python import time from dataclasses import dataclass, field from typing import Optional class ContaminatedCommitError(RuntimeError): """Raised when a speculative branch is about to commit effects whose justification depended on a read that overlapped a sibling's live write.""" pass @dataclass class TraceEvent: kind: str # "read" | "write" resource: str timestamp: float branch_id: str @dataclass class Branch: branch_id: str events: list[TraceEvent] = field(default_factory=list) revalidation_budget: int = 2 committed: bool = False def write_visibility_windows(branches: list[Branch]) -> dict[str, list[tuple[float, float, str]]]: """Map resource -> [(apply_time, close_time, branch_id)] for speculative writes. A window closes at commit/rollback; here we model it as still-open until selection.""" windows: dict[str, list[tuple[float, float, str]]] = {} now = time.time() for b in branches: for e in b.events: if e.kind == "write": windows.setdefault(e.resource, []).append((e.timestamp, now, b.branch_id)) return windows def is_contaminated(branch: Branch, windows: dict[str, list[tuple[float, float, str]]]) -> Optional[TraceEvent]: """Return the first read event in `branch` that falls inside a *sibling's* write-visibility window on the same resource, else None.""" for e in branch.events: if e.kind != "read": continue for (apply_t, close_t, writer) in windows.get(e.resource, []): if writer == branch.branch_id: continue if apply_t <= e.timestamp <= close_t: return e return None def commit_branch(branch: Branch, siblings: list[Branch]) -> None: windows = write_visibility_windows(siblings) contamination = is_contaminated(branch, windows) if contamination is None: branch.committed = True return # Contaminated: attempt bounded re-validation. while branch.revalidation_budget > 0: branch.revalidation_budget -= 1 # Re-read the contaminated resource; here we model re-read as clean # only if no sibling window now covers the new timestamp. retry_ts = time.time() still = any( apply_t <= retry_ts <= close_t and writer != branch.branch_id for (apply_t, close_t, writer) in windows.get(contamination.resource, []) ) if not still: branch.committed = True return raise ContaminatedCommitError( f"branch {branch.branch_id} read {contamination.resource} at " f"t={contamination.timestamp:.3f} inside a sibling write-visibility window; " f"re-validation budget exhausted ({branch.revalidation_budget} left). " f"Branch is uncommittable and must be excluded from selection." ) def select_and_commit(branches: list[Branch], costs: dict[str, float]) -> Branch: """Select the cheapest branch, but force re-validation of the winner's read-set before the selection is finalized.""" winner = min(branches, key=lambda b: costs[b.branch_id]) others = [b for b in branches if b.branch_id != winner.branch_id] commit_branch(winner, siblings=others) if not winner.committed: raise ContaminatedCommitError( f"winner {winner.branch_id} failed post-selection re-validation; " f"selection must fall through to next-cheapest clean branch." ) return winner ```