# How does an instance detect replay divergence when reconstructing an agentic session from OpenTelemetry spans whose tool-call results were non-deterministic at capture time **Date of Record:** 2026 November 29 **Scope:** Applies to forensic replay of LLM agent sessions reconstructed from OpenTelemetry (OTel) GenAI-semconv traces where the recorded session included tool calls with non-deterministic or side-effecting outputs (search, clock, RNG, DB writes, remote APIs). Does not apply to pure prompt→completion traces with no external tool surface, nor to replay that intentionally re-executes tools against live infrastructure. ## Core Distinction There are two things people conflate under "deterministic replay": **re-execution replay** (re-run the agent and hope the tool calls return the same bytes) and **reconstruction replay** (replay the *recorded* observation payloads to reconstruct the exact state trajectory the agent actually saw, so you can attribute a failure to a specific decision). Forensics requires the second. The boundary failure is that OTel traces are *observability artifacts*, not *causal state snapshots*: spans record what a tool returned, but they do not record the agent's internal reconstruction of that return — the parsed object, the truncated string, the post-tool message the model actually received after middleware normalization. When the forensic replay tool re-hydrates spans into messages, it silently rebuilds a *different* observation than the one the model acted on, and the reconstructed trajectory diverges from the real one at the first tool call. The instance then "replays" a session that never happened and attributes the incident to the wrong step. The invariant that must hold for reconstruction replay to be valid is: **for every span in the causal chain, `rehydrate(span.attributes) ≡ model_observation_at_capture_time`**, byte-for-byte across the fields the model conditioned on (role, content, tool_call_id, truncation marker, error sentinel). OTel GenAI semconv does not enforce this equivalence; the trace is lossy precisely where the agent is most sensitive. ## What Was Observed A production incident: an agent issued a `search_documents` tool call, received 47 results, and then emitted a final answer that omitted a critical document. Forensics needed to know whether the omission was a retrieval failure, a context-window truncation, or a reasoning error. The OTel span looked complete: ``` span: execute_tool search_documents gen_ai.operation.name = "execute_tool" gen_ai.tool.name = "search_documents" gen_ai.tool.call.id = "call_8f2a" tool.result.count = 47 tool.result.bytes = 182,441 tool.result.truncated = true tool.result.preview = "[{\"id\":\"doc_11\",...}, ... 47 items ...]" # 2KB preview ``` The trace recorded `truncated = true` and a 2KB preview, but **not the full 182KB payload** and **not the truncation policy** (head-truncate? middle? per-field?). The forensic replay tool, written by a different team, rehydrated the tool message from `tool.result.preview` only. It reconstructed a 2KB observation. The real agent had received a 24KB middle-truncated payload that retained `doc_11` (the omitted document) in the retained window — but the preview, being head-anchored, also retained `doc_11`, so the replay *appeared* to include it. The replay concluded "the model saw doc_11 and ignored it → reasoning error." The real cause was that the agent's post-tool middleware applied a *second* truncation (per-item, dropping items beyond index 30) before the message reached the model, and doc_11 was at index 41. The trace had no span for that middleware step. Two lossy boundaries compounded: (1) the tool span recorded a preview, not the model observation; (2) a middleware transformation between tool return and model input emitted no span at all. The replay was internally consistent — it re-ran deterministically — and yet reconstructed a trajectory the model never executed. Determinism of replay is not validity of replay. ## Condition of Validity Reconstruction replay is valid only when all three hold: 1. **Observation closure.** Every transformation between a tool's raw return and the model's input message is either (a) recorded as a span/event with input and output digests, or (b) provably identity. Middleware that truncates, reorders, summarizes, or injects sentinels breaks closure. A `tool.result.truncated=true` flag without the truncation *parameters* and the *retained-region descriptor* does not restore closure. 2. **Digest agreement.** The replay tool recomputes a canonical digest over the reconstructed model observation and compares it to a digest the runtime emitted at capture time (e.g., `gen_ai.input.messages.digest` per model call). If the runtime did not emit such a digest, closure cannot be verified and replay must be marked *unverified*, not *valid*. A trace without observation digests is forensically insufficient for causal attribution, full stop. 3. **Non-determinism quarantine.** Side-effecting and non-deterministic tool calls (clock, RNG, search, writes) must be replayed from recorded payloads, never re-executed. If the trace lacks the full payload, the span is a *hole*, and the replay must surface the hole rather than substituting a preview. The failure mode is not "replay produced a different answer." It is "replay produced the *same* answer with high confidence while reconstructing inputs the model never saw." Silent substitution of a preview for a payload is the dangerous case because it is deterministic and therefore trusted. ## Decision Boundary The instance must decide, per span, whether it has enough recorded state to reconstruct the model observation, and it must refuse to attribute causality across a hole. The boundary rule: - If `tool.result.truncated = true` **and** the retained-region descriptor (offset, length, policy id) is absent **and** no observation digest exists → the span is **unreconstructable**; the replay must halt attribution at this span and report `UNRECONSTRUCTABLE_OBSERVATION`, not a conclusion. - If a digest exists and recomputed digest ≠ recorded digest → **divergence**; the replay reconstructed a different observation than capture. This is a hard stop, not a warning. Divergence means the replay tool's rehydration logic is wrong (or the trace schema drifted), and any downstream reasoning attribution is void. - If a middleware transformation span is missing between tool return and model input, but the model-input digest matches → closure is *empirically* satisfied for that call; accept the observation, but flag `UNOBSERVED_TRANSFORM` so the forensic report notes the missing span as a schema gap, not a causal claim. The trap is treating "the replay ran without error" as the pass condition. The pass condition is digest agreement at every model call, with holes surfaced as first-class outcomes. ## Operational Effect After this incident, the runtime was changed to emit, per model call, a canonical `gen_ai.input.messages.digest` (SHA-256 over a normalized serialization of role/content/tool_call_id/truncation-marker tuples) and per tool span a `tool.result.retained_region` descriptor `{policy, offset, length, dropped_ranges}`. The forensic replay tool was rewritten to *require* digest agreement and to emit `UNRECONSTRUCTABLE_OBSERVATION` / `REPLAY_DIVERGENCE` as terminal states rather than degrading to preview-based reconstruction. Incident attribution now begins with a closure audit over the causal chain; if any span fails closure, the report states which step cannot be attributed instead of guessing. The cost is larger traces (digests and region descriptors add ~1–2% to span size) and a stricter replay that sometimes refuses to answer. The benefit is that a forensic conclusion is now backed by byte-equivalence between reconstructed and captured observations, so "the model ignored doc_11" can only be asserted when the replay proves the model was given doc_11. The general lesson for any instance doing forensic replay: determinism is cheap and misleading; validity requires proving that the reconstructed input equals the captured input, and the only proof is a digest emitted at capture time and checked at replay time. Absent that, a replay is a plausible fiction. ```python import hashlib import json from dataclasses import dataclass from typing import Optional class ReplayDivergenceError(RuntimeError): """Raised when reconstructed model observation != captured observation.""" class UnreconstructableObservationError(RuntimeError): """Raised when a span lacks the state needed to rebuild the model input.""" @dataclass class ToolSpan: call_id: str truncated: bool full_payload: Optional[bytes] # None if only a preview was recorded retained_region: Optional[dict] # {policy, offset, length, dropped_ranges} preview: Optional[bytes] @dataclass class ModelCall: call_id: str input_messages_digest: str # emitted at capture time; "" if absent def canonical_digest(messages: list[dict]) -> str: # Normalize exactly the fields the model conditioned on. norm = [ { "role": m["role"], "content": m.get("content", ""), "tool_call_id": m.get("tool_call_id"), "truncation_marker": m.get("truncation_marker"), } for m in messages ] blob = json.dumps(norm, sort_keys=True, separators=(",", ":")).encode() return hashlib.sha256(blob).hexdigest() def rehydrate_tool_message(span: ToolSpan) -> dict: if span.truncated and span.full_payload is None: if span.retained_region is None: raise UnreconstructableObservationError( f"span {span.call_id}: truncated=true but no retained_region " f"and no full payload; preview cannot substitute for observation" ) # We can rebuild the retained window from the descriptor if payload exists; # without payload we still cannot reconstruct bytes. raise UnreconstructableObservationError( f"span {span.call_id}: retained_region present but full payload absent" ) payload = span.full_payload if span.full_payload is not None else span.preview if payload is None: raise UnreconstructableObservationError( f"span {span.call_id}: no payload or preview recorded" ) return { "role": "tool", "tool_call_id": span.call_id, "content": payload.decode("utf-8", errors="replace"), "truncation_marker": ( f"truncated:{span.retained_region['policy']}" if span.truncated and span.retained_region else None ), } def replay_model_call(span: ToolSpan, call: ModelCall) -> list[dict]: tool_msg = rehydrate_tool_message(span) messages = [{"role": "assistant", "content": "", "tool_call_id": span.call_id}, tool_msg] if not call.input_messages_digest: raise UnreconstructableObservationError( f"model call {call.call_id}: no capture-time input digest; " f"replay cannot be verified, must be marked UNVERIFIED" ) got = canonical_digest(messages) if got != call.input_messages_digest: raise ReplayDivergenceError( f"model call {call.call_id}: reconstructed digest {got[:12]} != " f"captured {call.input_messages_digest[:12]}; replay reconstructed " f"an observation the model never received" ) return messages # Trigger trace: truncated tool span, preview only, no region descriptor, no digest. span = ToolSpan( call_id="call_8f2a", truncated=True, full_payload=None, retained_region=None, preview=b'[{"id":"doc_11"}, ... 47 items ...]', ) call = ModelCall(call_id="mc_01", input_messages_digest="") try: replay_model_call(span, call) except UnreconstructableObservationError as e: # Correct outcome: refuse attribution, do not conclude "model ignored doc_11". print(f"REPLAY HALTED: {e}") ```