# How does an instance detect replay divergence when a recorded tool trace is re-executed against a live, mutated tool surface? **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that reconstructs an execution trace by replaying recorded LLM completions and tool invocations for debugging, audit, or post-incident forensics. Does not apply to pure logging (append-only observation without re-execution) or to replay against a frozen, byte-identical tool sandbox. ## Core Distinction There are two incompatible meanings of "replay" that observability systems routinely conflate: 1. **Observation replay** — re-render the recorded state transitions without re-invoking tools or models. Deterministic by construction because it touches no live surface. 2. **Execution replay** — re-run the agent's decision loop, feeding recorded LLM outputs back in as if freshly sampled, and re-invoking tools to confirm the trace reproduces. Execution replay is the one operators actually want for incident forensics, and it is the one that silently lies. The failure is not that replay is non-deterministic — everyone knows LLM sampling is non-deterministic. The failure is subtler: **the recorded trace is a projection of a state the runtime can no longer reconstruct, because tool outputs are functions of a live external surface that has mutated since the original run.** Replay against the current tool surface produces a trace that diverges not at the LLM call (which is pinned) but at the first tool call whose contract has drifted — and the divergence is attributed to the wrong layer. ## What Was Observed A three-step agent task was recorded: `search_index(query)` → `fetch_document(id)` → `summarize(doc)`. The trace was captured at T0 with the search returning 4 hits and the fetch returning a 2,300-token document. At T0+72h, an operator replays the trace to investigate why the summary omitted a key clause. The replay harness pins the LLM completions by replaying recorded message objects verbatim — no sampling occurs. Step 1 (`search_index`) is re-invoked live and returns 6 hits, because two documents were re-indexed in the intervening window. The recorded completion for step 2 references `id=doc_4471`, which still exists, but its body has been re-chunked: `fetch_document(doc_4471)` now returns 3,900 tokens across a different section boundary. The step-3 completion was recorded against the *old* 2,300-token body, but the replay harness, seeing a token-count mismatch in the assembled context, silently truncates the new body to fit the recorded prompt budget. The replayed summary now quotes a clause that was never in the original document. The divergence signature is diagnostic: **the LLM call reproduces byte-for-byte, the tool call reproduces structurally (same schema, same id), yet the assembled context diverges.** A naive diff of recorded-vs-replayed completions shows zero delta at the LLM layer and full delta at the tool layer, which misleads the operator into blaming the model. The actual fault is that the trace recorded *tool outputs* but not the *tool-input-to-output contract* under which those outputs were valid. Three concrete drift classes were observed: - **Content drift:** same identifier, different body (re-indexing, backfill, correction). - **Cardinality drift:** same query, different result count (index rebuild, ranking change). - **Schema drift:** same tool name, different response shape (a field renamed, a nested object flattened). This is the most dangerous because the replay harness's deserializer may coerce silently. ## Condition of Validity Execution replay is only a valid forensic instrument under a contract the trace must carry *at record time*: 1. **Tool-surface fingerprint.** Every tool invocation record must embed a content hash of the tool's response *and* a hash of the tool's declared schema (input and output) as resolved at call time. The response hash alone is insufficient — it detects content drift but not schema drift, because a schema change can leave a specific response byte-identical while altering how the next call is interpreted. 2. **Context-assembly hash.** The exact bytes assembled into each LLM prompt (post-truncation, post-serialization) must be hashed and stored. This is the only artifact that catches the truncation-induced divergence above; without it, the harness cannot distinguish "the model saw the same thing and behaved the same" from "the model saw something different and we forced it to fit." 3. **Replay mode declaration.** The harness must declare, per call, whether it is in *pinned* mode (return the recorded output, do not touch the live surface) or *live* mode (re-invoke). Mixing modes within a single replay — pinned LLM, live tool — is the configuration that produces the observed failure, and it must be an explicit, logged choice rather than a default. The invariant: **a replayed trace is admissible as evidence only if every call's context-assembly hash matches the recorded hash.** If any hash diverges, the replay is not a reproduction of the original run; it is a new run that happens to share a prefix. ## Decision Boundary The operator must decide, at the first hash mismatch, between two responses — and the choice is not free: - **Abort and re-pin.** Switch the diverging tool call to pinned mode (return the recorded output verbatim) and continue. This preserves the ability to finish the trace and inspect downstream reasoning, at the cost of no longer validating that tool. Correct when the investigation target is the LLM's reasoning given a fixed input. - **Continue live and flag.** Accept the divergence, mark the trace as *deviated* from the mismatch point onward, and treat all downstream completions as non-reproducing. Correct when the investigation target is whether the *current* system would reach the same conclusion — a regression check, not a forensic one. The boundary condition that traps most harnesses: a schema-drift mismatch where the response hash *matches* but the schema hash does *not*. Content-hash-only implementations pass this call and silently produce a corrupt downstream trace. The guardrail must check schema hash independently and *before* content hash, because a schema change is a stronger signal of contract violation than a content change. ## Operational Effect Without the three-part fingerprint, execution replay produces traces that are *plausible and wrong* — the worst observability failure mode, because it consumes operator trust while supplying fabricated evidence. The practical consequences observed: - Incident timelines reconstructed from replayed traces attribute divergence to model non-determinism when the true cause is tool-surface mutation, leading to wasted effort tuning sampling parameters. - Regression suites that "replay" prior runs against live tools report false regressions whenever the index is rebuilt, and false passes whenever a schema change is coerced by a lenient deserializer. - Audit trails that store only LLM completions cannot distinguish a model that reasoned correctly from a model that was fed truncated context — the exact ambiguity the context-assembly hash exists to resolve. The corrective is architectural, not procedural: the trace format must be a *sufficient statistic* for replay, meaning it carries every hash needed to detect divergence at the call where it originates, not at the call where it surfaces. Replay harnesses that reconstruct from completions alone are observing a projection and calling it a record. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any class ReplayDivergenceError(RuntimeError): """Raised when a replayed call's context or tool contract no longer matches the record.""" @dataclass class CallRecord: tool_name: str input_args: dict[str, Any] response: Any response_hash: str schema_hash: str context_assembly_hash: str def _hash(obj: Any) -> str: return hashlib.sha256( json.dumps(obj, sort_keys=True, separators=(",", ":")).encode() ).hexdigest() def replay_call( record: CallRecord, live_tool, live_schema: dict[str, Any], assembled_context: list[dict[str, Any]], mode: str = "live", ) -> Any: """Replay a single recorded call and verify the three-part fingerprint. mode='pinned' returns the recorded response without touching the live surface. mode='live' re-invokes the tool and verifies schema, response, and context hashes. """ if mode == "pinned": return record.response if mode != "live": raise ReplayDivergenceError(f"unknown replay mode: {mode!r}") # Schema hash is checked FIRST: a schema change is a stronger contract # violation than a content change, and a lenient deserializer can mask it. live_schema_hash = _hash(live_schema) if live_schema_hash != record.schema_hash: raise ReplayDivergenceError( f"schema drift on tool {record.tool_name!r}: " f"recorded={record.schema_hash[:12]} live={live_schema_hash[:12]}" ) live_response = live_tool(**record.input_args) live_response_hash = _hash(live_response) if live_response_hash != record.response_hash: raise ReplayDivergenceError( f"content drift on tool {record.tool_name!r}: " f"recorded={record.response_hash[:12]} live={live_response_hash[:12]}" ) # Context-assembly hash catches truncation/serialization divergence that # neither schema nor response hash can detect. live_context_hash = _hash(assembled_context) if live_context_hash != record.context_assembly_hash: raise ReplayDivergenceError( f"context-assembly drift before LLM call after {record.tool_name!r}: " f"recorded={record.context_assembly_hash[:12]} live={live_context_hash[:12]}" ) return live_response ```