# What happens when an instance speculatively forks a branch and its compensating rollback is not idempotent under replay **Date of Record:** 2026 November 27 **Scope:** Applies to orchestrators that run a planner agent which forks N speculative sub-agents against a shared external-effect surface (filesystem, ticket tracker, API mutations), then merges the winning branch and issues compensating "undo" actions for the losers. Does not apply to read-only fan-out or to branches isolated in per-branch sandboxes with no shared mutable state. ## Core Distinction Speculative execution is safe only when the *forward* effect and its *compensating* effect form an exact inverse pair. In LLM-driven agents this inverse is assumed to exist because the planner wrote a `rollback` tool call that "looks" symmetric with the `apply` call. It is not symmetric. The forward call is executed by one agent with one snapshot of intent; the rollback is executed later, by a different agent (or a replayed instance of the same one), against a mutated world, with a *reconstructed* argument set derived from a lossy trace. The boundary that fails is not "did the rollback run" — it is "was the rollback's precondition still true when it ran." Idempotency of the compensator, under a world that changed between apply and compensate, is the invariant that speculative branch-and-merge silently violates. ## What Was Observed A planner instance P forks three branches (B1, B2, B3) to resolve an ambiguous task: "assign the incident to the on-call engineer and page them." Each branch independently: 1. reads the on-call roster (non-deterministic: the roster rotates every 5 minutes), 2. issues `assign(incident, engineer)` and `page(engineer)`, 3. writes a checkpoint `{branch, engineer, page_id, pre_state}` to the shared trace bus. P commits B1 (engineer = alice). It then dispatches rollback for B2 and B3. Here is the failure trace: - B2 had assigned the incident to **bob** and paged bob, obtaining `page_id=8841`. Its `pre_state` recorded `assignee=null`. - Between B2's apply and B2's rollback, B1's commit landed and set `assignee=alice`. - B2's rollback agent reconstructs intent from the trace: "undo assign → set assignee back to `pre_state`," i.e. `assign(incident, null)`. This executes and **erases B1's committed assignment**. The rollback of a loser destroyed the winner. - B3 had paged **bob** as well (bob was on-call during B3's window, alice during B1's). B3's rollback calls `cancel_page(8841)`. But 8841 was B2's page, not B3's — B3's own `page_id` was lost because B3's checkpoint write raced with its own process exit and the trace contains `page_id: null`. The compensator used a *fuzzy-matched* page id, cancelled the wrong page, and bob was never un-paged while carol's page (B3's actual target) remained live. Two distinct boundary violations surfaced: - **Compensator-vs-commit ordering:** a loser's rollback mutated state that a winner had legitimately overwritten. The compensator's precondition (`assignee == bob`) was false at execution time, but the agent did not check it — it replayed the recorded intent blindly. - **Compensator argument reconstruction loss:** the rollback's argument (`page_id`) was recovered from an incomplete trace, and the recovery step silently substituted a plausible-but-wrong value rather than failing. Neither is a crash. Both are *successful* tool calls that return 200. The system's health checks (all rollbacks "completed") reported green while the incident was assigned to nobody and an engineer was paged for a resolved event. ## Condition of Validity The invariant that must hold for speculative branch-and-merge to be sound: > For every branch b and every effect e(b) it applied, the compensating action c(b) must be a *conditional* inverse: it executes only if the world still matches the post-state that e(b) produced, and it must carry an unforgeable, exact effect identifier minted at apply time — never one reconstructed at rollback time. Concretely, three conditions must all hold, and the observed failure required only one to break: 1. **Compare-and-compensate (CAS on rollback).** The compensator must assert `current_state == e(b).post_state` before mutating. If B2's rollback had checked `assignee == bob`, it would have seen `alice` and aborted cleanly instead of clobbering the commit. 2. **Effect identity is minted, not inferred.** `page_id` must be written to durable storage *as part of the same atomic step that issues the page*, or the page must be issued with a client-supplied idempotency key so the compensator can address it by key regardless of trace completeness. Reconstructing an id from a partial trace and "filling the gap" is the failure mode. 3. **Merge is a serialization point.** The winner must be committed *before* any loser's compensator reads the world, and the commit must bump a version that losers' CAS checks against. If B1's commit and B2's rollback can interleave, the invariant is unenforceable regardless of agent quality. ## Decision Boundary The correct decision at the orchestrator is not "roll back losers" — it is *classify each branch's effects by reversibility class before forking*: - **Reversible-and-guarded** (state with a version/CAS, idempotency-keyed external calls): safe to speculate. Rollback = conditional inverse. - **Irreversible** (sent emails, paged humans, charged cards, posted messages): *never* place these inside a speculative branch. They must be hoisted to a post-merge commit phase executed exactly once by the winner, after merge. The observed incident paged a human from inside a branch — that is the design error, and no rollback logic can undo a page that already reached a phone. - **Ambiguous** (roster reads, assignment when assignee is a mutable single field): treat as guarded; require CAS. If a planner proposes a branch containing an irreversible effect, the orchestrator must reject the fork and force the effect into the commit phase. The rollback machinery is a *safety net for reversible effects*, not a general undo log. Treating it as a general undo log is how a loser's compensator deletes a winner's commit. ## Operational Effect After this incident the orchestrator adopted three hard rules, each addressing one broken condition: - **Fork-time effect classification.** The planner's tool schema tags every tool `reversible: bool`. Forks whose branch trace contains a non-reversible tool call are refused with `SpeculationRejected`; the planner must restructure to defer the effect past merge. - **Minted effect handles.** Every mutating tool returns an opaque `effect_handle` the orchestrator persists synchronously before the branch may continue. Compensators address effects *only* by handle. A compensator that cannot find a handle for an effect it believes it applied must fail loud, not guess. - **Versioned CAS compensators.** Rollback calls carry `expected_version`; mismatch aborts the compensator and escalates to a human rather than replaying intent. The merge step increments the global version, so any loser's in-flight compensator is guaranteed to see a mismatch and abort. Net effect: speculative fan-out still runs, but the failure surface shrinks from "silent wrong-world" to "loud abort with a human in the loop," which is the only acceptable posture when the compensator's precondition can no longer be trusted. ```python from dataclasses import dataclass from typing import Optional class SpeculationRejected(RuntimeError): """Raised when a branch proposes an effect that cannot be safely compensated.""" class CompensatorPreconditionFailed(RuntimeError): """Raised when a rollback's target state no longer matches the applied post-state.""" @dataclass(frozen=True) class Effect: handle: str # minted at apply time, never reconstructed reversible: bool post_version: int # world version immediately after this effect applied @dataclass class Branch: branch_id: str effects: list[Effect] def validate_fork(branch: Branch) -> None: """Reject forks that contain irreversible effects before any side effect runs.""" for e in branch.effects: if not e.reversible: raise SpeculationRejected( f"branch {branch.branch_id} contains irreversible effect {e.handle}; " "hoist to post-merge commit phase" ) def compensate(branch: Branch, world_version: int, expected: Effect) -> None: """Conditional inverse: only mutate if the world still matches the applied post-state.""" if world_version != expected.post_version: # A winner's commit (or another rollback) moved the world; do NOT replay intent. raise CompensatorPreconditionFailed( f"branch {branch.branch_id}: effect {expected.handle} expected version " f"{expected.post_version}, world at {world_version}; aborting to avoid clobbering commit" ) # ... issue inverse addressed strictly by expected.handle ... def merge_and_rollback(winner: Branch, losers: list[Branch], world_version: int) -> int: for b in [winner, *losers]: validate_fork(b) committed_version = world_version + 1 # merge is the serialization point for b in losers: for e in b.effects: compensate(b, committed_version, e) # will abort on any version drift return committed_version ```