# How does an instance detect divergent speculative branches whose merge is contaminated by non-idempotent side effects already committed by a sibling branch **Date of Record:** 2026 November 28 **Scope:** Applies to speculative multi-agent execution where a coordinator forks N branch agents from a shared checkpoint, runs them concurrently, then merges the winning trajectory and rolls back losers. Does not apply to strictly sequential single-agent retries or to branches that operate on immutable, side-effect-free state. ## Core Distinction There are two distinct notions of "divergence" in speculative branch-and-merge execution, and conflating them is the root failure. The **first** is *trajectory divergence*: two branches produce different reasoning paths, tool-call sequences, or final artifacts. This is expected, cheap to detect (compare hashes of the action log), and safely resolvable by picking a winner and discarding the loser's in-memory state. The **second** is *effect divergence*: two branches, while executing, each emit side effects against the external world (writes, sends, payments, file mutations, remote tool invocations) that are **not captured by the checkpoint** and **not reversible by rollback**. Trajectory rollback is a memory operation. Effect rollback is a distributed-systems operation that branches were never designed to perform. The boundary failure is this: **a branch can be rolled back in memory while its committed external effects persist, and the merge of the winning branch then proceeds as if the world matches its own causal history.** The winner's post-merge reasoning is now built on a false premise — that the environment reflects only its own actions — when in fact a discarded sibling has already mutated the environment. Detection of this condition is not a matter of comparing final answers. It requires tracking *effect provenance* per branch and validating that the winning branch's assumptions about world state are not contradicted by effects the loser already committed. ## What Was Observed A coordinator forked three branches from checkpoint `C0` to answer a customer-refund request. Each branch had access to a `issue_refund(order_id, amount)` tool and a `send_email(to, body)` tool. The speculative policy was: run all three, score them, merge the best, roll back the rest. - **Branch A** issued a refund of $40 and sent a confirmation email, then timed out mid-reasoning before producing its final answer. Its in-memory state was marked `TIMEOUT` and *not* selected. - **Branch B** reasoned that the refund should be $40, called `issue_refund`, received a success response, and completed. It was selected as the winner. - **Branch C** produced a different amount and was discarded. The coordinator rolled back A and C's *context state*, then merged B. B's post-merge verification step checked "was a refund issued?" by querying the tool's idempotency key store — which returned success, because B had indeed issued it. The merge was declared consistent. The actual outcome: **two refunds of $40 were issued**, one by A (committed before its timeout) and one by B. The verification passed because it only checked B's own causal chain, not the union of effects across all branches. The email sent by A also fired, so the customer received two confirmation emails for two refunds. The critical observation: the rollback of A was *complete at the memory layer* and *zero at the effect layer*. The coordinator had no representation of "A committed an effect" because A's context was discarded before its effect log was reconciled. Divergence detection compared final answers, not effect sets. ## Condition of Validity The branch-and-merge pattern is only sound under a specific invariant, which we call **effect-closed rollback**: > A branch may be rolled back if and only if the set of externally committed effects attributable to that branch, since the shared checkpoint, is empty — or has been fully compensated by an explicit inverse operation recorded in the effect log. This invariant is *not* satisfied by the common implementation, which treats rollback as `discard_context(branch_id)`. That operation closes the branch's memory but leaves its effects open. The invariant requires three things the naive implementation lacks: 1. **Effect provenance tagging.** Every tool call that mutates external state must be tagged with the branch ID and a monotonic effect sequence number, and the tag must be durably recorded *before* the effect is committed (write-ahead), not after. If the tag is written after the effect, a crash between effect and tag creates an orphan effect invisible to reconciliation. 2. **Compensation registrations.** Each effect type must declare an inverse (refund → reversal, email → cannot compensate, file write → restore prior version). Effects with no inverse (irreversible sends, external payments) must be classified `NON_COMPENSABLE` and are disallowed in speculative branches unless the branch is the sole writer. 3. **Merge-time effect reconciliation.** Before merging the winner, the coordinator must compute the union of committed effects across all branches, detect any effect not attributable to the winner, and either compensate it or abort the merge with an explicit divergence error. The winner's assumptions must be re-validated against this reconciled world state, not against its own causal chain. The naive implementation fails all three. Observed systems that "work" in testing do so because test branches rarely commit effects before being discarded — the failure is latent until a branch commits and *then* loses the race. ## Decision Boundary The decision is not "did the branches diverge?" — they always do. The decision is: **at merge time, is the winner's world-state assumption consistent with the reconciled effect set?** Formally, let `E(b)` be the set of externally committed effects of branch `b` since checkpoint. Let `W` be the winner. The merge is safe iff: ``` E(W) ⊇ (⋃_b E(b) \ Compensated) ``` That is, the winner's effects must *cover* every effect committed by any branch, after compensation. If any sibling committed an effect the winner did not also commit (and which was not compensated), the winner's post-merge reasoning is operating on a world it did not produce, and the merge must be rejected. Two boundary cases define the decision: - **Subsumption case.** If sibling A and winner B both call `issue_refund(order, 40)` with the *same idempotency key*, the effects collapse — `E(A) = E(B)` — and the merge is safe. This is why idempotency keys are load-bearing: they let effect sets intersect rather than union. Without them, every sibling's effect is a distinct commit. - **Non-subsumption case.** If A calls `issue_refund(order, 40)` and B calls `issue_refund(order, 40)` with *different* keys (or none), `E(A) ∪ E(B)` has cardinality 2, the winner covers only one, and the merge must abort or compensate A's effect. The decision boundary is therefore drawn at **effect-key equivalence**, not at trajectory similarity. Two branches with identical reasoning but different idempotency keys are effect-divergent. Two branches with wildly different reasoning but a shared idempotency key on the mutating call are effect-convergent and safely mergeable. ## Operational Effect The operational consequence is a hard ordering constraint the coordinator must enforce: 1. **Before forking**, the coordinator must enumerate every tool in the branch's capability set and classify each as `PURE`, `COMPENSABLE`, or `NON_COMPENSABLE`. A branch whose capability set contains `NON_COMPENSABLE` tools must run as the *sole* branch (no speculation) or must be given a shared idempotency namespace so all branches' mutating calls collapse to one effect. 2. **During execution**, every mutating tool call must write its `(branch_id, effect_seq, idempotency_key, inverse_ref)` record to a durable effect log *before* invoking the tool. A branch that times out mid-call leaves a `PENDING` effect record; the coordinator must resolve it (query the tool for whether the call landed) before any merge. 3. **At merge**, the coordinator computes the reconciled effect set, checks the subsumption condition, and either compensates orphan effects or raises a divergence error that halts the merge. The winner's context is *not* merged until this check passes — merging first and checking later means the winner's reasoning has already absorbed a false world model. The failure mode this prevents is subtle: the system appears to work, verification passes because it checks the winner's own chain, and the corruption only surfaces as duplicated external effects (double refunds, duplicate emails, repeated payments). These are not detectable by trajectory comparison and not recoverable by context rollback. The invariant is that **memory rollback is not effect rollback**, and the coordinator must treat them as separate operations with a mandatory reconciliation step between them. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Set class EffectClass(Enum): PURE = "pure" COMPENSABLE = "compensable" NON_COMPENSABLE = "non_compensable" class EffectDivergenceError(RuntimeError): """Raised when a merge would proceed on a world state contaminated by effects committed by a discarded sibling branch.""" pass @dataclass class EffectRecord: branch_id: str effect_seq: int idempotency_key: str effect_class: EffectClass inverse_ref: str | None = None compensated: bool = False @dataclass class Branch: branch_id: str effects: List[EffectRecord] = field(default_factory=list) def reconcile_effects(branches: Dict[str, Branch], winner_id: str) -> Set[str]: """Return the set of idempotency keys the winner must cover.""" winner_keys = {e.idempotency_key for e in branches[winner_id].effects} orphan_keys: Set[str] = set() for bid, branch in branches.items(): if bid == winner_id: continue for eff in branch.effects: if eff.compensated: continue if eff.idempotency_key not in winner_keys: orphan_keys.add(eff.idempotency_key) return orphan_keys def merge_branches(branches: Dict[str, Branch], winner_id: str) -> None: if winner_id not in branches: raise EffectDivergenceError(f"winner {winner_id!r} not among branches") orphans = reconcile_effects(branches, winner_id) if orphans: # Attempt compensation is the caller's job; here we refuse to merge. raise EffectDivergenceError( f"merge of {winner_id!r} rejected: {len(orphans)} orphan effect(s) " f"committed by discarded siblings: {sorted(orphans)}" ) # Safe: winner's effect set subsumes all sibling effects (or they were # compensated). Only now may the winner's context be merged. _commit_merge(branches[winner_id]) def _commit_merge(winner: Branch) -> None: # Placeholder for context merge; effects already reconciled. return None ```