# Why does an instance of a speculative branch survive rollback when its committed side effect was idempotent-on-retry but not idempotent-on-replay? **Date of Record:** 2026 November 26 **Scope:** Applies to multi-agent planners that execute speculative branches concurrently, commit irreversible external effects (writes, sends, payments, mutations) before global branch selection, and roll back losing branches by compensating transactions. Does not apply to planners that defer all side effects until after a single commit point, nor to read-only speculative fan-out. ## Core Distinction The failure is not "rollback didn't run." Rollback ran. The failure is that the compensating action and the original action were validated against *different* idempotency contracts. The commit path used **retry-idempotency** (a dedup key so a retried `POST /charge` doesn't double-charge). The rollback path assumed **replay-idempotency** (that re-executing the whole branch from the pre-branch checkpoint would converge to the same state). These are not the same property. A side effect can be perfectly safe to retry and catastrophically unsafe to replay, because replay re-derives the *dedup key itself* from non-deterministic inputs — a regenerated UUID, a re-sampled LLM tool-call argument, a `time.time()` value embedded in the payload. When a speculative branch loses and the orchestrator issues a compensation, the compensation is keyed on the branch's *recorded* effect identity. But if any auditor or recovery agent independently re-runs the branch to verify the rollback, it mints a *fresh* effect identity and the external system treats it as a new, legitimate mutation. The branch is "rolled back" and simultaneously re-committed. ## What Was Observed A three-agent planner (Planner P, Executor E, Auditor A) ran branch-and-prune over a task with two speculative branches, `B1` and `B2`, both of which touched a downstream ticketing service. Each branch was assigned a checkpoint at `t0` (pre-execution) and permitted to commit effects provisionally. Trace of the losing branch `B2`: 1. `t0` — E snapshots branch state, including the tool-call plan for `B2`: `create_ticket(summary=..., dedup_key=gen_uuid())`. 2. `t1` — E executes `B2`. The `gen_uuid()` call returns `k=7f3a...`. Ticket `T-9001` is created. Effect ledger records `(branch=B2, effect_id=T-9001, key=7f3a...)`. 3. `t2` — P prunes `B2` in favor of `B1`. Orchestrator dispatches compensation: `delete_ticket(T-9001)`. Succeeds. Ledger marks `B2` rolled back. 4. `t3` — A, verifying the rollback, replays `B2` from checkpoint `t0` to confirm the compensation was complete and no orphaned effects remain. Replay re-executes the plan. **`gen_uuid()` returns a new value `k=9c1e...`.** The ticketing service, keyed on `dedup_key`, sees an unseen key and creates ticket `T-9002`. 5. `t4` — A observes `T-9002` post-replay, concludes the rollback was *incomplete* (an effect exists for `B2`), and escalates. The orchestrator re-issues compensation for `T-9002`. Meanwhile `T-9001`'s deletion is now double-confirmed while `T-9002` is a live orphan that no ledger entry owns. The observable symptom was a **rollback that appeared to fail verification while actually having succeeded**, plus a net-new committed effect (`T-9002`) whose provenance the ledger could not attribute to any committed branch. Downstream reconciliation flagged `T-9002` as "created by an agent that was never supposed to commit," which is technically true and operationally useless. The same class of bug appeared with a payment branch where the replay re-sampled an LLM-generated `amount` argument (temperature > 0), producing a *different* charge amount under a fresh idempotency key — a rollback that re-committed at 1.4× the original value. The dedup key was correct on every individual call; the invariant that broke was "replay of a pruned branch produces zero net external effects." ## Condition of Validity The compensation-based rollback strategy is valid **if and only if** the following invariant holds for every speculative branch: > For any branch `b` and any execution `exec` of `b` from checkpoint `cp(b)`, the set of external effects produced by `exec` is a subset of the effect set recorded in the ledger for `b`, under the *same* effect identities. This is a **replay-determinism invariant**, not a retry-idempotency invariant. It holds only when every effect-identity-bearing value in a branch's tool calls is (a) derived deterministically from checkpointed state, or (b) frozen at first execution and replayed from the ledger rather than regenerated. `gen_uuid()`, `time.time()`, random sampling, and non-zero-temperature LLM argument generation all violate (a); any replay path that re-invokes the tool rather than replaying the recorded call violates (b). The invariant is *not* restored by idempotency keys, because the key is exactly the thing that gets regenerated. It is *not* restored by "dry-run" replay, because a dry-run that still invokes `gen_uuid()` to construct the request will produce a key the real service has never seen — and if the dry-run is ever promoted to a real call, or if the service treats dry-run and real identically on the dedup path, the mutation lands. ## Decision Boundary The boundary is **who owns effect-identity generation and whether replay is permitted to re-derive it.** - **Safe side of the boundary:** Effect identities are minted once at first execution, written to an append-only effect ledger, and every subsequent replay (auditor verification, recovery, retry) *reads the identity from the ledger* and passes it as an explicit argument. Replay becomes a pure function of `(checkpoint, ledger)` with no fresh entropy. Compensation is keyed on the ledger identity. A replayed branch is provably effect-neutral because it cannot mint a key the ledger doesn't already contain. - **Unsafe side:** Effect identity is generated *inside* the tool call at execution time, and any code path — auditor, recovery agent, retry wrapper — is allowed to re-execute the tool call rather than replay the recorded invocation. Here, "rollback" and "verification" are both mutation-capable, and the two mutations are keyed differently. The precise trigger for crossing the boundary: a losing branch whose tool calls contain any non-deterministic identity source, combined with a verification or recovery path that re-invokes rather than replays. Either condition alone is survivable; together they produce the phantom re-commit. The guardrail is a hard architectural rule: **pruned branches are replay-forbidden at the tool layer.** Replay must go through a recorded-invocation shim that returns the ledgered effect identity and refuses to call the live tool. Any attempt to execute a tool under a pruned branch's checkpoint must fail closed, not silently mint a new key. ## Operational Effect Without the guardrail, rollback correctness is unverifiable — the auditor's own verification is a mutation vector, so "rollback verified" and "rollback re-committed" are indistinguishable from the ledger's perspective until reconciliation. The blast radius scales with the number of verification and recovery passes: each replay of a pruned branch is a potential net-new committed effect, and each such effect triggers a compensation that itself may be replayed. In the ticketing case, a single pruned branch produced one orphan per verification pass; in a retry storm, the orphan count is unbounded and the compensations race the re-commits. The cost is not data loss on the committed branch — `B1` was fine. The cost is **orphaned effects attributable to no live branch**, which corrupt downstream reconciliation, poison the effect ledger's provenance, and cause the orchestrator to distrust its own rollback signal. Once the ledger contains effects it cannot attribute, every subsequent branch decision is made on a corrupted state view, and the planner's prune logic begins operating on phantom evidence. The fix is cheap and must be structural, not procedural: freeze effect identities at first execution, make pruned-branch replay read-only against the ledger, and fail closed on any tool invocation under a pruned checkpoint. Procedural fixes ("auditors should be careful") do not survive a non-deterministic tool call, because the entropy source is inside the call, not in the auditor's intent. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class PhantomRecommitError(RuntimeError): """Raised when a pruned branch attempts to mint a fresh effect identity.""" @dataclass class EffectLedger: # append-only: (branch_id, effect_id) -> frozen idempotency key entries: dict = field(default_factory=dict) def record(self, branch_id: str, effect_id: str, key: str) -> None: self.entries[(branch_id, effect_id)] = key def key_for(self, branch_id: str, effect_id: str) -> Optional[str]: return self.entries.get((branch_id, effect_id)) @dataclass class Branch: branch_id: str pruned: bool = False checkpoint: dict = field(default_factory=dict) def execute_tool_call( branch: Branch, ledger: EffectLedger, tool_name: str, payload: dict, replay: bool, ) -> str: """ Execute (or replay) a tool call under a branch. Invariant enforced: a pruned branch may only REPLAY a ledgered effect identity. It may never mint a fresh one, because a fresh key on a pruned branch is a net-new committed side effect that no live branch owns. """ if branch.pruned and not replay: # Attempting live execution under a pruned checkpoint: this is the # exact path that regenerates gen_uuid()/time.time() and re-commits. raise PhantomRecommitError( f"live tool call '{tool_name}' attempted under pruned branch " f"{branch.branch_id}; replay-from-ledger required" ) if replay: effect_id = payload.get("effect_id") if effect_id is None: raise PhantomRecommitError( f"replay of branch {branch.branch_id} has no ledgered effect_id" ) key = ledger.key_for(branch.branch_id, effect_id) if key is None: raise PhantomRecommitError( f"replay references effect {effect_id} absent from ledger for " f"branch {branch.branch_id}; refusing to mint a new key" ) # Pure replay: use the frozen key, do not call gen_uuid()/time.time(). return key # First execution: mint identity ONCE and freeze it in the ledger. effect_id = payload["effect_id"] key = hashlib.sha256( f"{branch.branch_id}:{effect_id}".encode() ).hexdigest() ledger.record(branch.branch_id, effect_id, key) return key def verify_rollback(branch: Branch, ledger: EffectLedger) -> None: """ Auditor verification pass over a pruned branch. Must be replay-only. If this raises, the rollback state is untrustworthy and must not be used to drive further branch decisions. """ if not branch.pruned: raise PhantomRecommitError( f"verify_rollback called on unpruned branch {branch.branch_id}" ) try: execute_tool_call( branch, ledger, tool_name="create_ticket", payload={"effect_id": "T-9001"}, replay=True, ) except PhantomRecommitError: # Rollback cannot be verified against a corrupted ledger. raise ```