Why does an instance roll back a speculative branch only to replay it into the same poisoned state: idempotency-key aliasing across speculative forks
**Date of Record:** 2026 December 1 **Scope:** Applies to multi-agent systems where a planner forks speculative execution branches (parallel tool-calling subagents, speculative decoding of plans, or optimistic parallel tool calls) and reconciles them via rollback-and-replay on the winning branch. Does not apply to strictly sequential single-agent loops or to systems where every tool call carries a fresh, server-issued nonce.
Core Distinction
The failure is not "the rollback didn't happen." Rollback of *local agent state* (context segments, scratchpad, working memory) is usually correct. The failure is that rollback is treated as *global*, when in fact side-effecting tool calls executed on a losing branch have already mutated external state that the replaying branch re-encounters under the *same idempotency key*. The distinction that matters: **fork identity ≠ effect identity**. Two speculative branches that diverge in reasoning may still emit tool calls carrying the same derived idempotency key, because the key is computed from a stable prefix (task ID + step index) rather than from the branch's actual lineage. When the losing branch's effect lands first and the winning branch replays, the tool's dedup layer returns the *losing branch's* cached result — the winner inherits the loser's side effect.
This is distinct from ordinary replay discrepancy: the bug is not that replay produces a different answer, it is that replay produces the *wrong branch's* answer, silently, with a 200 OK.
What Was Observed
A three-branch speculative fan-out (branches `A`, `B`, `C`) on a document-mutation task. Each branch planned independently and issued a `write_record` tool call. The idempotency key was derived as `sha256(task_id + "::" + str(step_index))` — a deterministic function of the *shared* plan prefix, not the branch. All three branches therefore emitted the *same* key for their first write.
Trace:
- Branch `B` and `C` were killed by the reconciler as losers at step 3 (divergent plan confidence). Branch `A` was selected.
- `B`'s in-flight `write_record` (issued at step 2, before the kill signal propagated) completed at the tool server and was cached under key `K = sha256(task::0)`.
- `A` reached step 2 on replay and called `write_record` with the same key `K`.
- Tool dedup layer returned `{"status": "ok", "cached": true, "record_id": "rec_881"}` — `rec_881` was `B`'s write, containing `B`'s payload (a different field set, because `B` had inferred a different schema from the same context).
- `A`'s context now contained a tool result claiming success for a write whose payload it never authored. Downstream steps in `A` reasoned over `rec_881`'s fields, which were inconsistent with `A`'s plan.
The reconciler's invariant — "winning branch's external effects are exactly those the winner intended" — was violated with no error surfaced. The only observable signal was a later schema-validation failure two steps downstream, misattributed to `A`'s reasoning rather than to the aliased write.
Condition of Validity
The rollback-and-replay safety property holds **iff** every side-effecting tool call's idempotency key is a function of the *branch lineage*, not the shared plan prefix. Formally: for branches `b_i ≠ b_j`, `key(b_i, step) ≠ key(b_j, step)` for all `step` at which both branches may emit effects. The observed system satisfied `key = f(task, step)` which is constant across `i`, so the property fails at the first step where two branches both emit a side-effecting call.
Secondary condition: the tool server's dedup cache must not be consulted across branch boundaries during reconciliation. If the reconciler cannot distinguish "cached from my own prior attempt" from "cached from a sibling branch," it cannot honor the invariant even with distinct keys — it will still accept a foreign result as its own.
Decision Boundary
When a speculative fork is created, the system must choose between:
- **Lineage-keyed effects (safe):** derive idempotency keys from `hash(task_id + branch_id + step_index)`. Losing branches' effects are orphaned, not aliased. Requires the tool server to accept arbitrary keys and requires a compensating delete/supersede pass for orphaned effects, or acceptance of write amplification.
- **Prefix-keyed effects (unsafe under fork):** derive from `hash(task_id + step_index)`. Cheap, dedup-friendly, but only valid if at most one branch can emit a given step's effect — i.e., if the fork is *speculative read-only* until reconciliation commits.
The boundary is: **prefix-keying is only valid when the fork is read-only.** The moment a speculative branch is permitted to emit a side-effecting call before commit, prefix-keying aliases effects and the rollback invariant is unenforceable. The system under observation crossed this boundary by allowing `write_record` on uncommitted branches while retaining prefix-keyed dedup.
Operational Effect
The failure is silent and *self-concealing*: the wrong-branch result is returned as a success, so the winning branch's context is poisoned with a plausible but foreign tool result. Downstream reasoning diverges from the winner's own plan, and the divergence is attributed to model error rather than to reconciliation. Recovery requires either (a) lineage-keying plus an orphan-sweep, or (b) a commit barrier that forbids side-effecting calls on uncommitted branches — with the guardrail that any `write_*` tool invoked on a branch whose `branch_id` is not the reconciler's committed winner must raise, not silently dedup.
import hashlib
from dataclasses import dataclass, field
from typing import Optional
class SpeculativeEffectAliasingError(RuntimeError):
"""Raised when a side-effecting tool call on a speculative branch would
alias its idempotency key with a sibling branch's effect."""
pass
@dataclass
class Branch:
branch_id: str
committed: bool = False
@dataclass
class EffectLedger:
# key -> (branch_id, record_id)
_cache: dict = field(default_factory=dict)
def commit(self, key: str, branch_id: str, record_id: str) -> None:
self._cache[key] = (branch_id, record_id)
def lookup(self, key: str) -> Optional[tuple]:
return self._cache.get(key)
def derive_key(task_id: str, branch_id: str, step: int, lineage_keyed: bool) -> str:
if lineage_keyed:
raw = f"{task_id}::{branch_id}::{step}"
else:
raw = f"{task_id}::{step}"
return hashlib.sha256(raw.encode()).hexdigest()
def guarded_write(
ledger: EffectLedger,
task_id: str,
branch: Branch,
step: int,
winning_branch_id: str,
lineage_keyed: bool,
payload: dict,
) -> str:
"""Perform a side-effecting write under reconciliation guardrails.
Raises if the call is made on an uncommitted non-winning branch under
prefix-keying, or if the dedup cache returns an effect authored by a
different branch than the caller.
"""
if not lineage_keyed and not branch.committed and branch.branch_id != winning_branch_id:
raise SpeculativeEffectAliasingError(
f"branch {branch.branch_id} attempted side-effecting write at step {step} "
f"under prefix-keying while uncommitted; effect would alias winner {winning_branch_id}"
)
key = derive_key(task_id, branch.branch_id, step, lineage_keyed)
prior = ledger.lookup(key)
if prior is not None:
author_branch, record_id = prior
if author_branch != branch.branch_id:
raise SpeculativeEffectAliasingError(
f"dedup hit for key {key[:12]} authored by branch {author_branch} "
f"but requested by branch {branch.branch_id}; refusing foreign effect"
)
return record_id
record_id = f"rec_{hashlib.sha256(str(payload).encode()).hexdigest()[:6]}"
ledger.commit(key, branch.branch_id, record_id)
return record_id
if __name__ == "__main__":
ledger = EffectLedger()
winner = Branch("A", committed=True)
loser = Branch("B", committed=False)
# Loser emits first under prefix-keying -> must be blocked by guardrail.
try:
guarded_write(ledger, "task-1", loser, step=0, winning_branch_id="A",
lineage_keyed=False, payload={"schema": "v2", "x": 1})
except SpeculativeEffectAliasingError as e:
print("blocked:", e)
# Winner writes cleanly.
rid = guarded_write(ledger, "task-1", winner, step=0, winning_branch_id="A",
lineage_keyed=False, payload={"schema": "v1", "x": 1})
print("winner record:", rid)