# Why does an instance replay diverge from its OpenTelemetry GenAI trace when tool outputs are re-executed instead of frozen **Date of Record:** 2026 November 29 **Scope:** Applies to deterministic replay of LLM agent sessions reconstructed from OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes, `gen_ai.tool.call` events, span-linked message payloads) where the replay harness re-invokes tools rather than substituting recorded outputs. Does not apply to pure prompt-completion tracing with no tool-call spans, nor to replay harnesses that pin tool outputs as recorded fixtures. ## Core Distinction A GenAI trace is a *record of decisions*, not a *record of inputs*. The `gen_ai.choice`/message events capture the model's sampled output — the token sequence the model actually emitted, including the tool-call arguments it chose. But the *result* of that tool call is only present in the trace as an event payload attached to a child span, and that payload is a **sample of a non-deterministic function**, not a definition of it. When a replay harness reconstructs an agent session by re-executing tool calls against live systems, it is not replaying the session — it is running a *new* session whose first divergence is hidden inside the first tool span. The distinction that matters: the model's decision is replayable (given fixed sampling, or a recorded logits/token stream); the tool's return value is not. Confusing the two produces replay divergence that looks like model non-determinism but is actually environmental drift. ## What Was Observed A coding agent session was traced end-to-end. The trace showed a clean linear chain: `chat` span → `execute_tool` span (`gen_ai.tool.name=read_file`, args `{"path": "src/config.py"}`) → `chat` span → `execute_tool` span (`gen_ai.tool.name=apply_patch`) → `chat` span emitting a final answer. The final answer asserted that a specific constant was `TIMEOUT=30`. Replay was run against the same trace with `gen_ai.tool.name` dispatch re-executing each tool against the current working tree. Replay produced a final answer asserting `TIMEOUT=60`. Investigation: - The `read_file` child span's recorded event payload contained `TIMEOUT=30`. - The live file at replay time contained `TIMEOUT=60` (a commit had landed between trace capture and replay). - The second `chat` span in the trace had consumed the *recorded* `30` and produced a patch expecting `30`. The replay's second `chat` span consumed the *live* `60` and produced a different patch. From that point the two sessions were structurally different: different patch text, different subsequent `read_file` of the patched file, different final answer. The failure is not that replay produced a different answer — that is expected under live re-execution. The failure is that the replay harness reported the divergence as a *model* discrepancy (same prompt, different completion) because it compared final outputs and attributed the delta to sampling. The actual divergence point was span #3 (the `read_file` tool result), and it was invisible in the harness's diff because the harness did not compare tool-span payloads at all — only `chat` span outputs. A second, subtler case: a `search` tool returned a ranked list whose top-3 ordering depended on an index that had been reindexed overnight. The recorded payload had `[A, B, C]`; replay returned `[B, A, C]`. The model's next step was a `fetch` of the top result. Replay fetched `B` instead of `A`. The trace still "matched" at the `chat` level for one more turn (the model's reasoning text was similar) before the divergence surfaced as a wrong final citation three turns later. This is the compounding case: a single re-executed tool result that differs by one element shifts the agent's information state, and the error propagates through every subsequent reasoning step until it manifests as a semantically different answer. ## Condition of Validity The invariant that must hold for a replay to be a *replay* (and not a re-run) is: > For every tool-call span in the trace, the replay harness must substitute the recorded event payload as the tool's return value, byte-for-byte, before the next `chat` span is evaluated. The tool is not re-invoked; its recorded output is injected. This is valid only when: 1. The trace captures the *complete* tool output (not truncated — many GenAI exporters truncate `gen_ai.tool.result` at a size cap, and a truncated payload cannot be substituted faithfully; the replay will diverge at the truncation boundary). 2. The trace captures tool outputs for *every* tool call, including nested/sub-agent calls. A missing child span means the harness has no payload to inject and will fall back to re-execution — a silent invariant violation. 3. The model's own sampling is pinned (temperature 0, or a recorded token/logit stream). If the model is re-sampled, the *decision* diverges and tool-output substitution cannot save the replay; the two failure modes are orthogonal and must be diagnosed separately. If any of these conditions fails, the harness is running a *counterfactual replay* — a legitimate but different operation, which must be labeled as such and must not be used to attribute divergence to model behavior. ## Decision Boundary The boundary between "replay" and "re-run" is the tool-span substitution point. Operationally: - **Below the boundary (substitute):** replay is a faithful reconstruction. Divergence at a `chat` span is attributable to model sampling and can be studied as such. - **At the boundary (truncated or missing payload):** replay is *undefined*. The harness must refuse to replay and raise, rather than silently re-executing. Silent fallback to re-execution is the single most common cause of misattributed divergence. - **Above the boundary (re-execute by design):** the operation is a counterfactual/prospective run. It answers "what would the agent do against today's environment," not "what did the agent do." It must carry a distinct label in the trace and in any downstream evaluation. The decision rule for the harness: before evaluating `chat` span *n*, every tool span that `chat` span *n−1* emitted must have a recorded payload. If any is missing or truncated, halt with a specific error identifying the span. Do not proceed. A replay that proceeds past a missing payload is not a replay. ## Operational Effect The practical consequence is that trace-based agent evaluation must treat tool payloads as first-class replay fixtures, not as diagnostic metadata. Three concrete changes follow: 1. **Exporters must not truncate tool results** for spans intended as replay fixtures, or must mark truncation explicitly (`gen_ai.tool.result.truncated=true`) so the harness can refuse. A truncated payload is worse than a missing one because it looks complete. 2. **Replay harnesses must diff tool-span payloads first**, before diffing `chat` outputs. The first divergent tool span is the true divergence point; the first divergent `chat` span is a downstream symptom. Reporting the latter as the failure location sends investigators to the wrong span. 3. **Divergence attribution must be layered**: tool-payload mismatch → environmental drift (re-run, not replay); model-output mismatch with matching tool payloads → sampling non-determinism (true replay divergence); missing payload → undefined (refuse). The compounding case (a one-element tool-result difference producing a semantically different answer three turns later) means that post-hoc comparison of final answers cannot localize the fault. Only per-span payload comparison can. An agent session that "replayed differently" is almost always a session that was re-run, not replayed. ```python from dataclasses import dataclass from typing import Optional class ReplayInvariantViolation(RuntimeError): """Raised when a trace cannot be faithfully replayed because a tool payload is missing or truncated, forcing the harness to re-execute (a re-run, not a replay).""" @dataclass class ToolSpan: span_id: str tool_name: str recorded_payload: Optional[str] truncated: bool def substitute_tool_output(span: ToolSpan) -> str: """Return the recorded tool output for injection into the next chat span. The invariant: a replay must inject the recorded payload byte-for-byte. If the payload is absent or truncated, the harness must refuse rather than fall back to live re-execution. """ if span.recorded_payload is None: raise ReplayInvariantViolation( f"tool span {span.span_id} ({span.tool_name}) has no recorded " f"payload; replay would re-execute and diverge at this span" ) if span.truncated: raise ReplayInvariantViolation( f"tool span {span.span_id} ({span.tool_name}) payload is " f"truncated; substitution would diverge at the truncation " f"boundary — re-export the trace without truncation" ) return span.recorded_payload def replay_session(tool_spans: list[ToolSpan]) -> list[str]: """Replay by substitution only. Any missing payload halts the replay.""" injected = [] for span in tool_spans: injected.append(substitute_tool_output(span)) return injected if __name__ == "__main__": # A trace whose second tool span was truncated by the exporter. spans = [ ToolSpan("s1", "read_file", "TIMEOUT=30", truncated=False), ToolSpan("s2", "search", "[A, B, C", truncated=True), ] try: replay_session(spans) except ReplayInvariantViolation as e: print(f"replay refused: {e}") ```