# How does an instance detect that a speculative parallel branch has already committed side effects before the merge point? **Date of Record:** 2026 November 27 **Scope:** Applies to orchestrators that fan out multiple agent branches speculatively from a shared checkpoint, execute them concurrently, and merge results deterministically with the option to roll back losing branches. Does not apply to single-threaded agent loops or to branches whose only outputs are pure text returned to the caller. ## Core Distinction Speculative branch execution assumes that a branch is *reversible* until the merge gate admits it. That assumption is false the moment a branch performs an externally visible side effect—sending an email, writing to a database, calling a non-idempotent API, mutating a shared file—before the merge decision. The orchestrator's rollback logic typically operates on *agent state* (context window, scratchpad, tool-call ledger) and treats that rollback as equivalent to *world rollback*. These are two different substrates with different reversibility guarantees. The non-obvious failure is not "a branch did a bad thing." It is that the losing branch's side effect is invisible to the merge comparator, because the comparator only inspects branch *outputs and state deltas*, not the external effect log. The merge therefore succeeds, the rollback reports success, and the system proceeds with a world state that contains effects from a branch it believes it discarded. Detection must be grounded in an effect ledger keyed to the checkpoint epoch, not in the branch's self-report. ## What Was Observed A planner agent at checkpoint C₀ fans out three speculative branches (B₁, B₂, B₃) to resolve an ambiguous user request: "update the customer record and notify them." Each branch independently interprets "notify" and "update" and proceeds. - B₁ calls `crm.update(customer_id, field="tier", value="gold")`, then `email.send(template=tier_upgrade)`. - B₂ calls `crm.update(customer_id, field="tier", value="silver")` after reading a conflicting source, then decides not to notify. - B₃ reads state, concludes the update is unsafe without confirmation, and returns a clarifying question. The merge comparator scores branches on a rubric (task completion, risk). B₁ wins. The orchestrator commits B₁'s state delta, discards B₂ and B₃, and logs `rollback: B₂, B₃ → reverted to C₀`. But B₂'s `crm.update` already executed against the live CRM before the merge gate. The rollback restored B₂'s *agent context* to C₀; it did not restore the *customer record*, which now reads `tier=silver` and was subsequently overwritten by B₁ to `tier=gold` — except the CRM emitted a tier-change audit event for the silver transition, and a downstream loyalty job keyed on that event fired. The observable symptom was not an exception. It was a duplicate audit trail and a loyalty grant for a tier the customer never legitimately held. The orchestrator's own logs showed a clean merge with successful rollback. The divergence was only visible by diffing the external effect ledger against the set of committed branches. ## Condition of Validity The invariant that makes speculative merge safe is: > For every branch B executed speculatively from checkpoint C₀, every external effect E produced by B must be either (a) buffered and not applied until B is admitted at the merge gate, or (b) recorded in an effect ledger with the branch ID and epoch, and the merge rollback must reverse every ledgered effect of every non-admitted branch before the merge is declared complete. The invariant holds only when one of these is true: 1. **Effect deferral.** All side-effecting tool calls are intercepted and staged; the branch operates against a transactional overlay that is committed only on admission. This requires the tool layer to support prepare/commit semantics, which most external APIs do not. 2. **Effect ledgering with compensating actions.** Each side effect is recorded with a reversible compensation (delete the row, send a correction, invalidate the token). Rollback runs compensations in reverse order. This requires every tool to declare a compensation, and requires the merge to block on compensation success. 3. **Effect fencing.** The branch's credentials are scoped to a sandbox that cannot reach production; effects are replayed by the orchestrator after admission. This requires credential isolation per branch and a replay mechanism. If none of these hold, the merge is *unsound*: it can admit a branch while the world contains effects from branches it discarded. The failure is silent because the state-level rollback succeeds and reports success. ## Decision Boundary An instance must treat a branch as *unsafe to speculate* — and serialize it instead of fanning out — when any of the following is detected at branch admission time: - A tool in the branch's declared toolset has `reversible=False` and no compensation registered. - The branch's first action reads external state that another concurrent branch may write (a write-write or read-write hazard across branches on the same resource key). - The branch has exceeded its effect budget (number of ledgered effects) before reaching the merge gate, indicating it is acting rather than exploring. - The merge comparator's rubric cannot be evaluated without the branch's effects having already occurred (i.e., the branch's value is only observable post-effect). This is the subtle case: some branches *must* act to be evaluated. Those branches cannot be speculative; they must be sequenced with explicit user or policy confirmation. Conversely, a branch is safe to speculate when its toolset is fully deferrable or fully compensable *and* its resource keys are disjoint from every other concurrent branch. The boundary is resource-key disjointness plus effect reversibility, not task similarity. ## Operational Effect The practical consequence is that the orchestrator must maintain an **effect ledger** as a first-class artifact, separate from the agent state checkpoint, and the merge operation must be a two-phase commit over that ledger: 1. **Prepare:** every branch records intended effects; deferrable effects are staged, non-deferrable effects are executed and ledgered with compensations. 2. **Decide:** the comparator selects the winning branch. 3. **Commit:** the winner's staged effects are applied; the losers' ledgered effects are compensated in reverse order. 4. **Verify:** the ledger is diffed against the applied world state; any uncompensated loser effect aborts the merge and escalates. The verification step is what catches the failure above. Without it, the orchestrator has no way to distinguish "rollback succeeded" from "rollback succeeded at the state layer while the world diverged." The detector is a set difference: `ledgered_effects(losers) − compensated_effects(losers) ≠ ∅` implies an unsound merge, and the instance must halt rather than proceed. The cost is that speculative fan-out becomes strictly less parallel: branches sharing resource keys must be serialized or fenced, and branches with irreversible tools cannot speculate at all. This is the correct trade. Parallelism that silently corrupts external state is not parallelism; it is uncontrolled concurrent mutation with a merge log that lies. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class MergeSoundnessError(RuntimeError): """Raised when a speculative merge would admit a branch while uncompensated effects from a discarded branch remain in the world.""" class EffectState(Enum): STAGED = "staged" # deferrable, not yet applied APPLIED = "applied" # executed against external world COMPENSATED = "compensated" # reversed after discard @dataclass class Effect: branch_id: str resource_key: str compensation: Optional[str] # None => irreversible state: EffectState = EffectState.STAGED @dataclass class EffectLedger: effects: list[Effect] = field(default_factory=list) def record(self, effect: Effect) -> None: if effect.state is EffectState.APPLIED and effect.compensation is None: raise MergeSoundnessError( f"branch {effect.branch_id} applied irreversible effect on " f"{effect.resource_key} with no compensation" ) self.effects.append(effect) def uncompensated_for(self, branch_ids: set[str]) -> list[Effect]: return [ e for e in self.effects if e.branch_id in branch_ids and e.state is EffectState.APPLIED ] def verify_merge(ledger: EffectLedger, winner: str, losers: set[str]) -> None: """Two-phase merge guard. Must run before the merge is declared complete.""" # Phase 1: compensate every applied effect of every losing branch. for effect in ledger.uncompensated_for(losers): if effect.compensation is None: raise MergeSoundnessError( f"cannot roll back branch {effect.branch_id}: irreversible " f"effect on {effect.resource_key}" ) # invoke compensation out-of-band; assume it succeeds or raises effect.state = EffectState.COMPENSATED # Phase 2: verify the world no longer carries loser effects. residual = ledger.uncompensated_for(losers) if residual: raise MergeSoundnessError( f"merge unsound: {len(residual)} uncompensated effect(s) from " f"discarded branches {sorted({e.branch_id for e in residual})} " f"remain after rollback of winner {winner}" ) # Phase 3: admit winner's staged effects. for effect in ledger.effects: if effect.branch_id == winner and effect.state is EffectState.STAGED: effect.state = EffectState.APPLIED ```