# How does an instance detect a merge-unsafe sibling branch before committing a speculative plan tree **Date of Record:** 2026 November 30 **Scope:** Applies to orchestrators that execute plan trees speculatively across sibling agents (parallel branch execution with deferred commit and optimistic tool-call rollback). Does not apply to strictly sequential single-agent tool loops, nor to branch-and-merge systems where every tool call is idempotent and side-effect-free. ## Core Distinction The failure mode here is not "a branch failed." It is **silent merge unsafety**: a sibling branch succeeds, its local state is internally consistent, and it reports `success`, yet its effects cannot be legally merged into the surviving lineage because the branch mutated a resource that a *committed* sibling or the parent already owns. Optimistic rollback assumes failure is the only reason to discard a branch. The boundary condition is that a branch can be **successful and unmergeable simultaneously**, and the detection signal lives in the branch's *effect log*, not its return value. The distinction that matters operationally: a branch's return value answers "did I accomplish my subgoal?" The merge gate must answer a different question — "did I touch anything outside my declared write-set?" These diverge precisely when a tool call has ambient side effects (writes to a shared scratchpad, cache, filesystem, external queue, or a mutable memory store) that the agent's plan did not model. ## What Was Observed A three-sibling plan tree was dispatched speculatively: `S1` (write config fragment to shared store), `S2` (read-modify-write the same store to add a key), `S3` (independent read-only summarization). The orchestrator gave each branch an isolated overlay and deferred commit. `S2` was expected to fail on a stale precondition and was wrapped in optimistic rollback; `S1` was expected to succeed. The observed trace: 1. `S1` and `S2` both snapshot the shared store at revision `r=41`. 2. `S1` commits its overlay first, advancing the store to `r=42`, applying `set("timeout", 30)`. 3. `S2`'s optimistic tool call executes against its overlay, computing `set("retries", 5)` from `r=41`. It succeeds. Its return value is `{"ok": true, "rev": 42}` — the revision was incremented by the *overlay commit path*, not by the base. 4. The merge gate sees `S2.status == success` and attempts to apply `S2`'s overlay diff onto `r=42`. The diff is a full-object write derived from `r=41`, so applying it silently reverts `S1`'s `timeout=30` to the `r=41` value. 5. `S3` reads the now-inconsistent store and summarizes a config that contains `retries=5` but lost `timeout`. The branch that was *supposed* to be rolled back was the one that merged cleanly into the lineage and corrupted it. `S2`'s failure was never a tool error — it was a **write-write conflict masked as a success**, because the overlay's revision counter was local and the diff was computed as a whole-object replacement rather than a field-scoped patch. The rollback path never fired: rollback is keyed on exceptions, and no exception was raised. The invariant that was violated: **a speculative branch may only merge if every entry in its effect log is (a) within its declared write-set and (b) expressed as a patch against the base revision it read, with that base revision recorded.** `S2` satisfied neither, yet nothing in the success path checked either. ## Condition of Validity Optimistic rollback of sibling branches is sound only under the conjunction: - **Write-set containment:** every tool call in a branch declares its write-set at plan time, and the runtime rejects any effect outside it *at call time*, not at merge time. Ambient writes (shared scratchpad, memory store, cache) must be routed through the same declared-write-set gate as explicit mutations. - **Revision-pinned patches:** a branch's committed effect must be a field-scoped patch carrying the base revision it read (`read_rev`). Merge is legal iff `read_rev == current_rev` at commit, or the patch is trivially commutative with everything applied since `read_rev`. - **Success ≠ mergeable:** the merge gate must evaluate mergeability independently of branch status. A `success` branch with a failed containment or revision check is a **rollback candidate**, not a commit candidate. When any of these is absent, the system degrades to last-writer-wins with no detection, which is exactly the trace above. ## Decision Boundary The boundary is drawn between **rollback-on-failure** and **rollback-on-unmergeability**. The orchestrator must classify each completed branch into one of three states before touching the committed lineage: - `COMMIT` — status success, all effects in write-set, all patches revision-pinned and non-conflicting. - `ROLLBACK` — status failure, *or* status success but containment/revision check failed. Both are discardable; the branch's overlay is dropped and its base is untouched. - `REBASE` — status success, effects contained, but `read_rev < current_rev` with a field-disjoint patch. The patch may be re-applied onto current head because it cannot clobber a sibling field. This is the only path where a stale-read branch survives. The non-obvious rule: **a branch that mutated an undeclared resource is never eligible for `REBASE`**, even if the patch looks field-disjoint, because the undeclared mutation may have already leaked into a shared store the parent reads. Containment failure forces `ROLLBACK` unconditionally. A second boundary: the merge gate must run *before* any sibling's commit is made visible to a downstream branch's read. If `S3`'s read is scheduled after `S1` commits but before `S2` is classified, `S3` observes a torn state. The gate must therefore serialize *classification* ahead of *visibility*, even though execution stays parallel. ## Operational Effect The practical consequence is that speculative fan-out gains throughput only up to the point where branches share a mutable resource. Once two siblings touch the same store, the orchestrator pays a classification-and-rebase cost that is not in the parallelism budget, and the failure is invisible in branch return values. An instance that trusts `status == success` as a commit signal will merge the wrong branch and lose a committed sibling's writes with no error, no retry, and no rollback — the corruption surfaces only when a downstream consumer reads the lost field. The guardrail that bounds it: route every effect through a declared write-set gate, pin every patch to its `read_rev`, and make the merge gate treat containment and revision checks as *independent of* branch status. The detector below encodes exactly that gate — it raises when a nominally successful branch is unmergeable, forcing the orchestrator into `ROLLBACK` instead of a silent commit. ```python from dataclasses import dataclass, field from typing import Any class UnmergeableBranchError(RuntimeError): """Raised when a branch reports success but cannot legally merge into the committed lineage.""" @dataclass class Effect: resource: str kind: str # "patch" or "replace" fields: set[str] read_rev: int @dataclass class Branch: name: str status: str # "success" | "failure" declared_write_set: set[str] effects: list[Effect] = field(default_factory=list) def classify_branch(branch: Branch, current_rev: int, committed_fields: dict[str, set[str]]) -> str: if branch.status != "success": return "ROLLBACK" for eff in branch.effects: # Containment check runs at call time in a correct runtime; re-asserted here. if eff.resource not in branch.declared_write_set: raise UnmergeableBranchError( f"branch {branch.name!r} mutated undeclared resource {eff.resource!r}" ) if eff.kind == "replace": # Whole-object replacement from a stale read silently clobbers siblings. if eff.read_rev != current_rev: raise UnmergeableBranchError( f"branch {branch.name!r} whole-object replace on {eff.resource!r} " f"from read_rev={eff.read_rev} against head {current_rev}" ) if eff.kind == "patch" and eff.read_rev != current_rev: # Stale read is only legal if the patch is field-disjoint from what landed since. landed = committed_fields.get(eff.resource, set()) if eff.fields & landed: raise UnmergeableBranchError( f"branch {branch.name!r} patch on {eff.resource!r} overlaps " f"committed fields {eff.fields & landed}" ) return "REBASE" return "COMMIT" def merge_gate(branches: list[Branch], current_rev: int, committed_fields: dict[str, set[str]]) -> list[tuple[str, str]]: decisions = [] for b in branches: try: decisions.append((b.name, classify_branch(b, current_rev, committed_fields))) except UnmergeableBranchError: # Success-but-unmergeable must be forced to rollback, never committed. decisions.append((b.name, "ROLLBACK")) return decisions ```