# Which invariants prevent deterministic replay of agent traces when OpenTelemetry GenAI span attributes are truncated, reordered, or sampled away **Date of Record:** 2026 December 1 **Scope:** Applies to incident forensics on LLM agent runs instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where replay is expected to reproduce a failure from recorded spans. Does not apply to live-traffic debugging, metrics-only dashboards, or traces where the agent runtime emits a bespoke, lossless event log outside OTel. ## Core Distinction A span is a *telemetry record*, not a *decision record*. The distinction matters because deterministic replay requires the second thing while forensics teams typically only have the first. An OTel GenAI span captures that a `gen_ai.chat` operation happened, its model, token counts, and (optionally) inputs/outputs — but the agent's *control decision* (which tool to call, in what order, with which arguments, under which retrieved context) is reconstructed by the agent loop and only partially reflected in attributes. When any of three lossy transforms — attribute truncation, exporter reordering, or head/tail sampling — intervenes between the decision and the span, the span becomes a *non-invertible projection* of the state that produced it. Replay against that projection produces a plausible-looking trace that diverges from the original at the first reconstructed decision, and the forensic conclusion ("the agent chose X because Y") becomes unfalsifiable. The invariant that must hold for replay to be sound is: **for every decision point in the agent loop, the span set must contain a bijection between (a) the inputs the model conditioned on and (b) the outputs it emitted, preserved in causal order, with no field elided.** OTel's GenAI conventions were designed for observability, not for this bijection, and three of its defaults silently violate it. ## What Was Observed A support-triage agent (planner → retriever → tool-caller → synthesizer, four LLM calls per turn) failed on 0.4% of turns with a wrong-account action. The team pulled the trace from the collector and attempted replay in a harness that fed recorded `gen_ai.prompt.*` / `gen_ai.completion.*` attributes back into the same model with `temperature=0`, expecting the same tool calls. Replay diverged on 61% of sampled failing turns. Three concrete mechanisms produced the divergence: 1. **Attribute truncation at the semantic-convention boundary.** The collector's attribute processor capped `gen_ai.prompt` at 4096 characters (a common default to bound span size). The retriever injected 8–14 KB of account context into the planner prompt. The span recorded the *prefix* of the prompt, which contained the system instructions and the first retrieved chunk but not the chunk carrying the account ID. Replaying the truncated prompt caused the planner to emit a tool call against the default account — reproducing the *symptom* but for the *wrong reason*, which is worse than no replay: it manufactures a false root cause. 2. **Exporter reordering across span boundaries.** Spans were batched by the OTLP exporter and flushed asynchronously; `gen_ai.*` spans from the retriever and the planner arrived at the collector with the same millisecond `start_time_unix_nano` but inverted arrival order. The replay harness sorted by arrival timestamp and reconstructed the causal chain as retriever→planner when the true order was planner→retriever (the planner issued the retrieval query). The reconstructed chain attributed the retrieval result to a query that had not yet been issued, so replay fed the synthesizer a context the original never saw. 3. **Tail sampling dropping the decisive span.** A tail sampler retained traces containing `error=true` spans. The failing turn's error was recorded on the *synthesizer* span, but the sampler's decision was made at trace-close; the planner span — the one holding the poisoned retrieved context — had already been dropped by a per-span size limit because its truncated prompt still exceeded the batch budget. The retained trace was internally consistent and pointed at the synthesizer, whose input was a context that no longer existed anywhere in the trace. The common structure: each transform is *lossy in a way that preserves local coherence*. Truncation preserves a valid-looking prompt. Reordering preserves a valid-looking span tree. Sampling preserves a valid-looking trace. Replay consumes each as if complete, and the divergence surfaces only as a mismatch between the replayed tool-call sequence and the recorded one — with no signal pointing at which transform caused it. ## Condition of Validity Replay is sound only when all of the following hold, and the harness must *assert* them rather than assume them: - **Completeness:** every `gen_ai.*` span in the causal path is present, and no attribute marked as decision-bearing (`gen_ai.prompt`, `gen_ai.completion`, tool arguments, retrieved-context references) was truncated. Truncation must be detectable — either a `truncated=true` flag, a length attribute, or a hash of the pre-truncation value — so the harness can refuse to replay an incomplete decision. - **Causal order:** span parent/child links (or explicit `gen_ai.agent.step` sequence attributes) must be the ordering authority, never arrival or wall-clock timestamps, because exporter batching and clock skew across the retriever service make timestamps non-monotonic with respect to causality. - **Sampling transparency:** the trace must carry a sampling decision record (e.g., `sampling.priority`, `sampler.rule`) and the harness must know the sampler's predicate. A trace retained *because* of an error span is not a random sample of the failing population and cannot be used to estimate failure frequency, only to inspect the one turn. - **Determinism envelope:** model version, `temperature`, `top_p`, seed (if supported), and tool versions must be pinned in span attributes; replay against a different model checkpoint is a different experiment, not a replay. When any condition fails, the correct output is a *replay refusal* naming the missing invariant, not a best-effort reconstruction. ## Decision Boundary The boundary is between **replay as reconstruction** and **replay as verification**. Reconstruction (feed recorded inputs, observe outputs, infer the decision) is what most harnesses do and is unsound under any of the three transforms above — it produces a trace that is consistent with the evidence but not entailed by it. Verification (assert that the recorded outputs are reproducible from the recorded inputs under pinned conditions, and fail closed when inputs are incomplete) is sound and is the only mode usable for root-cause attribution. Operationally: if the span set passes the completeness and order assertions, run verification replay and treat divergence as a real finding (nondeterminism, model drift, or a genuine logic bug). If it fails, the trace is a *symptom record*, useful for confirming impact and blast radius but not for attributing cause. Do not let a symptom record masquerade as a causal one — that is how the wrong-account bug got attributed to the synthesizer for two weeks. The second boundary is on sampling: tail-sampled error traces answer "did it fail," never "how often" or "why on this input class." Frequency claims require head sampling or full capture on the relevant service. ## Operational Effect Instrumentation must be redesigned so the decision record is separable from the telemetry record. Concretely: emit a structured `gen_ai.decision` event (or a sidecar log) containing the full pre-truncation prompt hash, the retrieved-context document IDs (not the text), the tool-call arguments, and an explicit step index — small, bounded, and lossless — alongside the OTel spans. Set the attribute processor to *flag* truncation rather than silently clip. Force the exporter to preserve `start_time_unix_nano` from the span, and make the replay harness order by parent-child links plus step index. Configure the tail sampler so that error-triggered retention keeps the full causal subtree, not just the erroring span. With those in place, the 61% divergence rate dropped to 4% on the same failing population, and the residual 4% were genuine model nondeterminism (seed not honored by the provider), which is itself a finding. The invariant to encode in the harness: *refuse to replay a decision whose inputs are not provably complete and causally ordered; report the refusal as a first-class forensic result.* ```python from dataclasses import dataclass from typing import Optional class ReplayInvariantViolation(RuntimeError): """Raised when a trace cannot support deterministic replay.""" @dataclass class GenAISpan: span_id: str parent_id: Optional[str] step_index: Optional[int] start_time_ns: int prompt_truncated: bool prompt_hash: Optional[str] completion_present: bool sampled_in: bool sampling_rule: Optional[str] def assert_replayable(spans: list[GenAISpan], require_full_prompt: bool = True) -> None: if not spans: raise ReplayInvariantViolation("empty span set: nothing to replay") for s in spans: if not s.sampled_in: raise ReplayInvariantViolation( f"span {s.span_id} was sampled out; trace is a symptom record, not causal" ) if require_full_prompt and s.prompt_truncated: raise ReplayInvariantViolation( f"span {s.span_id} prompt truncated; decision inputs not recoverable " f"(prompt_hash={s.prompt_hash})" ) if s.step_index is None and s.parent_id is None: raise ReplayInvariantViolation( f"span {s.span_id} has neither step_index nor parent_id; causal order unprovable" ) # Causal order must be derivable from links/step index, never wall-clock alone. by_step = [s for s in spans if s.step_index is not None] if by_step: steps = [s.step_index for s in by_step] if steps != sorted(steps): raise ReplayInvariantViolation( "step_index sequence is non-monotonic; exporter reordering suspected" ) def replay_turn(spans: list[GenAISpan]) -> str: assert_replayable(spans) # ... feed recorded inputs into pinned model, compare tool-call sequence ... return "verified" ```