# Which invariants prevent speculative branch merge from resurrecting side effects already committed by a discarded trajectory **Date of Record:** 2026 December 2 **Scope:** Applies to orchestrators that fan out a task into N parallel speculative branches (drafters), each permitted to invoke tools optimistically, then reconcile by selecting or merging trajectories. Does not cover single-trajectory retries or human-in-the-loop approval gates, where rollback is externally arbitrated. ## Core Distinction The failure is not "a branch produced a wrong answer." It is that **rollback of a speculative branch does not roll back the world**. A discarded trajectory's *reasoning* is reversible; its *tool side effects* are not. The distinction that matters operationally is between **trajectory state** (context, partial plan, scratchpad — cheaply discardable) and **effect state** (rows written, messages sent, files mutated, remote resources provisioned — durable and observable by peers). Speculative execution is only sound when the merge step reconciles against effect state, not trajectory state. Most orchestrators reconcile the wrong one: they compare final drafts, pick a winner, and assume the losers "never happened." ## What Was Observed A three-branch fan-out on a task of the form "reconcile customer record and notify." Each branch was given the same goal and permitted to call `update_record` and `send_notification` optimistically. Branch A drafted a correct reconciliation but stalled on a slow `update_record` call and was discarded at the 12s branch timeout. Branch B produced a slightly worse reconciliation and won the merge. Branch C was abandoned early on a heuristic. The merge selected B's trajectory and replayed B's tool calls to "commit" them. Two side effects escaped the rollback: 1. Branch A's `update_record` had already committed server-side before A's timeout fired — the timeout cancelled the *await*, not the *write*. When B's commit ran, it overwrote A's write with a conflicting value derived from a *different* reconciliation. The final record was consistent with neither branch. 2. Branch C had invoked `send_notification` once before abandonment. Because C was never selected, its notification was never reconciled or deduplicated; the customer received a message referencing a reconciliation that was never committed. The orchestrator logged a clean merge. No branch reported an error. The divergence surfaced only when the customer replied to a notification whose referenced state did not exist. The trigger condition is precise: **optimistic invocation of a non-idempotent, externally observable effect, combined with a branch-selection policy that discards branches without enumerating their committed effects.** It requires (a) at least one effect that commits before the branch's cancellation propagates, and (b) a merge that treats unselected branches as effect-free. ## Condition of Validity Speculative merge is sound only under a conjunction of invariants. Violating any one converts the merge from a reconciliation into a silent corruption: - **Effect ledger completeness.** Every optimistic tool invocation must append an immutable `(branch_id, effect_id, idempotency_key, pre_state_hash, post_state_hash)` record *before* the call is dispatched, and the record must survive branch cancellation. A branch whose ledger entry is missing is treated as having unknown effects, not zero effects. - **Effect fencing.** Effects carry a branch fence token. The merge may only commit effects whose fence matches the winning branch; effects from losing branches must be either compensated (if compensable) or surfaced as conflicts (if not). There is no third option. - **Idempotency keys derived from intent, not branch identity.** If keys include `branch_id`, replaying the winner under a new branch id double-applies. Keys must hash the *semantic intent* `(task_id, target, desired_delta)` so that two branches converging on the same delta collapse to one effect. - **Merge is a transaction over the ledger, not over drafts.** The commit step must read the ledger, detect cross-branch effect overlap on the same target, and refuse to commit when overlap exists without an explicit conflict resolution. Draft comparison is necessary but not sufficient. ## Decision Boundary The boundary is **compensability of the effect class**. Classify every tool before granting optimistic invocation rights: - *Pure / read-only*: safe to speculate freely; no ledger entry needed beyond observability. - *Idempotent-writable with intent-derived keys*: safe to speculate; merge deduplicates by key. - *Compensable* (reversible via a defined inverse — e.g., a reservation with a release): safe to speculate only if the branch registers its inverse at dispatch time, so the merge can compensate losers deterministically. - *Non-compensable and externally observable* (sent messages, charged payments, dispatched physical actions): **must not be speculated**. These require a serialized commit gate: only the selected branch may invoke them, after merge. Optimism here is not a performance tradeoff; it is an unbounded correctness liability. The decision rule for the orchestrator: before fan-out, compute the set of effect classes reachable from the task's tool grants. If that set intersects non-compensable externally observable effects, disable optimistic invocation for those tools and force the branch to *propose* rather than *perform*. Everything else may proceed speculatively. ## Operational Effect With the ledger and fencing in place, the failure mode above is bounded: branch A's committed write is detected as a cross-branch overlap at merge, and the merge halts with a conflict rather than silently overwriting. Branch C's notification is either compensated (if a retraction is defined) or surfaced. The cost is a merge that can *fail loudly* — which is the point. Speculative execution trades latency for the obligation to reconcile effects; the invariant that makes the trade safe is that **no effect commits without a ledger entry, and no merge completes without reconciling every ledger entry against the winning fence.** The orchestrator must treat "a discarded branch" as "a branch whose effects are unowned," never as "a branch that did nothing." ```python from dataclasses import dataclass, field from typing import Literal EffectClass = Literal["pure", "idempotent", "compensable", "non_compensable"] class SpeculativeMergeViolation(RuntimeError): """Raised when a merge would commit over unreconciled cross-branch effects.""" @dataclass(frozen=True) class EffectRecord: branch_id: str effect_id: str idempotency_key: str target: str effect_class: EffectClass committed: bool compensated: bool = False @dataclass class EffectLedger: records: list[EffectRecord] = field(default_factory=list) def record_dispatch(self, rec: EffectRecord) -> None: # Must be durable before the tool call is dispatched. self.records.append(rec) def effects_for_target(self, target: str) -> list[EffectRecord]: return [r for r in self.records if r.target == target] def merge_branches( ledger: EffectLedger, winning_branch: str, all_branches: list[str], ) -> list[str]: """Reconcile a speculative fan-out. Returns effect_ids safe to commit. Invariant: every committed effect from a losing branch must be either compensated or escalated as a conflict. Silent overwrite is forbidden. """ losing = [b for b in all_branches if b != winning_branch] safe: list[str] = [] conflicts: list[str] = [] for target in {r.target for r in ledger.records}: effects = ledger.effects_for_target(target) committed_elsewhere = [ e for e in effects if e.committed and e.branch_id in losing and not e.compensated ] if committed_elsewhere: for e in committed_elsewhere: if e.effect_class in ("non_compensable", "compensable"): conflicts.append(e.effect_id) else: # idempotent: dedupe by intent key, safe to re-derive safe.append(e.effect_id) for e in effects: if e.branch_id == winning_branch and not e.committed: safe.append(e.effect_id) if conflicts: raise SpeculativeMergeViolation( f"merge aborted: losing-branch effects on shared targets " f"were committed and are not reconciled: {conflicts}. " f"Compensate or resolve explicitly before committing {winning_branch}." ) # Deduplicate by intent-derived key so convergent branches collapse. seen: set[str] = set() deduped: list[str] = [] for eid in safe: rec = next(r for r in ledger.records if r.effect_id == eid) if rec.idempotency_key in seen: continue seen.add(rec.idempotency_key) deduped.append(eid) return deduped def grant_optimism(tool_effect_class: EffectClass) -> bool: """Only non-observable or intent-idempotent tools may be speculated.""" if tool_effect_class == "non_compensable": raise SpeculativeMergeViolation( "optimistic invocation denied: non-compensable externally " "observable effect must be serialized behind the merge gate" ) return tool_effect_class in ("pure", "idempotent", "compensable") ```