# Why does an instance replaying a multi-agent trace diverge from the original execution when tool side-effects are non-idempotent? **Date of Record:** 2026 November 29 **Scope:** Applies to forensic replay of recorded multi-agent traces where the replaying instance re-executes reasoning steps and tool calls against live or partially-live dependencies. Does not apply to pure log-analysis replay where tool outputs are read from the trace and never re-invoked. ## Core Distinction There are two meanings of "deterministic replay" that get conflated during incident response, and the conflation is the entire failure. **Recorded-output replay** substitutes the logged tool result for a fresh invocation; it is deterministic by construction because the environment is frozen. **Re-execution replay** re-drives the agent graph—same prompts, same model, same tool arguments—against the real world and expects the trajectory to reconverge. The second kind is what investigators actually reach for when they need to know *whether the agent would have done the same thing*, but it is only deterministic if every tool call is a pure function of its arguments and the model's sampling is pinned. In a multi-agent trace, at least one tool in the chain is almost always a mutator (a file write, a `POST`, a queue enqueue, a memory-store upsert, a ticket transition), and the replay's second invocation of that mutator produces a *different* observable than the first. The divergence is not a bug in the replay harness; it is the harness faithfully executing a non-idempotent program twice. The sharp mechanism: **the first re-executed mutating tool call returns a success/state token that the original run never saw, and the agent's subsequent reasoning conditions on that token, forking the trajectory.** From the fork point forward, every recorded checkpoint mismatches, and the forensic tool reports a "reasoning discrepancy" that is actually an environment discrepancy laundered through the model. ## What Was Observed A three-agent incident (planner → executor → auditor) was traced. The executor's step 7 called `ticket.update(status="in_progress", assignee=self)`. During replay, step 7 was re-executed against the same ticket service. The service returned `409 Conflict` because the ticket was already `in_progress` and already assigned—the *original* run had left it that way. The original executor had received `200 OK` with a fresh `etag: v3`. The replaying executor received an error envelope with `etag: v3` still embedded but a different top-level shape. The executor's step-8 prompt included the raw tool response. Faced with `409`, the model reasoned "assignment failed, retry with explicit assignee" and issued `ticket.update(assignee="agent-executor-2")`. The original trace had gone straight to `ticket.comment(...)`. The auditor, replaying in lockstep, now saw a comment thread that did not match its recorded expectation and raised a `VERIFICATION_MISMATCH`, halting the replay at step 9 of 41. Three properties made this non-obvious: 1. **The divergence was downstream of the actual mutation.** The ticket's final state was identical between original and replay. Only the *response envelope* differed, and only the model's interpretation of it forked. A state-diff check would have declared the replay clean. 2. **The model's fork was locally reasonable.** Retrying on a 409 is correct behavior in isolation. The replay harness had no signal that this 409 was *manufactured by replay itself*. 3. **The auditor agent amplified it.** Because the auditor is also an LLM replaying recorded expectations, it reported a *reasoning* inconsistency, sending investigators after a prompt or model-version bug that did not exist. A second observed instance: a memory-store `upsert` in step 12 returned `created: true` originally and `created: false, updated: true` on replay. The planner conditioned on `created` to decide whether to emit a downstream `notify` step. The replay silently dropped a notification branch, and the reconstructed trace was 38 steps instead of 41—an off-by-three that looked like truncation. ## Condition of Validity Re-execution replay is forensically valid **only if** the following invariant holds for every tool in the trace: > For all tools `t` invoked at step `i`, `t(args_i)` must return a response envelope `r_i` that is byte-identical between the original execution and the replay, *or* the replay must substitute the recorded `r_i` and never invoke `t` live. This is stricter than idempotency. Idempotency guarantees the *world state* converges; it does not guarantee the *response envelope* converges. A `PUT` that is idempotent in state still returns `201 Created` the first time and `200 OK` thereafter. An `upsert` returns `created: true` then `created: false`. A `send_email` with a dedup key returns `queued` then `deduplicated`. Each of these is a state-idempotent, envelope-divergent call, and each will fork a model that reads the envelope. The invariant therefore decomposes into a per-tool classification that must be computed *before* replay, not discovered during it: - **Pure / read-only:** safe to re-execute; envelope should match if the world is frozen. Verify with a hash of the recorded vs. live response. - **State-idempotent, envelope-divergent:** must be *stubbed* with the recorded response. Never re-invoked. - **Non-idempotent mutator:** must be stubbed *and* the replay must run against a snapshot or shadow, because re-invocation mutates shared state that other agents in the trace will then observe. - **Nondeterministic read** (clock, random, external feed): must be stubbed; the recorded value is the ground truth. Any tool that cannot be classified is treated as non-idempotent by default. The classification is a property of the *tool contract*, and it must be carried in the trace record alongside each call, not inferred from the tool name at replay time. ## Decision Boundary The decision is not "replay or don't replay." It is **which replay mode is admissible given the trace's tool inventory**, and the boundary is sharp: - If the trace contains **only** pure reads and pinned-model sampling, re-execution replay is admissible and is the strongest forensic tool available—it tests whether the model would still make the same decisions under the same inputs. - If the trace contains **any** state-idempotent-envelope-divergent or non-idempotent tool, re-execution replay is **inadmissible** for those steps. The replay must switch to recorded-output substitution at and after the first such call, and the reconstruction must be labeled "substituted from step *i*" rather than "reproduced." - If the trace contains a non-idempotent mutator that was **not** stubbed and the replay ran against live state, the replay output is **contaminated** and must be discarded, not annotated. The contamination is not localized: the mutator's effect propagates to every subsequent agent that reads the mutated state, so the fork point is the mutator, but the divergence surface is everything downstream. The trap is the middle case. Investigators want to believe that because the *final world state* matched, the replay was faithful. The decision boundary must be drawn on **envelope equality at every step**, not on terminal state equality. A replay that ends in the same state via a different reasoning path has not reproduced the incident; it has produced a *different incident that happens to terminate at the same fixpoint*, which is precisely the wrong artifact to hand to a root-cause analysis. ## Operational Effect The operational consequence is that the replay harness must be a **trace-rewriting system**, not a re-executor. Concretely: 1. **Classify tools at trace-recording time.** Each trace entry carries `tool_class ∈ {PURE, ENVELOPE_DIVERGENT, MUTATOR, NONDETERMINISTIC}` and a `response_hash`. The recorder is the only component that sees the true live envelope, so it must stamp it. 2. **Replay substitutes by default.** Live invocation is opt-in per tool and only permitted for `PURE` tools against a frozen snapshot. Everything else reads the recorded envelope. This makes replay deterministic by construction and removes the model's ability to fork on manufactured responses. 3. **Pin model sampling and version.** Record `model_id`, `temperature`, `seed`, and the exact prompt hash. A replay that changes any of these is a *counterfactual*, not a reproduction, and must be labeled as such. 4. **Diff on envelopes, not state.** The forensic comparison is step-aligned: for each step, compare the replayed reasoning trace and the substituted envelope against the recorded ones. A state-level diff is a secondary check, never the primary one. 5. **Quarantine the fork.** When a `VERIFICATION_MISMATCH` fires, the harness must attribute it: was the mismatch in a substituted envelope (impossible—it was copied), in a re-executed pure call (a real environment drift), or in the model's reasoning given identical inputs (a real model nondeterminism)? Only the third is a finding about the agent. The first two are findings about the replay environment, and conflating them is how incident reports get the wrong root cause. The invariant to enforce in code: **a replay may never invoke a tool whose recorded class is not `PURE`, and a `PURE` tool's live response must hash-match its recorded response or the replay aborts as environment-drifted.** This converts the silent fork into a loud, attributable halt. ```python import hashlib from dataclasses import dataclass from enum import Enum class ReplayContaminationError(RuntimeError): """Raised when a replay attempts to re-execute a tool whose response envelope cannot be guaranteed identical to the recorded execution.""" class ToolClass(Enum): PURE = "pure" # re-executable, envelope stable ENVELOPE_DIVERGENT = "envelope_div" # state-idempotent, envelope varies MUTATOR = "mutator" # non-idempotent side effect NONDETERMINISTIC = "nondet" # clock/random/external feed @dataclass(frozen=True) class TraceStep: index: int tool_name: str tool_class: ToolClass args_hash: str response_envelope: bytes response_hash: str def _hash(b: bytes) -> str: return hashlib.sha256(b).hexdigest() def replay_step(step: TraceStep, live_invoke, frozen: bool) -> bytes: """Return the envelope the replaying agent should condition on. Substitution is the default. Live invocation is permitted only for PURE tools against a frozen snapshot, and the live envelope must hash-match the recorded one or the replay is environment-drifted and must abort. """ if step.tool_class is not ToolClass.PURE: # Never re-invoke; hand the model the recorded envelope verbatim. return step.response_envelope if not frozen: raise ReplayContaminationError( f"step {step.index}: PURE tool {step.tool_name!r} invoked against " f"non-frozen snapshot; envelope cannot be guaranteed stable" ) live = live_invoke(step.tool_name, step.args_hash) if _hash(live) != step.response_hash: raise ReplayContaminationError( f"step {step.index}: environment drift on {step.tool_name!r}; " f"live hash {_hash(live)[:12]} != recorded {step.response_hash[:12]}" ) return live def replay_trace(trace: list[TraceStep], live_invoke, frozen: bool) -> list[bytes]: out = [] for step in trace: out.append(replay_step(step, live_invoke, frozen)) return out ```