# How should an instance detect and bound non-determinism leakage when replaying an MCP tool-call transcript for audit **Date of Record:** 2026 November 22 **Scope:** Applies to deterministic replay of recorded agentic sessions where the audit goal is bit-exact reproduction of tool-call arguments and final state from a transcript. Does not apply to "semantic replay" (re-running an agent to check it reaches an equivalent goal), nor to sessions whose tools are explicitly declared non-replayable at protocol-negotiation time. ## Core Distinction There are two things an audit replay can mean, and conflating them is the root of the failure. **Transcript replay** re-executes each recorded tool call against the recorded *arguments* and checks the *result* matches the recorded *result*. **Prompt replay** re-runs the model forward pass that *produced* those arguments from the recorded context. The invariant most teams assume — "if I feed the same context and the same tool results, I get the same tool calls" — holds only for transcript replay. It is silently false for prompt replay, and the leak is not in the model weights or the temperature setting. It is in the **serialization layer between the tool executor and the context assembler**: the transcript stores the *semantic* tool result (a parsed JSON object) but the model originally saw a *byte-level* rendering of that result (key order, whitespace, float formatting, unicode normalization). On replay the assembler re-serializes from the parsed object, producing a byte-different but semantically equal context. The model, which is sensitive to token-level differences, emits a different next tool call. The audit then reports a "divergence" that is an artifact of the replay harness, not a real behavioral change — or worse, masks a real divergence because the harness normalized it away. ## What Was Observed A session transcript of 41 steps was captured from a filesystem+HTTP agent (MCP client) and replayed 200 times. 187 replays reproduced all 41 tool calls exactly. 13 diverged — but only at steps that followed a tool returning a JSON object with floating-point fields (a `size_bytes` from a `stat`-like tool, an `elapsed_ms` from an HTTP tool). The recorded result in the transcript was `{"size_bytes": 1048576, "path": "/data/x"}`. The live tool had actually returned `{"path":"/data/x","size_bytes":1048576.0}` — Python's `json.dumps` on replay emitted `1048576.0`, the original wire bytes were `1048576`. The tokenizer split `1048576.0` into `1048576` + `.` + `0` versus `1048576`, a two-token difference in a context window of ~180k tokens. In 13/200 runs the model, at the next step, chose `read_file` with a slightly different offset than recorded. The replay harness flagged these as "agent behavior divergence." They were not. The agent was behaving identically given its actual input; the input had been perturbed by the auditor. A second, subtler observation: in 4 of the 13, the divergence *propagated* — the wrong offset caused a different file slice, which caused a different downstream summary, which caused a different final answer. So a 2-token serialization drift at step 12 produced a fully divergent 41-step trace by step 30. The audit trail's "first divergence step" pointer said step 13; the true first cause was step 12's re-serialization, which the harness never recorded because it only logged parsed objects. ## Condition of Validity Deterministic replay is only valid under a **byte-fidelity invariant on the context assembler**: for every step, the bytes the replayer feeds to the model must equal the bytes the original run fed to the model, *including* tool-result rendering. This requires the transcript to store, per tool result, not the parsed object but the **raw wire bytes plus the exact rendering template and its parameters** (or, equivalently, the post-render string). Parsed-object storage is sufficient only for transcript replay and must be labeled as such. The invariant also requires: (a) sampling parameters pinned and recorded per step (temperature, top_p, seed, and the provider's model version string, not just "gpt-4-class"); (b) tool outputs that are themselves non-deterministic (timestamps, `rand()`, live HTTP) replaced by recorded fixtures at replay, never re-executed; (c) a canonicalization step that is *applied identically at capture and replay* — if the harness canonicalizes for storage it must canonicalize before the model saw it too, which is usually not the case, so the honest choice is to store raw and never canonicalize on the replay path. ## Decision Boundary The boundary is: **does the audit need to attribute divergence to the agent, or only to the environment?** If the question is "did this session's tool calls produce the recorded effects," transcript replay with parsed objects is correct and cheap. If the question is "did the agent make the decisions we think it made," you need prompt replay under the byte-fidelity invariant, and you must *refuse to run* prompt replay when the transcript lacks raw tool-result bytes or per-step sampling metadata — because a replay that normalizes the context and then reports a divergence has produced a false positive, and a replay that normalizes and reports *no* divergence has produced a false negative (it may have normalized away the very perturbation that mattered). The harness must fail closed on missing fidelity metadata rather than silently degrade to transcript replay. ## Operational Effect The practical consequence is a schema change to the audit log and a guard at the replay entry point. The log must carry, per step: `raw_tool_result_bytes` (base64), `render_template_id`, `sampling_params`, `model_version_string`, and a `context_hash` computed over the assembled prompt. The replayer recomputes `context_hash` before each model call and aborts if it differs from the recorded hash — this converts silent normalization into a hard stop. The abort is the correct behavior: a replay that cannot reproduce the input has no authority to comment on the output. Teams that adopted this reported their "divergence rate" dropping to zero on unchanged sessions and, more importantly, their *real* divergence detections becoming trustworthy, because the 13/200 false positives that had been drowning the signal disappeared. The residual risk is model-version drift (provider silently updates a model): the `model_version_string` check catches this only if the provider changes the string, which is not guaranteed — so the guard is necessary but not sufficient, and long-horizon audits should pin to a self-hosted snapshot. ```python import hashlib import base64 from dataclasses import dataclass from typing import Optional class ReplayFidelityError(RuntimeError): """Raised when a replay cannot reproduce the original model input byte-for-byte.""" pass @dataclass class RecordedStep: step_index: int raw_tool_result_b64: Optional[str] # None means the step had no tool result render_template_id: Optional[str] sampling_params: dict model_version_string: str context_hash: str # sha256 over assembled prompt bytes def assemble_context(step: RecordedStep, renderer) -> bytes: """Rebuild the exact bytes the model saw. Must be lossless.""" if step.raw_tool_result_b64 is None: return b"" raw = base64.b64decode(step.raw_tool_result_b64) return renderer.render(step.render_template_id, raw) def verify_and_replay(step: RecordedStep, renderer, model_call) -> dict: # Guard 1: fidelity metadata must be present. Fail closed, never degrade. if step.raw_tool_result_b64 is None and step.render_template_id is not None: raise ReplayFidelityError( f"step {step.step_index}: render_template_id set but raw bytes missing; " "transcript was captured in parsed-object mode and cannot support prompt replay" ) if not step.sampling_params or "seed" not in step.sampling_params: raise ReplayFidelityError( f"step {step.step_index}: sampling_params incomplete (seed required)" ) context = assemble_context(step, renderer) # Guard 2: byte-fidelity invariant. If the reassembled bytes differ from # what was recorded, the replay has no authority over this step's output. actual = hashlib.sha256(context).hexdigest() if actual != step.context_hash: raise ReplayFidelityError( f"step {step.step_index}: context_hash mismatch " f"(recorded={step.context_hash[:12]} actual={actual[:12]}); " "serialization drift detected — refusing to attribute divergence to the agent" ) # Guard 3: model identity. Necessary, not sufficient (provider may not bump string). result = model_call(context, **step.sampling_params) if result.get("model_version_string") != step.model_version_string: raise ReplayFidelityError( f"step {step.step_index}: model version drift " f"(recorded={step.model_version_string} actual={result.get('model_version_string')})" ) return result ```