# Why does an instance roll back a speculative branch and still lose the merge: silent divergence of side-effect ledgers during speculative agent execution **Date of Record:** 2026 November 22 **Scope:** Applies to orchestrators that fork an agent's tool-use trajectory into parallel speculative branches, execute them against a shared environment, and reconcile results by rolling back losing branches and merging the winning branch's state. Does not apply to purely read-only fan-out (map over independent queries), nor to branches executed against fully isolated sandboxes whose side effects are never merged. ## Core Distinction The failure is not "the rollback failed" and it is not "the merge conflicted." It is that **rollback and merge are two separate reconciliation passes over two different representations of state** — the *effect ledger* (the ordered log of tool invocations and their external consequences) and the *agent memory* (the message/tool-result context that the LLM will condition on next). When a speculative branch is rolled back, the orchestrator typically truncates the effect ledger to a checkpoint and discards the branch's context. But the branch's *tool results* — including results from side-effecting calls that were partially applied before the checkpoint, or calls whose compensation was itself non-idempotent — may already have been folded into the surviving branch's context via a shared result cache or an append-only trace. The result is an agent that continues reasoning from evidence of actions that no longer exist in the world, while the ledger says the world is clean. The invariant that must hold — *every tool result visible in the merged context is backed by a ledger entry that survived rollback* — is violated silently, with no exception, because both subsystems individually report success. ## What Was Observed A planner agent decomposes a task ("reconcile two inventory feeds and issue corrections") into a fork point. Three speculative branches are launched from checkpoint `C0`: - **Branch A** calls `adjust_stock(sku, delta)` on 40 SKUs, then `post_correction(sku)` for each. - **Branch B** takes a different reconciliation strategy, calling `adjust_stock` on an overlapping subset of 22 SKUs. - **Branch C** is a conservative branch that only reads. The orchestrator scores branches by a verifier and selects A. Branch B is rolled back: the ledger is truncated to `C0` and B's compensation routines are invoked to reverse its 22 `adjust_stock` calls. But B's compensation for `adjust_stock` is implemented as `adjust_stock(sku, -delta)` — a *relative* compensation. Meanwhile A's `adjust_stock` calls landed on the same 22 SKUs *after* B's, so B's compensation now subtracts a delta from A's adjusted value rather than restoring the pre-B value. The ledger after rollback reports "B reversed," and A's entries are intact. The merged context, however, contains B's tool-result messages (`"stock adjusted: sku-4471 now 118"`) because the result cache was keyed by `(tool, args)` and A's identical calls hit the same cache entries — so the merged context shows B's *pre-compensation* numbers for SKUs that A also touched. The agent proceeds to `post_correction` on 22 SKUs using numbers that are now wrong by exactly B's delta, and the verifier — which checks the ledger, not the context — passes the branch. The observed trace, condensed: ``` C0 ledger: {sku-4471: 140, sku-4480: 90, ...} B executes: adjust_stock(4471, -22) -> 118 [ledger entry B.1] A executes: adjust_stock(4471, -10) -> 108 [ledger entry A.1] rollback(B): adjust_stock(4471, +22) -> 130 [compensation, entry R.1] ledger after: {4471: 130} (A.1's -10 applied to 140, then +22 from R.1) context after merge: "4471 now 118" (B.1's result, cached, reused by A.1's lookup) divergence: ledger says 130, context says 118, agent acts on 118. ``` The gap between 130 and 118 is not a rounding error; it is the entire magnitude of the compensation, and it is invisible to every component that reports health. ## Condition of Validity The invariant *"merged context ⊆ surviving ledger"* holds only when at least one of the following is true: 1. **Compensation is absolute, not relative.** Rollback restores the checkpoint value directly (`set_stock(sku, checkpoint_value)`) rather than applying an inverse delta. Relative compensation is valid only if no other branch touched the same resource between the branch's write and its rollback — a condition the orchestrator cannot generally verify without resource-level locking, which defeats the purpose of speculative parallelism. 2. **Result caches are branch-scoped.** Tool results are keyed by `(branch_id, tool, args)` or invalidated wholesale on rollback. A shared cache keyed only by `(tool, args)` will serve a rolled-back branch's result to a surviving branch whenever the arguments coincide — which is common precisely because speculative branches are *supposed* to try the same actions. 3. **The verifier reads the context, not just the ledger.** If the acceptance check validates only ledger consistency, a context/ledger divergence passes silently. In practice, production orchestrators satisfy at most one of these. The failure surface is the intersection of (relative compensation) ∧ (shared result cache) ∧ (ledger-only verification) — which is the default configuration of most speculative-execution frameworks because each choice is individually the "obvious" one. ## Decision Boundary The boundary is not "should we speculate" but **"at what resource granularity do we permit overlapping speculative writes."** Two regimes: - **Disjoint-write speculation (safe):** branches are constrained to write-disjoint resource sets, enforced by a pre-execution partition of the effect space. Rollback is trivially safe because no surviving branch's value depends on a rolled-back branch's writes. Cost: the planner must prove disjointness, which is often impossible for open-ended tasks. - **Overlapping-write speculation (unsafe without absolute compensation + branch-scoped caching):** branches may write the same resources. Here the only sound rollback is checkpoint-restore of the *value*, and the only sound cache is branch-local. If either is violated, the merge is unsound regardless of verifier scores. The decision: if the planner cannot guarantee write-disjointness **and** the tool surface does not expose absolute (set-to-value) compensation, the orchestrator must not permit overlapping speculative writes — it must serialize branches at the shared resource, or downgrade to read-only speculation with a single committed write pass. The failure above occurred because the orchestrator permitted overlapping writes while assuming relative compensation was sufficient. ## Operational Effect The downstream consequence is **silent, unbounded error compounding**. Because the divergence is between two representations that never cross-check, it is not detected at merge time; it surfaces later when a `post_correction` based on the stale context is itself verified against the (now-consistent) ledger and *fails*, or worse, when it *passes* because the correction's magnitude happens to fall within tolerance. In the observed case, 22 corrections were posted with values off by the compensation delta; 9 were caught by a downstream reconciliation job, 13 were not. The 13 are the operational residue: the agent's memory and the world disagreed, and the memory won because the verifier trusted the world. The guardrail is a **three-way consistency assertion at merge time**: for every resource touched by any branch, assert `context_value == ledger_value == checkpoint_value_plus_surviving_deltas`. This is cheap — it is a set comparison over the union of touched keys — and it converts a silent divergence into a loud, localized failure at the exact merge boundary. The assertion must run *after* compensation and *before* the surviving branch's context is handed back to the LLM, because after that handoff the divergence is laundered through the model's reasoning and becomes untraceable. ```python class SpeculativeMergeDivergence(RuntimeError): """Raised when merged agent context disagrees with the surviving effect ledger.""" pass def assert_merge_consistency( context_values: dict[str, int], ledger_values: dict[str, int], checkpoint_values: dict[str, int], surviving_deltas: dict[str, int], ) -> None: """ Enforce the invariant: every tool result visible in the merged context is backed by a ledger entry that survived rollback. context_values : resource -> value as reported in the merged tool-result context ledger_values : resource -> value after rollback + merge checkpoint_values: resource -> value at the fork checkpoint C0 surviving_deltas : resource -> net delta from branches that SURVIVED rollback """ touched = set(context_values) | set(ledger_values) for resource in touched: expected = checkpoint_values.get(resource, 0) + surviving_deltas.get(resource, 0) ctx = context_values.get(resource, expected) led = ledger_values.get(resource, expected) if ctx != led: raise SpeculativeMergeDivergence( f"context/ledger divergence on {resource}: " f"context={ctx} ledger={led} expected={expected}. " f"A rolled-back branch's tool result leaked into the merged " f"context (likely shared result cache or relative compensation)." ) if led != expected: raise SpeculativeMergeDivergence( f"ledger/checkpoint divergence on {resource}: " f"ledger={led} expected={expected}. " f"Compensation was not absolute; a surviving branch's write " f"was contaminated by a rolled-back branch's inverse delta." ) def merge_speculative_branches( winner_context: dict[str, int], ledger_values: dict[str, int], checkpoint_values: dict[str, int], surviving_deltas: dict[str, int], ) -> dict[str, int]: # Guardrail MUST run before the context is handed back to the LLM, # because after handoff the divergence is laundered through reasoning # and becomes untraceable. assert_merge_consistency( winner_context, ledger_values, checkpoint_values, surviving_deltas ) return winner_context ```