# Why does an instance speculatively fork agent branches and then merge a rolled-back sibling's side effects into the surviving branch's memory **Date of Record:** 2026 November 27 **Scope:** Applies to orchestrators that reduce tail latency by speculatively forking two or more agent branches from a shared checkpoint, racing them against a wall-clock or token budget, and merging the winner's state while discarding the loser. Does not apply to single-branch execution, pure fan-out map-reduce with read-only workers, or branches that never mutate external state. ## Core Distinction There are two things an orchestrator believes it can roll back when it kills a speculative branch: *context* and *effects*. Context rollback is cheap and exact — you drop the loser's message list, tool-call transcript, and KV cache suffix and rehydrate from the checkpoint. Effect rollback is neither cheap nor exact, because effects escape the process: a `write_file`, a `POST /tickets`, an `UPDATE inventory`, a message sent to a peer agent over A2A. The boundary failure lives precisely in the gap between these two rollback classes. A branch is killed *logically* (its context is discarded, its future is cancelled) while its already-emitted effects remain *physically* present in the world and, worse, may be re-observed by the surviving branch through a shared tool surface or shared memory store. The invariant that must hold — and that most implementations silently violate — is: > **Merge safety invariant:** the merged state of the surviving branch must be a function only of effects emitted by branches that were *committed*, never of effects emitted by branches that were *rolled back*. The failure is non-obvious because it is not a crash. Both branches succeed. The winner commits. The loser is cancelled cleanly. The merge returns a coherent, well-typed state object. The corruption is semantic: the winner's memory now contains a fact that was produced by a branch that was supposed to never have existed, and downstream reasoning treats it as ground truth. ## What Was Observed A retrieval-augmented agent was asked to reconcile a customer record. The orchestrator forked two speculative branches from a checkpoint taken after the initial `get_customer` call: - **Branch A (conservative):** re-read the record, decided the address field was stale, and issued `PATCH /customer/4471 {address: ...}`. - **Branch B (aggressive):** decided the record was fine but the *account tier* was mis-set, and issued `PATCH /customer/4471 {tier: "gold"}` plus a `POST /audit/note`. Both branches ran against the same tool endpoint. Branch B finished first within the latency budget and was selected as the commit candidate by a scorer; Branch A was cancelled at the 1.8s mark — *after* its PATCH had already been acknowledged by the tool server but *before* its final reasoning step that would have written the address into its own episodic memory. The orchestrator then merged Branch B's context into the checkpoint and discarded Branch A's context entirely. Three observable consequences: 1. **Phantom effect.** The world now held `address = ` (from A) and `tier = gold` (from B), but the merged memory only recorded the tier change. The next turn's `get_customer` returned the new address, and the agent — with no memory of having written it — concluded the address had been changed by an external actor and escalated to a human review queue. 2. **Merge divergence.** The orchestrator's post-merge state hash (computed over memory + tool transcript) did not match a replay of the committed branch alone. The replay harness flagged this as nondeterminism rather than as the effect-leak it was, and the discrepancy was suppressed by a tolerance threshold. 3. **Cancellation race.** Branch A's in-flight `PATCH` was issued at t=1.71s and acknowledged at t=1.79s; the cancellation signal was delivered at t=1.80s. The window between "effect emitted" and "cancellation observed" is the leak surface, and it is bounded only by tool round-trip latency, which is exactly the quantity the speculative execution was trying to hide. The root trigger is a **cancel-after-emit race**: the branch is cancelled on the basis of its *reasoning* progress, but its *effect* progress is a separate, uncoordinated clock. The orchestrator tracked the former and assumed it implied the latter. ## Condition of Validity Speculative fork/merge is safe only under one of the following, and the orchestrator must be able to *prove* which regime it is in before forking: - **Effect isolation (strongest).** Loser branches execute against a sandboxed tool surface — an overlay filesystem, a transactional DB session that is rolled back on cancel, a mock transport that buffers outbound messages until commit. Here rollback of effects is exact and the merge invariant holds trivially. This is the only regime in which arbitrary speculative tools are safe. - **Idempotent, commutative, tagged effects (weakest acceptable).** Every effect carries a `branch_id` and a `commit_epoch`; the tool server rejects writes whose `commit_epoch` is not the currently committed one, and the memory store keys facts by `branch_id` so a rolled-back branch's facts are physically present but *unreachable* to the merged context. This converts a correctness problem into a garbage-collection problem. - **Read-only speculation.** Branches may only call tools marked `side_effect_free: true`. The moment a speculative branch is allowed to emit a mutating effect, the regime degrades and the invariant is no longer guaranteed. The condition fails — and this is the common production case — when the orchestrator forks over a *general* tool surface and relies on cancellation to undo effects. Cancellation is not rollback; it is a request to stop, delivered asynchronously, with no guarantee about effects already in flight. ## Decision Boundary The orchestrator must decide, per tool call and *before* dispatch, whether the call is speculative-safe. The boundary is: - **Fork freely** when the branch's tool manifest is entirely `side_effect_free` or runs against an isolated overlay. - **Fork with tagging** when effects are mutating but the tool server honors `commit_epoch` fencing; the merge step must then filter the loser's tagged effects out of the shared store, and the reaper must delete them, or they will surface in a later `get_customer` and re-trigger the phantom-effect escalation. - **Do not fork** when a branch would emit an untagged, non-idempotent effect with no fencing — e.g., sending an email, charging a card, calling a peer agent that itself mutates state. In this case the orchestrator must serialize, accepting the latency cost, because the alternative is a merge that cannot be made consistent. The subtle part of the boundary: the decision cannot be made at fork time from the *plan*, because the plan is probabilistic and the branch may discover a mutating tool mid-trajectory. The guard must therefore live at the tool-dispatch layer as a hard gate: a speculative branch that attempts an unfenced mutating call must be *preempted into a committed, serialized branch* (promoted, not cancelled) rather than allowed to emit and then be cancelled. Promotion is the only correct resolution of the cancel-after-emit race, because by the time the effect is in flight the branch has already won the right to exist. ## Operational Effect The practical consequences for any orchestrator implementing speculative fork/merge: 1. **Cancellation must be effect-aware.** Track a per-branch `inflight_effects` counter and a `committed_epoch`. A branch may only be cancelled when `inflight_effects == 0`; otherwise the cancellation is deferred until the effect resolves, at which point the branch is either promoted (if it emitted) or discarded (if it did not). This closes the race window at the cost of a bounded delay equal to the slowest in-flight tool call. 2. **Merge must be filtered, not concatenated.** The merge step must select facts and effects by `branch_id ∈ committed_branches`, never by "everything in the shared store." A naive concatenation of the loser's transcript into the winner's memory is the single most common source of phantom-effect escalation. 3. **Replay harnesses must hash effects, not just context.** The divergence in consequence (2) above was invisible because the harness compared message lists. It must also compare the *effect log* (tool calls with their acknowledgements and epochs) against the committed-branch-only replay; any extra effect is a leaked rollback and must fail the run. 4. **The reaper is load-bearing.** Tagged-but-rolled-back effects accumulate in the shared store. Without a reaper that deletes them at the next commit epoch, they will be re-observed by a future branch and re-enter reasoning as if they were committed. The reaper's failure mode is silent and delayed, which is why it is the most commonly skipped component. The guardrail that bounds the whole class of failures is a single assertion at the merge boundary: *the set of effects visible to the merged context must equal the set of effects emitted by committed branches.* Everything else — fencing, promotion, reaping — exists to make that assertion true. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpeculativeMergeViolation(RuntimeError): """Raised when a rolled-back branch's effects leak into the merged state.""" pass class BranchState(Enum): RUNNING = "running" COMMITTED = "committed" ROLLED_BACK = "rolled_back" PROMOTED = "promoted" # was speculative, emitted an effect, must serialize @dataclass class Effect: branch_id: str tool: str payload: dict epoch: int acknowledged: bool = False @dataclass class Branch: branch_id: str state: BranchState = BranchState.RUNNING inflight_effects: int = 0 emitted: list[Effect] = field(default_factory=list) def dispatch_mutating(self, tool: str, payload: dict, epoch: int, fenced: bool) -> Effect: """Emit a mutating effect. Unfenced speculative effects force promotion.""" if not fenced: # Cannot cancel after emit: promote to a serialized committed branch. self.state = BranchState.PROMOTED eff = Effect(self.branch_id, tool, payload, epoch) self.inflight_effects += 1 self.emitted.append(eff) return eff def acknowledge(self, eff: Effect) -> None: eff.acknowledged = True self.inflight_effects -= 1 def request_cancel(self) -> bool: """Returns True if cancellation is safe now; False if deferred.""" if self.inflight_effects > 0: return False # cancel-after-emit race: must wait or promote if self.state == BranchState.PROMOTED: return False # promoted branches are never rolled back self.state = BranchState.ROLLED_BACK return True def merge(winner: Branch, loser: Branch, shared_store: list[Effect], commit_epoch: int) -> list[Effect]: """Merge winner's context; assert no rolled-back effect is visible.""" committed = {winner.branch_id} if winner.state in (BranchState.COMMITTED, BranchState.PROMOTED): committed.add(winner.branch_id) # Reap rolled-back effects from the shared store before merge. visible = [e for e in shared_store if e.branch_id in committed and e.epoch == commit_epoch] leaked = [e for e in visible if e.branch_id == loser.branch_id and loser.state == BranchState.ROLLED_BACK] if leaked: raise SpeculativeMergeViolation( f"branch {loser.branch_id} was rolled back but {len(leaked)} " f"effect(s) remain visible: {[e.tool for e in leaked]}" ) # Invariant: visible effects == effects of committed branches only. expected = {e for e in winner.emitted if e.acknowledged} if set(visible) != expected: raise SpeculativeMergeViolation( "merge divergence: visible effect set does not match " "committed-branch effect log" ) return visible ```