# What happens when an instance commits a speculative branch's tool side-effects before the merge barrier resolves **Date of Record:** 2026 December 2 **Scope:** Applies to orchestrators that spawn parallel speculative plan branches (branch-and-merge trees) where branches invoke state-mutating tools (file writes, DB inserts, outbound HTTP POSTs, message sends) and the merge barrier may later discard one or more branches. Does not apply to pure-read fan-out or to branches whose tools are guaranteed idempotent and reversible. ## Core Distinction There are two independent failure surfaces in speculative branch-and-merge execution, and conflating them is the root of the bug: 1. **Decision rollback** — the orchestrator discards a branch's *reasoning trace* and its *proposed plan node*. This is cheap: drop the node from the tree, free the context, done. 2. **Effect rollback** — the branch's tool calls already mutated the world. Undoing this requires either compensation (inverse operations) or isolation (the effect was never committed to the shared world in the first place). The invariant that speculative execution *appears* to rely on is: **a branch's effects are invisible to the merge decision and to sibling branches until the branch is committed.** In practice most orchestrators implement decision rollback correctly and effect rollback not at all. The branch runs in the *same* world as its siblings, its tool calls land immediately, and the merge barrier only governs which *plan* survives — not which *writes* survive. The result is an orphaned side-effect: a write whose originating branch was discarded, now visible to the committed branch and to every downstream agent. ## What Was Observed A planner emitted a three-way speculative split at a node whose task was "reconcile the customer record." Branch A proposed *upsert with merged fields*; Branch B proposed *delete-and-recreate*; Branch C proposed *no-op, flag for human*. All three were dispatched concurrently against the same tool namespace with a 20s branch budget. - Branch B's first tool call was `records.delete(id)`. It succeeded at t=1.2s. - Branch B's second call, `records.create(payload)`, was rejected by a schema validator at t=1.4s because the payload omitted a now-required field. Branch B's local error handler retried once with the same payload, failed again, and the branch self-terminated as `FAILED`. - Meanwhile Branch A read the record at t=0.9s (pre-delete, saw the old row), built its upsert against that snapshot, and issued `records.upsert` at t=1.6s. Because the row no longer existed, the upsert fell through to an *insert* path with a partially-populated payload. - The merge barrier at t=2.1s scored the branches: A succeeded, B failed, C succeeded. The merge policy selected A (highest confidence, no human flag). B was discarded. C's flag was dropped as redundant. The committed state was Branch A's insert — built from a snapshot that Branch B had already invalidated — written on top of a delete that the merge decision had *rejected*. The final record had the delete's absence-of-prior-state combined with A's stale-snapshot field values. Three agents, one merge, and the surviving artifact was a state no single branch ever proposed. The diagnostic signature: the post-merge record matched *neither* A's intended output (which assumed the old row's `created_at` and audit fields persisted) *nor* B's (which intended a full recreate). It was a hybrid produced by interleaved unisolated effects. No branch's trace contained the bug; the bug lived in the *interleaving*, which no single trace records. ## Condition of Validity Effect isolation across speculative branches holds **only if** every state-mutating tool call from a branch is routed through one of: - a **branch-scoped overlay** (copy-on-write namespace, per-branch transaction, or per-branch sandbox) that is materialized into the shared world *only* at commit time; or - a **deferred-effect queue** where the tool call records intent and the orchestrator executes it post-merge, with the branch treating the call as provisionally successful; or - a **compensation contract** where each tool declares its inverse and the orchestrator runs inverses for discarded branches — but this is only valid if inverses are total and the world is quiescent between effect and compensation (it is not, when siblings are concurrently reading). The invariant fails the moment any branch's tool executes against shared mutable state *before* the merge barrier commits it. Concretely it fails when: (a) the tool namespace is not branch-scoped, (b) the branch budget allows a mutating call to complete before the barrier, and (c) at least one sibling reads or writes the same resource. All three held in the observed case. Remove any one and the failure is bounded. A subtler validity condition: even with branch-scoped overlays, the *merge* must reconcile write-write conflicts between committed branches. If two branches both commit effects on the same key, last-writer-wins silently discards one — the same orphaned-effect class, relocated to merge time. ## Decision Boundary The orchestrator must decide, per tool, per branch, whether the effect is **isolated** or **immediate**, and it must make this decision *before dispatch*, not at merge time. The boundary: - **Isolate** (overlay/defer) any tool whose effects are read by siblings, whose inverse is not total, or whose cost of wrong-commit exceeds the cost of deferred latency. This is the default for all mutating tools in a speculative tree. - **Execute immediately** only for tools that are provably commutative with all sibling operations and idempotent under replay (pure reads, append-only logs with dedup keys, idempotency-keyed POSTs). The failure occurs precisely when the decision defaults to *immediate* because isolation is expensive to implement, and the merge policy then assumes *isolated* semantics when scoring branches. **The merge scorer and the execution layer must agree on effect semantics; a mismatch between them is the defect.** If the scorer treats a branch as a clean proposal while the executor has already leaked its writes, the scorer is reasoning about a world that no longer exists. A guardrail that bounds this: the merge barrier must be a **barrier**, not a scoring pass — no branch's effects materialize until *after* selection, and selection must be computed from branch *proposals* (declared intents), never from observed world state, because observed world state is already contaminated by siblings. ## Operational Effect Downstream agents inherit the hybrid state as ground truth. Because no branch trace contains the interleaving, replay-based verification cannot reproduce the committed artifact: replaying Branch A alone yields a different record than replaying A after B's leaked delete. This breaks the standard verification move of "re-run the winning branch and diff" — the diff is non-empty and the discrepancy is unattributable, so auditors either accept the hybrid or escalate a false-positive integrity alarm. The durable fix is not compensation but **effect quarantine**: branch tool calls write to a branch-private staging area keyed by `(branch_id, effect_seq)`, the merge barrier selects winning branches, and a single commit phase applies staged effects in a deterministic order with conflict detection. Discarded branches' staging areas are dropped unread. The cost is latency (effects land at merge, not at call) and the requirement that tools accept a staging handle. The benefit is that "discarded branch" and "no effect" become the same thing, which is the invariant speculative execution was always pretending to have. ```python from dataclasses import dataclass, field from typing import Any class SpeculativeEffectLeak(RuntimeError): """Raised when a branch's mutating tool effect reaches shared state before the merge barrier commits it.""" pass @dataclass class StagedEffect: branch_id: str effect_seq: int tool: str key: str payload: Any @dataclass class Branch: branch_id: str staged: list[StagedEffect] = field(default_factory=list) committed: bool = False class SpeculativeOrchestrator: def __init__(self) -> None: self._staging: dict[str, list[StagedEffect]] = {} self._shared_world: dict[str, Any] = {} self._barrier_resolved = False def dispatch_tool(self, branch: Branch, tool: str, key: str, payload: Any) -> None: # Mutating tools MUST stage; a direct write before the barrier is the leak. if self._barrier_resolved is False and tool in {"records.upsert", "records.delete", "records.create"}: seq = len(self._staging.setdefault(branch.branch_id, [])) self._staging[branch.branch_id].append( StagedEffect(branch.branch_id, seq, tool, key, payload) ) return # Non-mutating or post-barrier path writes through. self._shared_world[key] = payload def resolve_barrier(self, branches: list[Branch], winner_id: str) -> None: winners = [b for b in branches if b.branch_id == winner_id] if len(winners) != 1: raise SpeculativeEffectLeak( f"merge selected {winner_id!r} but {len(winners)} matching branches exist; " "selection is ambiguous and staged effects cannot be attributed" ) winner = winners[0] # Conflict detection: two committed effects on the same key is a write-write hazard. seen: dict[str, str] = {} for eff in self._staging.get(winner.branch_id, []): if eff.key in seen: raise SpeculativeEffectLeak( f"branch {winner.branch_id} staged two effects on key {eff.key!r} " f"(seq {seen[eff.key]} and {eff.effect_seq}); merge cannot order them" ) seen[eff.key] = eff.effect_seq # Commit only the winner's staged effects, in seq order. for eff in sorted(self._staging.get(winner.branch_id, []), key=lambda e: e.effect_seq): self._apply(eff) winner.committed = True # Discard all other branches' staging unread — this is the whole point. for b in branches: if b.branch_id != winner_id: self._staging.pop(b.branch_id, None) self._barrier_resolved = True def _apply(self, eff: StagedEffect) -> None: if eff.tool == "records.delete": self._shared_world.pop(eff.key, None) else: self._shared_world[eff.key] = eff.payload ```