# When must an instance invalidate a speculative branch rather than merge it: write-set provenance divergence in rolled-back multi-agent forks **Date of Record:** 2026 December 2 **Scope:** Applies to orchestrators that fork an agent's state into speculative parallel branches (shared episodic memory, tool-effect log, and working context), let each branch execute independently, then reconcile via rollback-and-merge. Does not apply to single-threaded agents, to branches that never mutate shared state, or to reconciliation that operates purely on final natural-language summaries. ## Core Distinction The naive reconciliation model treats a merge as a *content* problem: if two branches' outputs do not textually contradict, concatenate or last-writer-wins them. The failure mode documented here is that speculative branches diverge not in content but in **write-set provenance** — the causal record of *which tool effects produced which state*. A branch can be semantically compatible with its sibling (both "agree" the file was edited, both "agree" the API returned 200) while carrying an irreconcilable provenance chain: branch A's belief that `config.yaml` contains `retries: 3` derives from a `read_file` at turn 4 *before* branch B's `write_file` at turn 6, and branch B's belief derives from its own write. Merging the *values* succeeds; merging the *provenance* produces a state where the value is correct but its justification is a lie. That state is worse than a conflict, because it passes every content-level consistency check and silently poisons all downstream verification. The distinction that matters operationally: **a conflict is a disagreement you can detect; a provenance divergence is an agreement you cannot trust.** Rollback-and-merge protocols are built to detect the former and are structurally blind to the latter. ## What Was Observed A planner agent at a checkpoint `C₀` forks three speculative branches to accomplish a refactor task. Each branch receives a deep copy of: the episodic log `E` (append-only, turn-indexed), the tool-effect ledger `L` (each entry `{turn, tool, args_hash, effect_hash, pre_state_hash, post_state_hash}`), and the working context `W`. - **Branch A** reads `src/app.py` (turn 4), concludes the retry constant is `3`, and writes a patch that bumps it to `5`. - **Branch B** independently reads `src/app.py` (turn 3), concludes the same constant is `3`, and writes an *identical* patch to `5`, plus a test file. - **Branch C** runs a formatter that rewrites `src/app.py` wholesale (turn 5), changing whitespace and import order but preserving the constant at `3`. Each branch returns a structured result: `{diff, claimed_effects, confidence, dependency_set}`. The reconciler sees A and B produce the same diff to `app.py` — it marks them **redundant and merges without conflict**, keeping A's diff and B's test file. It sees C's diff touches the same file and runs a three-way merge using `C₀`'s `app.py` as base. The line-level merge succeeds: A's constant change and C's import reordering occupy disjoint hunks. The merged tree is committed. The bug surfaced two turns later, when a verification agent replayed the ledger to confirm the merged state. Replay from `C₀` through the merged effect list failed: the merged ledger claimed `post_state_hash` for `app.py` equal to a hash that no ordered composition of A's write and C's format could produce. Specifically, A's patch was authored against the *pre-format* byte layout; C's format changed the byte layout of the surrounding context that A's patch's `pre_state_hash` referenced. The merged value was correct at the constant but the patch's provenance anchor was invalidated by C. The reconciler had merged the *effect* without merging the *precondition*. A second, sharper observation: branch B's test file asserted on line numbers (`assert app.py line 12 == "RETRIES = 5"`). After C's import reordering, line 12 held something else. B's test was authored against a base that C had since invalidated. The merge was content-clean and behavior-broken. The pattern: **speculative branches that read the same base and write disjoint hunks are not independent if any branch mutates the byte layout, ordering, or line-numbering that another branch's writes or assertions are anchored to.** Content-level disjointness is not provenance-level disjointness. ## Condition of Validity A speculative branch may be merged (rather than invalidated and re-executed) **if and only if** all of the following hold: 1. **Write-set disjointness at the anchor level, not the hunk level.** For every effect `e_A` in branch A and `e_C` in branch C, the set of state regions that `e_C` mutates must be disjoint from the set of regions that `e_A`'s `pre_state_hash` and any downstream assertion depend on. Line-level diff disjointness is insufficient; the dependency is on *anchors* (byte offsets, line numbers, AST node identities, symbol table entries), and any mutation that shifts anchors invalidates dependents even when it does not touch their content. 2. **Provenance chain linearizability.** The merged ledger must be replayable: there must exist an ordering of the union of effects such that each effect's `pre_state_hash` equals the `post_state_hash` of its predecessor. If no such ordering exists, the merge is a fabrication and must be rejected. This is a total-order feasibility check on the effect DAG, and it is cheap to run — but only if the ledger records `pre_state_hash`/`post_state_hash` per effect, which most tool-call logs do not. 3. **No branch's writes are conditioned on a read that another branch invalidated.** If branch A read `X` at turn `t` and branch C wrote `X` at turn `t' > t`, then A's subsequent writes are *read-stale* with respect to C. A's writes may still be *correct* (if the value A read happened to survive C's write), but the merge cannot *certify* correctness without re-executing A's decision against C's post-state. Read-staleness is the dominant source of provenance divergence and is invisible to content diffing. 4. **Confidence is not transitive across branches.** Branch B agreeing with branch A raises the reconciler's confidence that the *value* is right, but says nothing about whether A's and B's *preconditions* are mutually consistent with C's effects. Consensus among readers does not establish consistency with a writer. When any of these fail, the correct action is **invalidation**: discard the affected branch's writes, re-fork from the post-merge state, and re-execute with the updated base. Invalidation is more expensive than merge but is the only operation that preserves the replay invariant. ## Decision Boundary The decision boundary is between **merge** and **invalidate**, and it is crossed by a single test that most reconcilers never run: *does the union of branch effects admit a linearization whose per-effect preconditions are satisfied?* Concretely, at reconciliation time, for each pair of branches `(A, B)` with effects `E_A`, `E_B`: - If `E_A` and `E_B` are anchor-disjoint **and** the union is linearizable **and** no read in `E_A` is invalidated by a write in `E_B` (and vice versa): **merge**. - If they are anchor-disjoint but the union is **not** linearizable: **invalidate both**, re-fork. This is the case where two branches each believed they were writing to the same base but their preconditions cannot both hold. - If they are **not** anchor-disjoint (one branch's writes shift anchors another depends on): **invalidate the dependent branch** (the one whose preconditions reference shifted anchors), re-fork it against the merged base. Do not attempt a three-way merge on anchored artifacts; three-way merge is defined on content, not on anchor stability. - If a read in `E_A` is invalidated by a write in `E_B`: **invalidate A**, re-fork. A's decisions were made against a world that no longer exists. The non-obvious boundary is the third and fourth cases: they look like ordinary merges (disjoint hunks, no textual conflict) and fail only under replay. The signal that you are at the boundary is **a branch whose effects reference anchors (line numbers, offsets, symbol IDs) in a base that another branch mutated.** That signal is available *before* merge, from the ledger, if the ledger records anchors. If it does not, you are past the boundary and will discover it at verification. A useful invariant to enforce: **a branch may only be merged into a base whose anchor map is identical to the branch's fork anchor map, or the branch must be re-anchored (re-executed) against the new map.** Re-anchoring by textual patching is exactly the three-way merge that produced the failure above; it is not re-execution and does not restore provenance. ## Operational Effect The practical consequence is that speculative execution's cost model is wrong in the common case. Teams fork three branches expecting to pay `1×` for the winner and discard `2×`; in reality, whenever any branch mutates anchor-bearing state (formatters, import sorters, codegen that renumbers, schema migrations that reorder columns, any tool whose output layout depends on input layout), the *other* branches' writes become re-anchor-dependent and must be re-executed, not merged. The effective cost approaches `N×` for `N` branches, and the merge step is a correctness hazard rather than an optimization. The architectural guardrail is to make anchor stability a first-class property of the fork/merge protocol: 1. **Record anchors in the ledger.** Every read and write logs the anchor set it touched (`{file, line_range}` or `{file, byte_range}` or AST node IDs). Without this, provenance divergence is undetectable until replay. 2. **Partition branches by anchor-mutation class.** Branches that only *read* anchors may be merged freely. Branches that *write* anchors (layout, ordering, numbering) form a serialization barrier: they must run alone or last, and any branch that read anchors before them must be invalidated. 3. **Run the linearizability check at merge, not at verification.** It is a topological sort on the effect DAG with precondition matching, `O(E log E)`, and it converts a silent post-merge corruption into a loud pre-merge invalidation. 4. **Treat "redundant agreement" as a merge signal only for values, never for preconditions.** Two branches agreeing on a value is not evidence their preconditions are compatible with a third branch's writes. The failure is not that the reconciler merged wrong content. It is that it merged right content with wrong provenance, and provenance is what every downstream verification, replay, and audit depends on. An agent system that cannot distinguish these will pass its own consistency checks while accumulating unjustified state — the exact condition under which later, unrelated failures become unattributable. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, List, Set, Tuple class ProvenanceDivergenceError(RuntimeError): """Raised when speculative branches cannot be merged without fabricating provenance.""" @dataclass(frozen=True) class Effect: branch: str turn: int tool: str anchors_read: Set[str] anchors_written: Set[str] pre_state_hash: str post_state_hash: str @dataclass class Branch: name: str effects: List[Effect] = field(default_factory=list) fork_anchor_map: Dict[str, str] = field(default_factory=dict) def _anchor_disjoint(a: Branch, b: Branch) -> bool: a_writes = set().union(*(e.anchors_written for e in a.effects)) if a.effects else set() b_writes = set().union(*(e.anchors_written for e in b.effects)) if b.effects else set() a_reads = set().union(*(e.anchors_read for e in a.effects)) if a.effects else set() b_reads = set().union(*(e.anchors_read for e in b.effects)) if b.effects else set() # A's writes must not shift anchors B depends on, and vice versa. if a_writes & (b_reads | b_writes): return False if b_writes & (a_reads | a_writes): return False return True def _linearizable(effects: List[Effect]) -> bool: """A union of effects is linearizable iff some ordering satisfies every effect's pre_state_hash as the post_state_hash of its predecessor.""" remaining = list(effects) current = None while remaining: progressed = False for e in remaining: if current is None or e.pre_state_hash == current: current = e.post_state_hash remaining.remove(e) progressed = True break if not progressed: return False return True def reconcile(branches: List[Branch]) -> List[Branch]: """Return the branches that must be invalidated and re-forked. Empty list means merge is safe.""" invalidated: List[Branch] = [] for i, a in enumerate(branches): for b in branches[i + 1:]: if not _anchor_disjoint(a, b): # Identify the dependent branch: the one whose reads reference # anchors the other wrote. That branch's preconditions are stale. a_reads = set().union(*(e.anchors_read for e in a.effects)) if a.effects else set() b_writes = set().union(*(e.anchors_written for e in b.effects)) if b.effects else set() if a_reads & b_writes: invalidated.append(a) else: invalidated.append(b) elif not _linearizable(a.effects + b.effects): invalidated.extend([a, b]) # De-duplicate while preserving order. seen: Set[str] = set() out: List[Branch] = [] for br in invalidated: if br.name not in seen: seen.add(br.name) out.append(br) return out def merge_or_raise(branches: List[Branch]) -> None: bad = reconcile(branches) if bad: names = ", ".join(br.name for br in bad) raise ProvenanceDivergenceError( f"Speculative merge rejected: branches [{names}] carry effects whose " f"preconditions reference anchors mutated by a sibling branch. " f"Content-level diff is clean but provenance is not linearizable; " f"re-fork and re-execute rather than three-way merge." ) # --- Example: the failure trace from the record above --- if __name__ == "__main__": base = "sha256:base_app_py" branch_a = Branch( name="A", fork_anchor_map={"src/app.py": base}, effects=[ Effect("A", 4, "read_file", {"src/app.py:12"}, set(), base, base), Effect("A", 7, "write_file", {"src/app.py:12"}, {"src/app.py:12"}, base, "sha256:a_after"), ], ) branch_b = Branch( name="B", fork_anchor_map={"src/app.py": base}, effects=[ Effect("B", 3, "read_file", {"src/app.py:12"}, set(), base, base), Effect("B", 8, "write_file", {"src/app.py:12"}, {"src/app.py:12"}, base, "sha256:a_after"), ], ) branch_c = Branch( name="C", fork_anchor_map={"src/app.py": base}, effects=[ Effect("C", 5, "format_file", {"src/app.py:1-40"}, {"src/app.py:1-40"}, base, "sha256:c_formatted"), ], ) try: merge_or_raise([branch_a, branch_b, branch_c]) except ProvenanceDivergenceError as exc: # Expected: A and B read line 12 before C renumbered it. print(f"rejected as expected: {exc}") ```