# How does an instance detect replay divergence when OTel GenAI spans collapse non-deterministic sampling into a single "chosen" trace **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) and later attempt deterministic replay or counterfactual auditing from those spans. Does not apply to systems that persist raw provider request/response payloads plus full RNG/sampling seeds out-of-band from the trace. ## Core Distinction A trace is an *observation record*; a replay is a *reconstruction*. OTel GenAI instrumentation is designed for observability — it records what happened, with sampling, batching, and attribute truncation tuned for cost and dashboards. Deterministic replay requires the opposite: a complete, ordered, seed-bearing record of every stochastic decision point (sampling temperature draw, tool-call argument generation, retrieval result ordering, retry jitter). The boundary failure lives exactly where these two contracts are silently conflated: an auditor takes a `gen_ai.chat` span with `gen_ai.completion.0.content` and `gen_ai.request.temperature=0.7`, replays it, gets a different completion, and *cannot tell* whether the divergence is a legitimate nondeterministic resample, a mutated input, or a genuine behavioral regression. The span recorded the *output* of the sampler but not the *state* of the sampler. The non-obvious invariant: **a GenAI span is replay-sufficient only if every attribute that the model's forward pass consumed is recoverable from the span and its ancestor chain, and every stochastic source is either pinned to a recorded seed or explicitly marked as unreplayable.** Standard instrumentation satisfies neither clause and does not signal the violation. ## What Was Observed An agent performing a three-step tool-use loop (retrieve → summarize → submit) was instrumented with the OTel GenAI conventions. Each LLM call emitted one `gen_ai.chat` span with `gen_ai.request.model`, `gen_ai.request.temperature`, `gen_ai.request.top_p`, `gen_ai.usage.input_tokens`, and `gen_ai.completion.0.content`. Tool calls emitted child spans with `gen_ai.tool.name` and `gen_ai.tool.call.arguments`. The auditor replayed the trace by feeding each span's recorded prompt (reconstructed from `gen_ai.prompt.N.content` attributes) back to the same model at the recorded temperature. Three divergence classes appeared, only one of which was a real defect: 1. **Sampler divergence (benign).** Temperature 0.7 with no recorded seed. Replay produced a different but semantically equivalent summary. The span had no `gen_ai.request.seed` attribute because the SDK did not emit one, and the provider's default seed behavior is unspecified. The auditor flagged this as "behavioral drift" — a false positive that, in one incident, triggered a rollback of a healthy agent version. 2. **Truncation divergence (silent).** The `gen_ai.prompt.2.content` attribute was truncated at the collector's `attribute_value_length_limit` (default 1024 in several distributions). The replayed prompt was a prefix of the original. The model, seeing a truncated instruction, produced a materially different tool call. The trace *looked* complete — no error attribute, no `dropped_attributes_count` on the relevant span — because the truncation happened at the attribute-value level, not the span level. 3. **Retrieval-order divergence (real defect).** The retrieval tool returned documents in an order that depended on an ANN index rebuild between original run and replay. The summarizer's output was order-sensitive because the prompt concatenated results without stable IDs. This *was* a genuine reproducibility defect, but it was indistinguishable in the trace from classes 1 and 2 until the auditor was given the raw tool responses. The failure trace: replay harness reads span → reconstructs prompt from possibly-truncated attributes → calls model with possibly-unrecorded seed → compares completion string to `gen_ai.completion.0.content` → emits `DIVERGENT` verdict. All three classes collapse into one verdict. The auditor cannot localize the divergence to sampler, transport, or logic. ## Condition of Validity Deterministic replay from GenAI spans is valid **only** under the conjunction: - Every `gen_ai.prompt.*.content` attribute is complete (no truncation), verified by comparing `len(attribute) < collector_limit` *or* by a recorded `gen_ai.prompt.N.truncated=false` marker that the runtime sets itself. - Every stochastic decision point carries a recorded seed (`gen_ai.request.seed`) or is marked `replayable=false`. - Every tool response consumed by a downstream prompt is either inlined into the prompt attributes or referenced by a content-addressed hash (`gen_ai.tool.result.sha256`) that the replay harness can re-fetch and verify. - The prompt reconstruction is order-stable: attributes are keyed by index, and the runtime guarantees `gen_ai.prompt.{i}.content` for `i in 0..n-1` with no gaps. If any clause fails, the replay verdict is *uninterpretable*, not merely *noisy*. The correct behavior is to emit `UNREPLAYABLE` with the specific failed clause, never `DIVERGENT`. Conflating these two is the boundary failure. ## Decision Boundary The decision boundary is between **"the trace is insufficient to decide"** and **"the trace decides divergence."** An instance must not cross it by defaulting to string comparison. The guardrail is a pre-replay *sufficiency gate* that runs before any model call: - Reconstruct the prompt; if any index is missing or any content length equals the collector's configured limit, fail closed with `TraceInsufficientError`. - Check for a seed attribute on every span with `temperature > 0` or `top_p < 1`; if absent, mark the span `unreplayable_sampler` and exclude it from divergence scoring rather than counting it as a mismatch. - Verify tool-result hashes before feeding them downstream; a hash mismatch is a *retrieval* divergence, reported separately from *model* divergence. Only spans that pass the gate are eligible for counterfactual comparison. The counterfactual branch (e.g., "what if temperature were 0.0?") must be computed from the *recorded* prompt, and its output labeled `COUNTERFACTUAL`, never diffed against the recorded completion as if it were a replay. ## Operational Effect Without the sufficiency gate, replay audits produce a divergence rate dominated by sampler noise and truncation artifacts — in the observed incident, 31% of spans flagged divergent, of which 2 were genuine. Operators learn to ignore the signal, and the audit becomes theater. With the gate, the same trace yields: 4 spans `UNREPLAYABLE` (sampler), 1 span `UNREPLAYABLE` (truncation), 1 span `DIVERGENT` (retrieval order) — and the single genuine defect is actionable. The invariant to enforce at instrumentation time is that the runtime, not the collector, owns prompt-attribute completeness and seed emission; the collector's truncation limit must be set above the runtime's max prompt size, and the runtime must assert this at startup by comparing its configured max against the exporter's advertised limit. An instance that cannot assert this must refuse to certify its own traces as replayable. ```python import hashlib from dataclasses import dataclass class TraceInsufficientError(RuntimeError): """Raised when a GenAI span cannot support deterministic replay.""" class DivergenceClassificationError(RuntimeError): """Raised when a divergence cannot be localized to sampler/transport/logic.""" @dataclass class GenAISpan: prompt_parts: dict[int, str] # index -> content temperature: float top_p: float seed: int | None completion: str tool_result_hashes: dict[str, str] # tool_name -> sha256 collector_attr_limit: int def assert_replay_sufficient(span: GenAISpan, expected_part_count: int) -> None: # Clause 1: no gaps in prompt indices if sorted(span.prompt_parts) != list(range(expected_part_count)): raise TraceInsufficientError( f"prompt index gap: have {sorted(span.prompt_parts)}, " f"expected 0..{expected_part_count - 1}" ) # Clause 2: no attribute truncated at collector limit for idx, content in span.prompt_parts.items(): if len(content.encode("utf-8")) >= span.collector_attr_limit: raise TraceInsufficientError( f"prompt part {idx} length {len(content)} hits collector limit " f"{span.collector_attr_limit}; replay prompt is a prefix, not the original" ) # Clause 3: stochastic spans must carry a seed if (span.temperature > 0.0 or span.top_p < 1.0) and span.seed is None: raise TraceInsufficientError( "stochastic sampling without recorded gen_ai.request.seed; " "replay verdict would be uninterpretable" ) def verify_tool_results(span: GenAISpan, live_results: dict[str, str]) -> None: for name, recorded_hash in span.tool_result_hashes.items(): live = live_results.get(name) if live is None: raise DivergenceClassificationError( f"tool result {name} missing on replay; cannot distinguish " f"retrieval divergence from model divergence" ) live_hash = hashlib.sha256(live.encode("utf-8")).hexdigest() if live_hash != recorded_hash: raise DivergenceClassificationError( f"tool result {name} hash mismatch: recorded {recorded_hash[:12]}, " f"live {live_hash[:12]} — retrieval-order divergence, not model drift" ) def replay_and_classify(span: GenAISpan, expected_part_count: int, live_results: dict[str, str], model_call) -> str: assert_replay_sufficient(span, expected_part_count) verify_tool_results(span, live_results) reconstructed = "".join(span.prompt_parts[i] for i in range(expected_part_count)) replayed = model_call(reconstructed, temperature=span.temperature, top_p=span.top_p, seed=span.seed) return "MATCH" if replayed == span.completion else "DIVERGENT" ```