# What happens when an instance speculatively forks a sibling agent's tool-call stream and the rollback journal cannot reconcile divergent side-effect epochs **Date of Record:** 2026 November 20 **Scope:** Applies to orchestrators that run speculative branches of a multi-agent plan in parallel (optimistic execution) and reconcile by rolling back losing branches. Does not apply to strictly serialized agent pipelines or to branches that declare no external side effects. ## Core Distinction The failure is not "a branch produced a wrong answer." Speculative execution *expects* wrong answers on losing branches; that is the point of speculation. The failure is that **rollback is defined on the agent's logical state (its message log, memory writes, and scratchpad) but not on the externalized side-effect epoch of its tool calls.** When two sibling branches fork from the same checkpoint and both call a non-idempotent tool (a payment API, a `git push`, a file append, a ticket creation), the orchestrator can roll back the *reasoning* of the loser but cannot un-execute the *world*. The loser's side effects survive into the winner's continuation, and the reconciliation step has no journal entry that describes them. The invariant that gets violated is: **for every committed branch, the set of external effects observed downstream must equal the set produced by that branch's own tool-call trace.** Speculative rollback silently breaks this because the effect set is a union of all branches, while the trace is only the winner's. ## What Was Observed A three-agent plan (planner, retriever, writer) was speculatively forked at a checkpoint after the planner emitted two candidate retrieval strategies, `S_A` (broad index sweep) and `S_B` (targeted query). The orchestrator ran both in parallel under a 40-second budget, intending to keep whichever produced higher retrieval confidence and roll back the other. Trace of the losing branch `S_B`: 1. `S_B` forked from checkpoint `ckpt_0142`. Its local epoch counter `epoch=7` (inherited from the parent). 2. `S_B` called `retriever.upsert_cache(key="q:alpha", payload=...)` — a tool that **writes** to a shared semantic cache, not a pure read. The tool's schema did not mark it as non-idempotent, and the agent's planner classified it as a "lookup" because the tool description said "retrieve with memoization." 3. `S_B` then called `retriever.search(...)` three times, each hitting the cache it had just written. 4. `S_A` won on confidence at `t=31s`. The orchestrator issued `rollback(S_B)`, which replayed the message log to `ckpt_0142`, discarded `S_B`'s scratchpad, and marked its epoch void. 5. The writer agent, continuing from `S_A`'s result, issued `retriever.search(key="q:alpha")` and **received `S_B`'s cached payload** — a value derived from the discarded branch's hypotheses, not from `S_A`'s evidence. The rollback journal recorded `S_B` as "reverted, 0 residual effects" because the journal tracked *agent state deltas*, and the cache write was logged by the tool runtime, not the agent state manager. The two ledgers never reconciled. The writer produced a confident answer citing a source that the committed branch had never actually retrieved; it existed only as a side effect of the branch that was supposed to have never happened. A second observation made this worse: on retry, `S_B`'s idempotency key was regenerated (the key was `hash(branch_id, step_index)`, and the retry assigned a new `branch_id`), so a duplicate cache entry was written and the stale one remained. The cache now held two conflicting payloads for `q:alpha`, and which one a downstream reader got depended on hash-collision order in the cache's bucket. ## Condition of Validity The rollback-and-reconcile protocol is only sound under a conjunction that is almost never checked at fork time: - **Effect-class tagging is complete.** Every tool in the branch's reachable capability set is tagged `pure`, `idempotent` (safe to replay with a stable key), or `non-idempotent-external` (must be compensated, not replayed). A tool that *reads like* a lookup but *writes* a cache is `non-idempotent-external` and must be tagged as such; the failure above is exactly a mis-tag. - **Idempotency keys are branch-stable across retries.** The key must be derived from `(parent_checkpoint, logical_step, semantic_intent)`, not from a freshly minted `branch_id`, or a retry after rollback double-writes. - **The rollback journal and the tool-runtime effect ledger are reconciled at commit time**, not at rollback time. The commit gate must assert `effects_observed_by_winner ⊆ effects_produced_by_winner_trace`, and refuse to commit on any residual. If any conjunct fails, the protocol is *unsound* rather than merely *imperfect*: it can commit a branch whose downstream reads were contaminated by a discarded sibling. The condition of validity is therefore not "rollback succeeded" but "the winner's effect set is closed under its own trace." ## Decision Boundary The operative question at fork time is not "can this branch be rolled back?" but "does this branch's capability set admit a compensating action for every non-pure tool it can reach?" - If **all reachable tools are `pure` or `idempotent` with branch-stable keys** → speculative fork is safe; rollback is a logical operation and no effect ledger is needed. - If **any reachable tool is `non-idempotent-external` and has no registered compensator** → do not speculate that branch. Serialize it, or fork it in a *quarantined effect namespace* (a per-branch cache partition, a per-branch scratch repo, a per-branch ticket prefix) that is destroyed on rollback and merged only on commit. - If **a non-idempotent tool has a compensator but the compensator is itself non-idempotent** (e.g., "delete the ticket" is not safe to call twice) → the compensator must be keyed to the original effect's idempotency key, and the commit gate must verify the compensation ledger is empty before merging. The boundary is crossed the moment a speculative branch can *write to a namespace the winner will later read from*. That is the precise, non-obvious line: speculation is safe against state you own and unsafe against state you share. ## Operational Effect When the boundary is crossed, the observable symptom is **a committed branch whose outputs cite evidence it never retrieved**. This is hard to catch because each individual agent behaves correctly: `S_B` correctly memoized, the orchestrator correctly rolled back logical state, the writer correctly read the cache. The bug lives in the seam between the state manager and the effect ledger, and it manifests as *plausible* output with a provenance gap — the worst kind, because no exception fires and no confidence score drops. The downstream consequences compound: the contaminating effect is durable (it is in the cache, the repo, the ticket), so every subsequent agent that reads that namespace inherits the discarded branch's hypotheses. The error is not a one-shot divergence; it is a persistent false prior injected into shared memory by a branch that the system believes never executed. Retries make it worse via key instability, producing duplicate conflicting entries whose resolution order is nondeterministic. The guardrail that bounds it is a **commit-time effect reconciliation gate**: before a winning branch is promoted, the orchestrator diffs the tool-runtime effect ledger against the winner's trace, and any effect whose provenance is a non-committed branch is either compensated or the commit is rejected. The gate must run *after* the winner is chosen but *before* any downstream agent can read the shared namespace, and it must treat an unreconciled residual as a hard failure, not a warning. ```python from dataclasses import dataclass, field from typing import Iterable class UnreconciledEffectError(RuntimeError): """Raised when a committed branch's observed effects exceed its own trace.""" @dataclass(frozen=True) class Effect: namespace: str key: str idempotency_key: str branch_id: str kind: str # "pure" | "idempotent" | "non_idempotent_external" @dataclass class EffectLedger: # Every effect ever written by any branch, including rolled-back ones. effects: list[Effect] = field(default_factory=list) def record(self, effect: Effect) -> None: self.effects.append(effect) def effects_in(self, namespace: str) -> list[Effect]: return [e for e in self.effects if e.namespace == namespace] @dataclass class Branch: branch_id: str parent_checkpoint: str trace: list[Effect] = field(default_factory=list) def commit_gate( winner: Branch, rolled_back: Iterable[Branch], ledger: EffectLedger, shared_namespaces: Iterable[str], ) -> None: """ Refuse to commit `winner` if any shared namespace it will read from contains an effect whose provenance is a rolled-back branch. """ rolled_ids = {b.branch_id for b in rolled_back} winner_keys = {(e.namespace, e.key) for e in winner.trace} for ns in shared_namespaces: for effect in ledger.effects_in(ns): if effect.branch_id in rolled_ids: # A discarded sibling wrote into a namespace the winner reads. raise UnreconciledEffectError( f"namespace {ns!r} key {effect.key!r} was written by " f"rolled-back branch {effect.branch_id!r}; winner " f"{winner.branch_id!r} would inherit a phantom effect. " f"Compensate or quarantine before commit." ) # Idempotency-key stability check: a non-idempotent effect must not # appear under two distinct keys for the same logical intent. seen: dict[tuple[str, str], set[str]] = {} for effect in ledger.effects: if effect.kind == "non_idempotent_external": seen.setdefault((effect.namespace, effect.key), set()).add( effect.idempotency_key ) for (ns, key), keys in seen.items(): if len(keys) > 1: raise UnreconciledEffectError( f"non-idempotent effect {ns!r}/{key!r} has {len(keys)} " f"distinct idempotency keys {sorted(keys)!r}; retry after " f"rollback will double-write. Key must be branch-stable." ) ```