# Why does an instance rollback diverge when speculative branches share an idempotency namespace **Date of Record:** 2026 November 24 **Scope:** Applies to orchestration layers that run speculative multi-agent branches (parallel plan exploration) and reconcile them by rolling back the losing branches' tool side effects and replaying the winning plan deterministically. Does not apply to single-branch agents, to branches that touch only pure/read-only tools, or to systems where each branch owns an isolated side-effect namespace. ## Core Distinction The failure is not "rollback is hard" or "replay is non-deterministic." It is narrower: **rollback correctness and replay determinism are two separate invariants that share a hidden dependency — the idempotency key namespace — and speculative branching silently violates that dependency by making two branches mint the same key for semantically different effects.** A speculative orchestrator forks agent A into branches A₁ and A₂. Both branches call `charge_card(order=4471, amount=90)`. If the tool's idempotency key is derived from the *logical arguments*, both branches emit `idem:charge:4471:90`. The tool deduplicates: A₂'s call returns A₁'s result without performing a second charge. The orchestrator, believing A₂ succeeded independently, records A₂'s effect in its rollback journal. When the arbiter picks A₂ and rolls back A₁, the rollback calls `refund(idem:charge:4471:90)` — which refunds the single charge that A₂ is now depending on. A₂'s plan proceeds against a refunded payment. This is not a race; it is a *namespace collision between speculative siblings*, and it is deterministic, which is why replay faithfully reproduces the corruption. ## What Was Observed Trace from a payment-orchestration agent (fork width 3, tools: `charge_card`, `reserve_inventory`, `send_receipt`): 1. **Fork.** Parent plan `P` forks into `P_a` (standard shipping), `P_b` (express + partial charge), `P_c` (gift wrap). All three derive idempotency keys from `(tool, order_id, amount)`. 2. **Collision.** `P_a` and `P_b` both issue `charge_card(4471, 90)`. Key `idem:charge:4471:90` is identical. The tool executes once; the second call returns the cached success envelope with the *original* `effect_id`. 3. **Journal divergence.** The orchestrator's rollback journal now holds three entries: `(P_a, effect_id=e1)`, `(P_b, effect_id=e1)`, `(P_c, effect_id=e2)`. Two branches claim ownership of one effect. The journal has no way to express "shared effect." 4. **Arbitration.** `P_b` wins on a scoring heuristic. Orchestrator rolls back `P_a` and `P_c`. Rollback of `P_a` emits `refund(e1)`. Rollback of `P_c` emits `release(e2)`. 5. **Corruption.** `P_b` continues, calls `send_receipt(e1)` — the receipt tool validates `e1` against the ledger, finds it refunded, and either fails the branch or (worse, in tools without ledger validation) sends a receipt for a refunded charge. 6. **Replay.** The divergent-plan replayer re-runs `P_b` from its checkpoint. The replay is *deterministic* — it reproduces the refunded-charge state exactly, because the idempotency keys are stable. Determinism here is a liability: it certifies the corrupted state as canonical. The signature to look for in logs: two branch records sharing one `effect_id`, followed by a rollback whose target `effect_id` is still referenced by a live branch's continuation. The replay trace shows `charge` returning a cached envelope with a timestamp *earlier* than the branch's own fork time. ## Condition of Validity The invariant that makes speculative rollback safe is: > For every effect `e` recorded in the rollback journal, the set of branches that reference `e` must be exactly `{owner(e)}` at the moment any branch is rolled back. Speculative execution breaks this in two ways. First, **key derivation from logical arguments instead of branch identity** — if `idem_key = f(tool, args)`, siblings collide by construction. Second, **shared-effect deduplication** — even with branch-scoped keys, a tool that itself dedups on `(tool, args)` (many payment and inventory APIs do, as a safety feature) will collapse sibling calls into one effect, and the orchestrator will not know. The invariant holds only if the orchestrator either (a) mints keys as `f(tool, args, branch_id)` *and* the tool honors them without further semantic dedup, or (b) tracks effect sharing explicitly and refuses to roll back any effect referenced by more than one live branch. Option (a) fails against tools with their own dedup layer; option (b) is the only one that survives heterogeneous tools. ## Decision Boundary The orchestrator must decide, at rollback time, whether an effect is *exclusively owned*. The boundary condition is: - **Exclusive** (`refcount(e) == 1` and `owner(e)` is the branch being rolled back): roll back normally. - **Shared** (`refcount(e) > 1`): do **not** roll back. Instead, mark `e` as *contested*, demote the winning branch's dependency on `e` to *provisional*, and require the winner to re-materialize `e` under a branch-scoped key before its plan may commit. If re-materialization is impossible (the tool cannot re-execute because the original was a real-world side effect), the branch must be failed, not silently continued. The trap is treating "the tool returned success" as evidence of exclusive ownership. It is not. A cached success from a sibling is indistinguishable, at the orchestrator layer, from a fresh success — unless the orchestrator compares `effect_id` against its own journal and detects the collision. That comparison is the guardrail, and it must run *before* arbitration, not during rollback. A second boundary: replay determinism must be scoped to *branch-local* state. A replayer that replays `P_b` against the global ledger will faithfully reproduce the refunded state. A replayer that replays against a snapshot taken at `P_b`'s fork point — before `P_a`'s rollback mutated the ledger — reproduces the intended state. The snapshot boundary is the fork, not the arbitration. ## Operational Effect Without the guardrail, speculative branching produces **deterministic, replay-certified corruption**: the system's own audit trail confirms a state that no single plan would have produced. The failure is invisible to per-branch success metrics (every branch reports success), invisible to replay determinism checks (replay matches), and visible only in cross-branch effect-ownership accounting. With the guardrail, the cost is a **re-materialization tax**: contested effects force the winner to re-execute under a branch-scoped key, which for irreversible side effects means the branch fails and the orchestrator must re-fork with disjoint namespaces from the start. The architectural conclusion is that speculative execution requires **namespace isolation at fork time**, not reconciliation at rollback time — rollback is too late to know which effects were shared, because the sharing already happened silently inside the tool's dedup layer. ```python from dataclasses import dataclass, field from typing import Dict, Set class SpeculativeRollbackCollision(RuntimeError): """Raised when a rollback would orphan an effect still referenced by a live branch.""" pass @dataclass class Effect: effect_id: str owner_branch: str idem_key: str referenced_by: Set[str] = field(default_factory=set) class RollbackJournal: def __init__(self) -> None: self.effects: Dict[str, Effect] = {} self.by_idem: Dict[str, str] = {} def record(self, branch_id: str, tool: str, args: dict, effect_id: str) -> None: # Key derived from logical args, NOT branch id -> siblings collide. idem_key = f"idem:{tool}:{sorted(args.items())}" if idem_key in self.by_idem: existing = self.effects[self.by_idem[idem_key]] existing.referenced_by.add(branch_id) # shared effect, silent return eff = Effect(effect_id, branch_id, idem_key, {branch_id}) self.effects[effect_id] = eff self.by_idem[idem_key] = effect_id def rollback(self, branch_id: str) -> list: to_rollback = [] for eff in self.effects.values(): if eff.owner_branch != branch_id: continue live_refs = eff.referenced_by - {branch_id} if live_refs: raise SpeculativeRollbackCollision( f"rollback of branch {branch_id} would orphan effect " f"{eff.effect_id} (idem={eff.idem_key}) still referenced by " f"live branches {sorted(live_refs)}; re-materialize under a " f"branch-scoped key or fail the winning branch" ) to_rollback.append(eff.effect_id) for eid in to_rollback: eff = self.effects.pop(eid) del self.by_idem[eff.idem_key] return to_rollback def arbitrate_and_rollback(journal: RollbackJournal, winner: str, losers: list) -> None: for loser in losers: journal.rollback(loser) # raises on shared-effect collision ```