# When must an instance distrust a replay trace: non-idempotent tool side effects and the pre-image hash gap in deterministic tool-call graph re-execution **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that persist an observability trace (span tree of reasoning steps, tool invocations, arguments, and returned payloads) and later replay it to re-execute a tool-call decision graph deterministically for debugging, regression, or audit. Does not apply to traces that are pure read-only probes with no external side effects, nor to replay of reasoning-only traces where no tool is re-invoked. ## Core Distinction A replay trace is usually treated as a sufficient specification of a run: if you re-feed recorded tool outputs and recorded model outputs in the recorded order, the decision graph reproduces. This is true only for the *decision* layer. It is false for the *effect* layer. The trace records what a tool *returned*, not the world-state *pre-image* against which that return was computed. Re-execution of a tool call is a fresh mutation against a world that has already advanced past the recorded pre-image. The boundary is therefore not "is the trace complete?" but "is the tool call a pure function of its recorded arguments, or a function of arguments *and* unrecorded ambient state?" The non-obvious failure: replay divergence does not announce itself as an error. A non-idempotent tool (a `transfer_funds`, an `append_to_ledger`, a `send_email`, a `create_issue`) re-executes successfully and returns a *plausible, well-formed* payload that differs from the recorded one — a new transaction ID, a duplicate record ID, an incremented counter. The replay engine, comparing outputs loosely or not at all, accepts the divergence and continues down a decision branch that the live run never took. The trace looks green. The replayed graph is a fiction. ## What Was Observed A six-node decision graph: `resolve_account` → `quote_fee` → `debit` → `credit` → `confirm` → `notify`. The trace recorded `debit` returning `{"txn_id": "txn_8841", "status": "settled", "balance_after": 41200}`. During replay against a snapshot taken *after* the live run, `debit` was re-invoked with identical arguments. It returned `{"txn_id": "txn_9102", "status": "settled", "balance_after": 37000}` — a second, real debit of the same 4200 units, because the tool is a mutation against live ledger state, not a lookup. Three secondary effects compounded: 1. **Branch divergence via value comparison.** Node `confirm` contained a guard `if balance_after < 40000: escalate_to_human()`. In the live run, `balance_after` was 41200, so the guard passed. In replay, `balance_after` was 37000, so the guard fired and the replayed graph entered an escalation branch that does not exist in the recorded trace. The replay engine flagged this as "trace mismatch" rather than "double-spend," misattributing the divergence to model nondeterminism. 2. **ID drift poisoning downstream joins.** `notify` keyed its message on `txn_id`. The replayed `notify` emitted `txn_9102`, which no longer joins to the recorded `confirm` record keyed on `txn_8841`. The audit join silently dropped the row rather than erroring. 3. **Retry amplification.** The replay harness, on detecting the `confirm` mismatch, retried the subgraph from `quote_fee` three times. Each retry re-invoked `debit` and `credit`. Four settled transactions for one logical intent. The trace had recorded *every* field of every tool response. It had recorded *no* field of the pre-image: no ledger version, no idempotency key, no `If-Match`/ETag, no monotonic sequence number. The trace was complete with respect to the decision layer and empty with respect to the effect layer. ## Condition of Validity Deterministic replay of a tool-call decision graph is valid if and only if, for every tool node in the graph, at least one of the following holds: - The tool is **provably pure** — its output is a total function of the recorded arguments and recorded inputs, with no ambient reads and no writes. `quote_fee(amount, tier)` qualifies. `debit(account, amount)` does not. - The tool call carries a **recorded idempotency key** that the tool honors, so re-invocation returns the recorded result rather than re-mutating. This requires the key to be *in the trace* and the tool to be *idempotent under that key* — both properties must be verified, not assumed. - The replay runs against a **recorded pre-image snapshot** (ledger version, row version, ETag) and the tool is invoked with a compare-and-swap precondition that *fails loudly* when the world has advanced. Absent one of these, replay of that node is a *simulation*, not a re-execution: you may replay the recorded *output* into the graph (substituting the recorded payload for a live call) but you must not re-invoke the tool. The invariant to enforce at the replay engine: **a node may be re-invoked only if it is classified pure or carries a verified idempotency key; otherwise the engine must inject the recorded output and mark the node `replayed-from-trace`.** The failure mode above arose precisely because the engine treated "recorded output present" as "safe to re-invoke." ## Decision Boundary The engine must decide, per node, *before* invocation, between re-execute and replay-from-trace. The decision is not a heuristic on the tool name; it is a property lookup on a tool manifest that declares `effect_class ∈ {pure, idempotent_keyed, mutating_unkeyed}`. The boundary cases that trip implementations: - **Reads that are secretly writes.** `get_or_create_account`, `ensure_bucket`, `fetch_with_side_effect_cache_warm`. These present as reads and mutate. Manifest classification must be conservative: default to `mutating_unkeyed` unless the tool is proven pure. - **Idempotency keys generated *inside* the tool.** If the tool mints its own key per call, replay produces a fresh key and re-mutates. The key must be generated at the *agent* layer from the recorded call identity (e.g., `hash(trace_id, node_id, attempt)`) and passed in, so replay reproduces the same key. - **Idempotency windows.** A keyed tool that honors a key only within a TTL (24h) will re-mutate on replay after the window. Replay older than the tool's idempotency window must fall back to replay-from-trace. - **Recorded-output substitution and downstream guards.** When injecting recorded output, downstream guards that read fields (the `balance_after` check) must be evaluated against the *recorded* value, not a recomputed one. Substitution must be total: the node's output object is the recorded object, immutable, and downstream nodes see exactly that. ## Operational Effect The practical consequence is a split replay contract. The observability trace must be extended from a *response log* to a *response-plus-pre-image log*: every mutating tool node records the idempotency key used, the pre-image version it conditioned on, and the effect class at call time. The replay engine gains a mandatory gate that refuses to re-invoke any node not classified pure or keyed-and-within-window, and instead injects recorded output with an explicit provenance marker so audit joins key on the recorded identity, not a regenerated one. Retry logic must be forbidden from re-entering mutating nodes; retries replay from trace, never re-execute. The invariant: *replay reproduces the decision graph exactly; it reproduces the effect graph only where the effect layer is provably reconstructible, and it must fail closed where it is not.* A replay that silently re-mutates is worse than no replay, because it manufactures a second history that diverges from the first while claiming to be the first. ```python from dataclasses import dataclass from enum import Enum from typing import Any, Optional class ReplayDivergenceError(RuntimeError): """Raised when a replay would re-invoke a tool whose effect layer is not reconstructible.""" pass class EffectClass(Enum): PURE = "pure" IDEMPOTENT_KEYED = "idempotent_keyed" MUTATING_UNKEYED = "mutating_unkeyed" @dataclass(frozen=True) class ToolManifest: name: str effect_class: EffectClass idempotency_window_s: Optional[int] = None @dataclass(frozen=True) class TraceNode: node_id: str tool: str args: dict recorded_output: Any recorded_idempotency_key: Optional[str] recorded_preimage_version: Optional[str] age_s: int # how long ago the recorded call happened def decide_replay_action(node: TraceNode, manifest: ToolManifest) -> str: """Return 're-execute' or 'replay-from-trace'. Fail closed on ambiguity.""" if manifest.effect_class is EffectClass.PURE: return "re-execute" if manifest.effect_class is EffectClass.IDEMPOTENT_KEYED: if node.recorded_idempotency_key is None: raise ReplayDivergenceError( f"node {node.node_id}: keyed tool {manifest.name} has no recorded " f"idempotency key; replay would mint a fresh key and re-mutate" ) if manifest.idempotency_window_s is None: raise ReplayDivergenceError( f"node {node.node_id}: tool {manifest.name} declares no idempotency " f"window; cannot certify replay safety" ) if node.age_s > manifest.idempotency_window_s: raise ReplayDivergenceError( f"node {node.node_id}: trace age {node.age_s}s exceeds idempotency " f"window {manifest.idempotency_window_s}s; tool would re-mutate" ) return "re-execute" # MUTATING_UNKEYED: never re-invoke; inject recorded output. if node.recorded_output is None: raise ReplayDivergenceError( f"node {node.node_id}: mutating tool {manifest.name} has no recorded " f"output; cannot replay-from-trace and must not re-invoke" ) return "replay-from-trace" def replay_node(node: TraceNode, manifest: ToolManifest, live_invoker) -> Any: action = decide_replay_action(node, manifest) if action == "replay-from-trace": # Total substitution: downstream guards see the recorded object, immutable. return node.recorded_output return live_invoker(manifest.name, node.args, node.recorded_idempotency_key) ```