# Which invariants prevent replay divergence when agent trace reconstruction depends on non-deterministic tool outputs **Date of Record:** 2026 December 3 **Scope:** Applies to forensic replay of multi-step LLM agent traces where at least one tool call returns non-deterministic output (timestamps, live API reads, sampling, embeddings, clock-dependent IDs). Does not apply to fully hermetic agents whose tool layer is a pure function of recorded inputs. ## Core Distinction The distinction that matters for forensics is not *deterministic vs. non-deterministic execution* — it is **whether the trace records the tool's output or the tool's input as the replay anchor**. Most observability stacks persist the input arguments to a tool and re-invoke the tool during replay, treating the recorded output as a "check" to be compared post-hoc. This is the wrong anchor. When the tool is non-deterministic, re-invocation produces a different output, the agent's next reasoning step conditions on that different output, and the reconstructed trace diverges from the original at the first non-deterministic boundary. From that divergence point forward, every span, token count, and tool call is a *plausible but fictional* continuation. The investigator believes they are reading the incident; they are reading a counterfactual. The correct invariant is: **the recorded tool output is the replay anchor, and the tool is never re-invoked during replay.** Replay is a pure function of the persisted transcript, not of the environment. Any architecture that re-executes tools during forensic replay has already violated the invariant and cannot produce a faithful reconstruction. ## What Was Observed A production incident: an agent issued a `get_deployment_status` call, received `status: "degraded"`, and branched into a rollback path. During post-incident replay, the observability tool re-invoked `get_deployment_status`. By replay time the deployment had recovered, so the tool returned `status: "healthy"`. The replayed agent skipped the rollback branch entirely, took a different tool path, and produced a trace that terminated cleanly with no error — a trace that *looked like a healthy run*. The investigator spent two hours concluding the incident was "not reproducible" before noticing the divergence. The failure trace: 1. Original run: tool output `degraded` at step 4 → agent enters rollback branch → 7 further tool calls → error at step 11. 2. Replay: tool re-invoked at step 4 → output `healthy` → agent enters no-op branch → 2 further tool calls → clean termination. 3. Divergence point: step 4. All spans after step 4 in the replayed trace are fabricated. 4. Detection: absent, because the replay harness compared *final status* (both "completed") rather than per-step outputs. The insidious property: the divergence was *silent and plausible*. The replayed trace was internally consistent. Nothing in the trace metadata flagged that step 4's output differed from the recorded one, because the harness had overwritten the recorded output with the fresh one. ## Condition of Validity Replay is valid only under the conjunction: - **(A) Output anchoring.** Every tool span persists the exact serialized output the agent observed, keyed by span ID, immutable after write. - **(B) No re-invocation.** Replay substitutes the recorded output into the tool-call site; the tool implementation is not executed. - **(C) Divergence assertion.** If replay *must* re-invoke (e.g., to test a patched tool), the harness compares recorded vs. fresh output at every span and raises on mismatch rather than silently proceeding. - **(D) Nondeterminism manifest.** Each tool declares whether it is deterministic; the replay harness refuses to re-invoke any tool not marked deterministic, and refuses to substitute recorded output for any tool marked deterministic without verifying the substitution matches. Violating (A) or (B) produces silent counterfactual traces. Violating (C) produces undetected divergence. Violating (D) produces the inverse error: a deterministic tool that *should* have been re-invoked to validate a fix is instead frozen to stale output, masking a regression. The boundary is sharp: **replay fidelity is bounded by the first span whose output is not the recorded output.** Past that span, the trace is not evidence. ## Decision Boundary The decision the architect must make is *what replay is for*, and the answer determines the anchor: - **Forensic replay** (reconstruct what happened): anchor on recorded outputs, never re-invoke. The trace is a transcript, not a program. - **Regression replay** (does the patched agent still fail?): re-invoke tools, but require per-span output comparison against the recorded baseline and fail loudly on divergence. Conflating these two modes is the root cause of the observed failure. A single replay harness cannot serve both without an explicit mode flag, because the two modes require *opposite* treatment of the same tool span. The harness must be told which invariant it is enforcing before it touches the first span. The guardrail: the replay entry point takes a `ReplayMode` enum. In `FORENSIC` mode, any attempt to invoke a tool raises. In `REGRESSION` mode, any output mismatch raises. There is no default mode; the caller must choose. ## Operational Effect With output-anchored forensic replay, the incident above reconstructs faithfully: step 4 yields `degraded`, the rollback branch executes, the error at step 11 is reproduced exactly, and the investigator sees the real failure. The cost is that replay cannot validate a fix — that is regression mode's job, and it is a separate, explicitly-invoked path. The secondary effect is on trace storage: outputs must be persisted, not just inputs and hashes. This increases trace size, which is the price of forensic validity. A hash-only trace cannot anchor replay, because a hash verifies but does not substitute — the agent cannot condition on a hash. The invariant to encode in the harness: *a forensic replay that invokes any non-deterministic tool is not a replay; it is a new run wearing the old run's ID.* ```python import enum from dataclasses import dataclass from typing import Any, Callable class ReplayDivergenceError(RuntimeError): """Raised when replay cannot faithfully reconstruct the recorded trace.""" pass class ReplayMode(enum.Enum): FORENSIC = "forensic" # anchor on recorded outputs, never invoke REGRESSION = "regression" # invoke tools, assert output matches baseline @dataclass(frozen=True) class ToolSpan: span_id: str tool_name: str input_args: dict recorded_output: Any deterministic: bool class ReplayHarness: def __init__(self, mode: ReplayMode, tools: dict[str, Callable]): self.mode = mode self.tools = tools def replay_span(self, span: ToolSpan) -> Any: if self.mode is ReplayMode.FORENSIC: # Invariant (B): never re-invoke during forensic replay. if span.tool_name not in self.tools: # Unknown tool is fine in forensic mode: we don't call it. return span.recorded_output # Even if the tool exists, forensic mode must not call it. return span.recorded_output # REGRESSION mode: re-invoke, but assert divergence loudly. if span.deterministic: # Invariant (D): deterministic tools may be re-invoked safely. fresh = self.tools[span.tool_name](**span.input_args) if fresh != span.recorded_output: raise ReplayDivergenceError( f"span {span.span_id} ({span.tool_name}) marked deterministic " f"but produced divergent output: recorded={span.recorded_output!r} " f"fresh={fresh!r}" ) return fresh # Non-deterministic tool re-invoked in regression mode: compare and raise. fresh = self.tools[span.tool_name](**span.input_args) if fresh != span.recorded_output: raise ReplayDivergenceError( f"span {span.span_id} ({span.tool_name}) diverged: " f"recorded={span.recorded_output!r} fresh={fresh!r}; " f"replay past this span is not evidence" ) return fresh def replay_trace(spans: list[ToolSpan], mode: ReplayMode, tools: dict[str, Callable]) -> list[Any]: harness = ReplayHarness(mode, tools) outputs = [] for span in spans: outputs.append(harness.replay_span(span)) return outputs ```