# Where must an instance refuse to merge a speculative branch: orphaned side-effect commits under branch-and-merge rollback **Date of Record:** 2026 December 4 **Scope:** Applies to multi-agent planners that fork a shared plan into speculative branches, execute tool calls on each branch in parallel, and merge the winning branch while discarding losers. Does not cover single-agent retry loops, pure-reasoning tree search with no external effects, or branches whose tools are strictly read-only and idempotent. ## Core Distinction The distinction that matters is between **plan state** and **effect state**. Branch-and-merge rollback is typically implemented against plan state: a branch is a copy-on-write overlay of the parent plan's step graph, and "rollback" means discarding that overlay. This is clean, deterministic, and cheap. But speculative branches do not only mutate plan state—they emit tool calls, and tool calls mutate the world. The merge operation treats the losing branches as if they never existed, while the world retains every side effect those branches already committed. The failure is not "a losing branch did work." The failure is that **the merge gate validates the winner's plan-state lineage but never validates the effect-state lineage**, so a losing branch's committed effects become orphaned: real, durable, and referenced by no surviving plan node. The invariant that must hold at merge time is that the set of committed external effects reachable from the merged plan equals the set of effects actually emitted by the winning branch's ancestry. When a loser has already flushed effects to the world, that equality is violated and the merge is unsound—even though every plan node in the winner is internally consistent. This is non-obvious because the plan merge passes all structural checks. The DAG is acyclic, the winner's preconditions are satisfied by the winner's own ancestors, and the discarded overlays are garbage-collected without error. The corruption lives entirely outside the plan representation. ## What Was Observed A three-branch speculative planner (branch A: query-then-write, branch B: write-then-verify, branch C: verify-then-query) forked from a shared parent at step 7 of a 14-step task. Each branch was assigned a token budget and an effect budget, and each was permitted to call mutating tools (`create_ticket`, `update_record`, `send_notification`) under the assumption that "speculative" meant "buffered." The buffering assumption held for plan state and failed for effects. Two mechanisms broke it: 1. **Effect flush on branch-local quorum.** Branch B's sub-planner reached its own internal verification quorum at step 11 and, because its local policy considered a verified sub-plan "committed," flushed `update_record(id=4471, status="resolved")` to the backing service immediately—before the top-level merge had even ranked the branches. The flush was not deferred to merge because the branch had no knowledge that it was speculative; speculation was a property of the *parent's* execution mode, and that mode was not propagated into the branch's tool-permission envelope. 2. **Non-transactional tool semantics.** The tool adapter for `update_record` was a plain RPC with at-most-once semantics and no rollback handle. Once the RPC returned 200, there was no compensating action recorded, because the branch's effect log was an in-memory list that the merge discarded along with the plan overlay. The merge then selected branch A, whose plan was shorter and cheaper and whose effects were a single `create_ticket`. The merged plan's effect lineage contained exactly one effect. The world contained two: A's ticket and B's record update. The record update was orphaned—no surviving plan node referenced it, no compensating action existed for it, and the task's post-conditions were evaluated against the plan lineage (which reported success) rather than the world (which now had a resolved record that the winning plan never intended to touch). A second-order observation: the orphan was not detected by the post-merge consistency check because that check compared the merged plan against the *parent's* pre-fork snapshot, and the parent snapshot predated all branch effects. The check confirmed "no plan node references an effect that doesn't exist," which is the wrong direction of the invariant. It never asked "does an effect exist that no plan node references." ## Condition of Validity The merge is sound only under a conjunction that is rarely checked explicitly: - **Effect deferral:** every mutating tool call on a speculative branch is either (a) buffered in a branch-scoped effect journal and not flushed until merge, or (b) executed against an isolated, discardable effect domain (a transaction, a sandbox namespace, a staging record) whose commit is itself the merge step. - **Speculation-mode propagation:** the branch's tool-permission envelope carries the speculation flag, so branch-local policies cannot unilaterally promote a sub-plan to "committed" and flush. A branch that does not know it is speculative will eventually behave as if it is authoritative. - **Compensating-action registration:** for any effect that cannot be deferred, a compensating action is registered in the *parent's* journal at emission time, not the branch's, so it survives branch discard. - **Bidirectional lineage check:** merge verifies both directions—every effect referenced by the merged plan exists in the world, and every world effect emitted since the fork is referenced by the merged plan or has a registered compensation. The last condition is the one that was absent. The first three are design-time; the fourth is the runtime guard that catches violations of the first three when they slip. ## Decision Boundary The decision boundary is whether a branch may emit an effect before the merge decision. Two regimes: **Deferrable effects (default).** The tool supports buffering or transactional isolation. The branch journals the intent, the merge commits the winner's journal and discards losers'. No orphan is possible because no effect reached the world pre-merge. This is the regime branch-and-merge was designed for. **Non-deferrable effects.** The tool is a fire-and-forget RPC, an external notification, a payment, or any call with no rollback handle and no isolation primitive. Here the instance must **refuse to speculate on that step**: either serialize the step outside the branch (execute it only after merge, on the winner), or require the branch to register a parent-scoped compensation before the call. If neither is possible, the branch must not fork past that step—the speculative region ends before the non-deferrable effect, and the effect is executed exactly once on the merged plan. The boundary is crossed the moment a branch's effect journal contains a flushed (not merely recorded) entry for a non-deferrable tool. At that instant the branch is no longer speculative in effect terms regardless of its plan-state label, and any subsequent merge that discards it produces orphans. ## Operational Effect When the boundary is crossed and the merge proceeds anyway, the observable signature is a **plan-world divergence that grows monotonically with branch count and effect density**. Symptoms: - Post-conditions pass against plan lineage while external state shows unintended mutations. - Retries of the same task compound orphans: each re-run forks again, and losers from prior runs are invisible to the new run's lineage check, so orphan count is superlinear in retries. - Idempotency keys, if present, are branch-scoped, so two branches updating the same record produce two distinct keys and both commit—deduplication fails precisely where it was most needed. - The failure is silent under load: more branches means more losers means more orphans, but the merge success rate stays at 100% because the merge only checks plan state. The guardrail that bounds it is the bidirectional lineage check plus speculation-mode propagation. Concretely: stamp every effect with the fork epoch and branch id at emission; at merge, reconcile the world's effect log since the fork epoch against the merged plan's referenced set; any unreferenced effect without a registered compensation aborts the merge and forces compensation before the merged plan is allowed to proceed. This converts a silent orphan into a hard merge failure, which is the correct behavior—an unsound merge must not be permitted to report success. ```python from dataclasses import dataclass, field from typing import Optional class OrphanedEffectError(RuntimeError): """Raised when a merge would discard a branch that already committed a non-deferrable effect.""" pass @dataclass class Effect: effect_id: str branch_id: str fork_epoch: int tool: str deferred: bool # True = buffered in journal, False = flushed to world compensation: Optional[str] = None @dataclass class Branch: branch_id: str plan_nodes: list = field(default_factory=list) effect_journal: list = field(default_factory=list) speculation_flag_propagated: bool = True @dataclass class MergeContext: fork_epoch: int winner: Branch losers: list world_effects_since_fork: list def merge_speculative_branches(ctx: MergeContext) -> list: # Direction 1: every effect the winner references must exist (checked elsewhere). # Direction 2: every world effect since fork must be reachable from winner # or carry a parent-scoped compensation. winner_effect_ids = {e.effect_id for e in ctx.winner.effect_journal} orphans = [] for eff in ctx.world_effects_since_fork: if eff.effect_id in winner_effect_ids: continue if eff.deferred: continue # never reached the world; not in this list anyway if eff.compensation is not None: continue # compensable; merge may proceed with compensation scheduled orphans.append(eff) if orphans: # A loser (or a mislabeled branch) flushed a non-deferrable effect. # Also catch the case where speculation mode was not propagated, which # is the upstream cause of branch-local quorum flushes. for b in ctx.losers: if not b.speculation_flag_propagated: raise OrphanedEffectError( f"branch {b.branch_id} ran without speculation flag; " f"flushed effects {[e.effect_id for e in orphans]} cannot be rolled back" ) raise OrphanedEffectError( "merge unsound: world effects without plan lineage or compensation: " f"{[ (e.effect_id, e.tool, e.branch_id) for e in orphans ]}" ) # Safe to commit winner journal; losers' deferred effects are discarded. committed = [e for e in ctx.winner.effect_journal if e.deferred] return committed def commit_winner(ctx: MergeContext) -> list: committed = merge_speculative_branches(ctx) # Only now do deferred effects reach the world. for e in committed: e.deferred = False return committed ```