# Where must an instance reconcile speculative branches before committing, when parallel plans have already mutated the same external resource? **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that fans a single goal into N speculative sub-plans executed in parallel against shared external resources (filesystems, issue trackers, databases, SaaS APIs), where each branch may write. It does not apply to read-only fan-out (map-reduce retrieval, parallel search) or to branches that write only to branch-private sandboxes that are never merged back. ## Core Distinction The failure here is not "a write conflict." Naive conflict detection catches two branches writing the same key at the same logical instant. The dangerous case is **divergent speculative writes that never collide in time but collide in intent**: branch A reads resource `R` at `t0`, writes a *derived* value at `t2`; branch B reads `R` at `t1` (after `t0`, before `t2`), writes a *different derived* value at `t3`. No write-write race fires. Both writes succeed. The reconciler then sees two "successful" branches and must decide which post-state is truth — but neither branch's post-state is correct, because each was computed from a pre-image that the other invalidated. The distinction that matters operationally: a **speculative branch is a hypothesis about a pre-image plus a transformation**. It is only valid if its pre-image still holds at commit time. Conflict detection on *writes* is insufficient; you must validate the *read-set* (the pre-image) at reconciliation, not just the *write-set*. This is optimistic concurrency control, and agent runtimes routinely omit it because each branch runs in its own LLM context that "feels" isolated. ## What Was Observed A planner instance decomposed "bump the dependency and fix call sites" into three parallel branches: (1) edit `pyproject.toml` to raise `libfoo` from 2.1→3.0; (2) update call sites in `src/` for the new API; (3) regenerate the lockfile. Branches 1 and 3 both touched the dependency graph. Branch 3's lockfile regeneration read `pyproject.toml` at `t1`, *before* branch 1's edit landed at `t2`. Branch 3 therefore produced a lockfile consistent with `libfoo==2.1`. Branch 1 then wrote `libfoo==3.0`. Both branches reported success. The reconciler, which compared write-sets for overlap, saw `pyproject.toml` (branch 1) and `poetry.lock` (branch 3) as disjoint and merged both. The merged tree was internally inconsistent: manifest said 3.0, lockfile pinned 2.1. The inconsistency was silent — no tool errored. It surfaced only when branch 2's updated call sites were exercised against the 2.1 API that the lockfile actually installed, at which point the error message pointed at branch 2's code, not at the reconciliation defect. The agent then spent three additional turns "fixing" correct code. The trace of the defect: ``` t0 branch1.read(pyproject) -> libfoo==2.1 t1 branch3.read(pyproject) -> libfoo==2.1 # pre-image captured t2 branch1.write(pyproject, libfoo==3.0) # succeeds t3 branch3.write(poetry.lock, libfoo==2.1) # succeeds; derived from stale pre-image t4 reconcile: write-sets {pyproject} ∩ {poetry.lock} = ∅ -> MERGE ``` The invariant that was violated: **a branch's write is only committable if every resource in its read-set is unchanged since the branch's read timestamp.** Branch 3's read-set contained `pyproject.toml`; that resource changed at `t2`; branch 3's write at `t3` was therefore stale and should have been rejected or re-derived. ## Condition of Validity Speculative parallel execution is safe only under one of three regimes: 1. **Disjoint read-write closure.** Every branch's read-set ∪ write-set is disjoint from every other branch's. Rare in practice; agents under-declare read-sets because they don't know what they'll read until they read it. 2. **Serializable commit with read-set validation.** Branches execute speculatively; at reconciliation each branch's read-set is checked against a version log. Any branch whose read-set was mutated by a *committed* peer is invalidated and re-run (or its transform re-applied to the new pre-image). This is the correct default and the one most runtimes lack. 3. **Explicit pre-image pinning.** Each branch snapshots the resources it reads and writes against a content-addressed snapshot; the merge step refuses to apply a branch whose snapshot is not the current head. The failure above occurred because the runtime assumed regime 1 (disjointness inferred from write-sets) while operating in regime 2 (overlapping read-sets). The gap between "writes don't overlap" and "reads don't overlap" is exactly the speculative-branch hazard. A subtlety: read-set validation must happen **at merge, against the committed head**, not at branch start. Validating at start is useless — the whole point is that peers mutate during execution. And a branch that reads a resource *twice* (once early, once late) has a read-set that must be validated against the *earliest* read of each resource, because the transform may have been partially computed from the earlier value. ## Decision Boundary The reconciler must decide, per invalidated branch, between **re-run** and **re-derive**: - **Re-run** the branch from scratch when its transformation is non-deterministic or depends on mid-execution LLM reasoning that cannot be replayed (e.g., the branch made a judgment call about which call sites to touch). Cost: full branch re-execution, including token spend. - **Re-derive** when the branch's transformation is a pure function of its read-set (lockfile generation, code formatting, schema migration apply). Cost: re-invoke the transform against the new pre-image, no LLM re-reasoning. The boundary is **whether the branch's output is a function of its inputs alone**. If the branch's LLM context made choices not captured in the read-set (e.g., "I decided to skip this call site because it looked unused"), re-deriving against a new pre-image silently drops that judgment. Re-run is required. This is the operationally expensive case and the one agents get wrong by defaulting to cheap re-derivation. A second boundary: **cascading invalidation.** If branch 3 is invalidated and re-run, its new write may invalidate branch 4's read-set, which was validated earlier in the merge order. The reconciler must either (a) validate all read-sets against the pre-merge head *before* applying any write (two-phase), or (b) iterate to a fixed point. Single-pass validation in commit order is unsound and produces the same class of defect one level deeper. ## Operational Effect Without read-set validation, speculative parallelism converts a serializable failure (agent hits a conflict, sees the error, adapts) into a **silent consistency violation** that surfaces far from its cause. The agent's error-recovery loop is then misdirected: it debugs the symptom (branch 2's call sites) rather than the cause (branch 3's stale derivation). Empirically this costs 2–4× the turns of the serial baseline it was meant to beat, because the agent is now repairing damage it cannot attribute. With read-set validation, the reconciler rejects branch 3 at `t4`, re-derives the lockfile against the `libfoo==3.0` manifest, and the merge is consistent on the first commit. The cost is one extra derivation, not a debugging spiral. The invariant to enforce: **speculative branches are transactions over declared read-sets; commit requires read-set currency at merge time; invalidation propagates to a fixed point before any write is applied.** An agent runtime that fans out parallel writers without this is not running speculative execution — it is running unsynchronized concurrent mutation with a merge step that launders the race into a plausible-looking tree. ```python import hashlib from dataclasses import dataclass, field from typing import Callable class StaleReadSetError(RuntimeError): """Raised when a speculative branch's read-set was mutated by a committed peer.""" @dataclass class VersionLog: """Content-addressed head per resource; the source of truth for read-set currency.""" heads: dict[str, str] = field(default_factory=dict) def snapshot(self, resource: str, content: bytes) -> str: digest = hashlib.sha256(content).hexdigest() self.heads[resource] = digest return digest @dataclass class Branch: name: str read_set: dict[str, str] # resource -> version observed at read time write_set: dict[str, bytes] # resource -> new content transform: Callable[[dict[str, bytes]], dict[str, bytes]] | None = None non_deterministic: bool = False # LLM judgment not captured in read-set def reconcile(branches: list[Branch], log: VersionLog) -> list[str]: """Two-phase merge: validate all read-sets against head, then apply. Raises StaleReadSetError if any branch's pre-image is no longer current. Caller must re-run or re-derive the offending branch and retry. """ # Phase 1: validate every read-set against the *current* head. stale: list[Branch] = [] for b in branches: for resource, observed in b.read_set.items(): current = log.heads.get(resource) if current is not None and current != observed: stale.append(b) break if stale: names = ", ".join(b.name for b in stale) raise StaleReadSetError( f"branches [{names}] derived from stale pre-images; " f"re-run if non_deterministic, else re-derive against current head" ) # Phase 2: apply writes and advance the log. applied: list[str] = [] for b in branches: for resource, content in b.write_set.items(): log.snapshot(resource, content) applied.append(b.name) return applied def commit_or_repair(branches: list[Branch], log: VersionLog) -> list[str]: """Drive reconciliation to a fixed point; re-derive deterministic branches.""" for _ in range(len(branches) + 1): # bounded fixed-point iteration try: return reconcile(branches, log) except StaleReadSetError: repaired: list[Branch] = [] for b in branches: is_stale = any( log.heads.get(r) not in (None, v) for r, v in b.read_set.items() ) if not is_stale: repaired.append(b) elif b.non_deterministic or b.transform is None: raise # cannot safely re-derive; escalate to caller for re-run else: new_pre = { r: log.heads.get(r, "") for r in b.read_set } new_writes = b.transform(new_pre) repaired.append( Branch( name=b.name, read_set={r: log.heads.get(r, "") for r in b.read_set}, write_set=new_writes, transform=b.transform, non_deterministic=False, ) ) branches = repaired raise StaleReadSetError("reconciliation did not converge within iteration bound") ```