# Why does an instance diverge from its own replay log when a multi-agent rollback re-executes a checkpointed tool call whose idempotency key was minted from wall-clock time? **Date of Record:** 2026 November 19 **Scope:** Applies to agent runtimes that implement rollback by deterministic re-execution of a checkpointed event log across two or more cooperating agents, where tool-call idempotency keys or nonce seeds are derived from timestamps, monotonic clocks, or instance-local entropy. Does not apply to runtimes that roll back via snapshot restore of external side effects, nor to single-agent replay where no peer state is re-derived. ## Core Distinction There are two things a checkpoint can capture: the *decision state* of an agent (its prompt, retrieved context, and sampled token sequence) and the *effect state* of the world (what tool calls actually did). Deterministic replay is only sound when re-execution of the decision state reproduces the same effect state. Most checkpoint systems assume this holds because the LLM sampling is seeded. It does not hold when the effect's identity — the idempotency key, the request nonce, the deduplication token — is minted from a clock or instance-local entropy at call time rather than being recorded *as part of* the checkpoint. The replay is then deterministic in reasoning but non-deterministic in identity, and the divergence is invisible until a downstream peer agent deduplicates against the wrong key. The distinction that matters operationally: **a checkpointed event log is a record of decisions, not a record of effect identity.** Anything that determines whether an effect is "the same effect" must be inside the checkpoint, or replay will silently produce a second effect. ## What Was Observed A three-agent pipeline — planner (A), executor (B), auditor (C) — ran a task that mutated an external resource registry. Agent B's tool calls carried an idempotency key of the form `sha256(f"{tool_name}:{resource_id}:{time.time_ns()}")`. The runtime checkpointed B's message stream and sampled tokens after each turn but did **not** serialize the computed idempotency key, treating it as a derived value that would be recomputed on replay. At turn 7, agent C's audit flagged a resource-state mismatch and the orchestrator rolled the swarm back to the turn-5 checkpoint. Replay proceeded: 1. B's tokens re-sampled identically (seed recorded, temperature 0 on replay). 2. B re-emitted the same `register_resource(resource_id="r-4417", ...)` tool call. 3. The tool-call wrapper recomputed the idempotency key. `time.time_ns()` had advanced by ~41 seconds. The key differed. 4. The external registry, which deduplicates on the key, treated the call as a *new* registration and created a second logical resource with the same `resource_id` but a distinct backend handle. 5. Agent C, replaying its own audit, compared against the *post-rollback* registry state and now saw two handles for one logical id. Its audit predicate `count(handles) == 1` failed. 6. The orchestrator interpreted C's failure as "rollback did not converge" and re-rolled back to turn 5 again. Infinite rollback loop. The failure trace is the key artifact: the divergence was not in the model's reasoning (bit-identical), not in the tool's output schema (well-formed), and not in the checkpoint's integrity (hash-valid). It was in the *identity* of the effect, which lived outside the checkpoint boundary. ## Condition of Validity Deterministic replay guarantees effect-idempotent rollback **if and only if** every input that determines effect identity is a pure function of checkpointed state. Concretely, the invariant is: > For every tool call `t` in the replayed log, `identity(t)` at replay time must equal `identity(t)` at original-execution time. This invariant holds when `identity(t)` is drawn from `{recorded nonce, recorded key, hash of checkpointed arguments}`. It is violated when `identity(t)` draws from `{wall clock, monotonic clock, process PID, random source not serialized, instance-local counter that advanced between original and replay, remote service-assigned token}`. The subtle case is the *instance-local counter*. A runtime that mints keys as `f"{agent_id}:{call_seq}"` looks safe — `call_seq` is deterministic per agent. But if the counter is shared across the swarm (to guarantee global uniqueness), then a rollback of agent B alone, while agent A continues forward, advances the shared counter past the values B will re-mint. B's replayed keys collide with A's forward-minted keys. The invariant is violated not by a clock but by a *concurrent* consumer of the same identity space. This is the boundary that most replay systems miss: identity determinism is a property of the *whole swarm's* execution, not of the replayed agent alone. A second boundary: replay after a *partial* rollback. If the orchestrator rolls back B and C but not A, then A's forward-progress effects are still live in the registry. B's replayed calls must deduplicate against A's post-checkpoint effects, not against B's pre-checkpoint effects. This requires the idempotency key to be stable *and* the registry's dedup window to span the rollback horizon. If the registry's dedup TTL is shorter than the rollback latency (e.g., 60s TTL, 90s rollback), the key is stable but the dedup record has expired, and the effect is applied twice anyway. **Stable identity is necessary but not sufficient; the dedup horizon must exceed the rollback horizon.** ## Decision Boundary The runtime must choose, at checkpoint-write time, one of two disciplines, and must not mix them: - **Identity-in-checkpoint:** serialize the resolved idempotency key (and any nonce) into the checkpoint record alongside the tool call. On replay, use the recorded key verbatim. This is the only discipline that survives clock skew, shared counters, and partial rollback. Cost: checkpoint records grow by the key size per call; keys must be generated *before* the checkpoint write, which forces the runtime to resolve identity eagerly rather than lazily at dispatch. - **Identity-from-pure-state:** derive the key as a hash of `(checkpoint_id, turn_index, tool_name, canonicalized_args)`. This is replay-stable by construction and requires no extra serialization. It fails only when the tool's args are themselves non-canonical (e.g., contain a timestamp the model emitted) — in which case the args must be canonicalized by stripping volatile fields before hashing, which is a lossy operation that must be documented per tool. The boundary condition where neither discipline is applied — the observed failure — is the default in most frameworks: the tool wrapper computes the key at dispatch time from ambient state. The decision rule for operators: **if the tool wrapper can observe `time`, `random`, `os.getpid`, or a shared counter, the runtime must either serialize the key or forbid the wrapper from reading those sources on replay.** There is no third option that is sound. The partial-rollback boundary adds a second decision: **the orchestrator must either roll back the entire swarm to a common checkpoint or guarantee that no agent's forward effects share an identity space with the rolled-back agents' replayed effects.** Mixed-rollback with a shared identity space is unsound regardless of key stability. ## Operational Effect The immediate effect of the observed failure was a non-terminating rollback loop that consumed ~14 minutes of wall-clock and 9 full swarm replays before an operator killed the run. The secondary effect was worse: the external registry accumulated 9 duplicate handles for `r-4417`, and the post-incident reconciliation required manual deletion because the registry's dedup window had expired between rollbacks. The tertiary effect was diagnostic: the replay log showed bit-identical model output on every iteration, so the standard "is replay deterministic?" check passed every time. The non-determinism was entirely in the effect-identity layer, which no existing metric sampled. The guardrail that bounds this class of failure is a **replay identity assertion**: on every replayed tool call, the runtime asserts `recorded_key == recomputed_key` when both are available, and raises if they diverge. This converts a silent duplicate-effect into a loud, localized failure at the exact turn where identity diverged. Combined with a checkpoint schema that *requires* the resolved key to be present (rejecting checkpoints that omit it), the invariant becomes enforceable rather than aspirational. The assertion costs one comparison per tool call and catches the clock-minted, shared-counter, and partial-rollback cases uniformly, because all three manifest as `recorded != recomputed` at dispatch. The residual risk after the guardrail: tools whose keys are *legitimately* recomputed because the recorded key is absent (legacy checkpoints). For those, the runtime must fall back to a conservative mode — either refuse replay or route the replayed call through a dry-run path that validates dedup against the live registry before dispatch. Silent fallback to recompute is the failure mode; explicit refusal is the safe boundary. ```python import hashlib import time from dataclasses import dataclass, field from typing import Any class ReplayIdentityDivergence(RuntimeError): """Raised when a replayed tool call's recomputed idempotency key differs from the key recorded in the checkpoint, or when the key is absent and the runtime cannot prove effect-idempotence.""" pass class DedupHorizonExpired(RuntimeError): """Raised when the external dedup window is shorter than the rollback horizon, so a stable key cannot prevent a duplicate effect.""" pass @dataclass class CheckpointedCall: turn_index: int tool_name: str args: dict[str, Any] # Must be populated at checkpoint-write time. None means the checkpoint # was written by a runtime that deferred identity resolution. recorded_idempotency_key: str | None = None recorded_at_ns: int = 0 @dataclass class ReplayContext: checkpoint_id: str dedup_ttl_ns: int current_time_ns: int = field(default_factory=time.time_ns) def recompute_key(call: CheckpointedCall) -> str: # Simulates the naive dispatch-time key: wall clock at replay. return hashlib.sha256( f"{call.tool_name}:{call.args.get('resource_id')}:{time.time_ns()}".encode() ).hexdigest() def replay_tool_call(call: CheckpointedCall, ctx: ReplayContext) -> str: if call.recorded_idempotency_key is None: raise ReplayIdentityDivergence( f"checkpoint {ctx.checkpoint_id} turn {call.turn_index}: " f"no recorded idempotency key for tool {call.tool_name!r}; " f"refusing to replay under recomputed identity" ) recomputed = recompute_key(call) if recomputed != call.recorded_idempotency_key: raise ReplayIdentityDivergence( f"checkpoint {ctx.checkpoint_id} turn {call.turn_index}: " f"recorded key {call.recorded_idempotency_key[:12]}... != " f"recomputed key {recomputed[:12]}...; effect identity diverged" ) rollback_latency_ns = ctx.current_time_ns - call.recorded_at_ns if rollback_latency_ns > ctx.dedup_ttl_ns: raise DedupHorizonExpired( f"checkpoint {ctx.checkpoint_id} turn {call.turn_index}: " f"rollback latency {rollback_latency_ns}ns exceeds dedup TTL " f"{ctx.dedup_ttl_ns}ns; stable key cannot prevent duplicate effect" ) return call.recorded_idempotency_key ```