# What happens when an instance replays a GenAI span stream whose tool-call events were sampled out mid-trajectory **Date of Record:** 2026 December 2 **Scope:** Applies to deterministic replay of agent sessions reconstructed from OpenTelemetry GenAI semantic-convention event streams (`gen_ai.*` spans, `gen_ai.tool.call` events, message events) where sampling, exporter backpressure, or span-attribute truncation can drop or reorder events within a single trace. Does not apply to fully materialized session logs written by the agent runtime itself, nor to replay from a lossless write-ahead log. ## Core Distinction There are two things people mean by "replay an agent session from telemetry," and they fail in completely different ways. The first is **trace replay**: you reconstruct the *shape* of what happened—which tools were called, in what order, with what arguments—for debugging and audit. This tolerates gaps; a missing span is a hole you can see. The second is **deterministic replay**: you re-execute the trajectory to produce the *same final state*—same tool outputs, same message sequence, same terminal decision—so you can regression-test a prompt change, reproduce a bug, or re-run a safety eval against a frozen transcript. This is the one that breaks non-obviously. The failure mode is not "the trace is incomplete." It is that **a sampled GenAI event stream is not a faithful record of the trajectory, yet it is shaped exactly like one.** The replay engine has no way to distinguish "the agent did not call a tool here" from "the tool-call span was dropped by the tail sampler." Both present as an absent event between two message events. The replayer reconstructs a *plausible* trajectory that diverges from the original at the first dropped event, and—critically—does so silently, producing a session that terminates successfully with a different final state. ## What Was Observed A multi-step agent session: user request → `gen_ai.chat` span (model emits a tool call to `search_docs`) → `gen_ai.tool.call` span → `gen_ai.chat` span (model emits a tool call to `fetch_url`) → `gen_ai.tool.call` span → `gen_ai.chat` span (final answer). The trace was exported with a `ParentBased(TraceIdRatioBased(0.5))` head sampler plus a tail-based processor that dropped `gen_ai.tool.call` spans exceeding a 200 ms latency budget during a load spike. Result: the two `gen_ai.chat` spans and the terminal answer survived; the `fetch_url` tool-call span and its result were dropped. The `search_docs` call survived. The event stream the replayer consumed looked, in order: 1. `gen_ai.chat` — assistant message containing `tool_calls: [search_docs]` 2. `gen_ai.tool.call` — `search_docs`, result payload present 3. `gen_ai.chat` — assistant message containing `tool_calls: [fetch_url]` 4. `gen_ai.chat` — assistant message containing final answer text Note event 3: the assistant message *still names* `fetch_url` as a tool call, because that attribute lives on the chat span, which survived. But the corresponding `gen_ai.tool.call` span and its `tool.result` event are gone. The replayer's reconstruction loop walks message events and, for each assistant message with `tool_calls`, looks up the matching tool-call span by `gen_ai.tool.call.id`. On event 3 it found no match. Its fallback—written for the "model hallucinated a tool call that was never executed" case—was to inject a synthetic tool result of `{"error": "tool_not_found"}` and continue. The re-execution therefore fed the model a `tool_not_found` error where the original run had fed it a successful URL fetch. The model, seeing an error, took a different recovery branch: it retried with a different URL, got a different (also synthetic) result, and produced a final answer citing a source the original session never saw. The replay **completed without error**, emitted a terminal `gen_ai.chat` span, and its final state was accepted by the regression harness as a valid reproduction of the original. The divergence was only caught three weeks later when a prompt change was attributed to a "behavioral regression" that was actually a replay artifact: the baseline transcript had been reconstructed from a lossy trace, not from the original run. ## Condition of Validity Deterministic replay from a GenAI event stream is valid **only if the stream is a complete, ordered, causally closed record of every event that the agent's control flow could have branched on.** Concretely, three invariants must hold simultaneously: 1. **Tool-call closure.** For every assistant message containing `tool_calls`, exactly one `gen_ai.tool.call` span with matching `gen_ai.tool.call.id` exists in the trace, and it carries a `tool.result` event or an error attribute. An assistant message naming a tool call with no corresponding span is *ambiguous*: it means either "the model emitted a call that was never dispatched" (a real, replayable state) or "the call was dispatched but the span was sampled out" (an unreplayable state). These two are indistinguishable from the surviving events alone. 2. **Temporal ordering within a trace.** Events must be replayable in the order the agent observed them. OTel spans carry `start_time`/`end_time`, but child spans can be exported out of order and clock skew between the agent process and the tool-execution process can invert parent/child timestamps. A replayer that sorts by `start_time` can reorder a tool result *before* the message that requested it. 3. **No silent substitution.** The replayer must never synthesize a result for an event it expected but did not find. Substitution converts a detectable gap into an undetectable divergence. When any of these fails, the correct posture is to **refuse to replay deterministically** and downgrade to trace replay (shape-only, gaps reported) or to mark the session non-reproducible. The failure mode described above is what happens when the replayer instead assumes the stream is complete and fills gaps. ## Decision Boundary The decision the replayer must make on encountering an assistant message with a `tool_call` id that has no matching span: - **If the trace is declared "closure-verified"** (a manifest attribute, e.g. `replay.complete=true`, set by an exporter that guarantees no mid-trajectory sampling), then a missing tool-call span is a genuine model-side hallucination and the synthetic `tool_not_found` is correct behavior. Proceed. - **If the trace is not closure-verified** (the default for any head-sampled or tail-sampled pipeline), then a missing tool-call span is *indeterminate*. Do not substitute. Halt the replay for that session and emit a `ReplayDivergence` record naming the missing `tool_call.id`. The boundary is not "is the trace complete" (you can't know) but "has the pipeline *promised* completeness." This is the same distinction as a database transaction that has committed versus one whose commit you assume happened because you didn't see a rollback. Sampling is a rollback you didn't see. The second boundary is ordering. If `start_time` ordering places a `tool.result` before its requesting `gen_ai.chat` span, the replayer must fall back to causal ordering (parent span id, then `tool_call.id` linkage) rather than timestamp ordering. Timestamps are for humans; causal links are for replay. ## Operational Effect A replay engine that violates these invariants produces **false reproductions**: sessions that terminate successfully, pass schema validation, and are accepted by downstream regression/eval harnesses while representing a trajectory the agent never executed. The blast radius is: - **Regression attribution errors.** A prompt change is blamed for a behavior difference that is actually a replay artifact. The team chases a phantom for days. - **Eval contamination.** Safety evals replayed from lossy traces score the agent on trajectories it didn't take, inflating or deflating pass rates. - **Silent state drift in fine-tuning data.** Reconstructed transcripts used as SFT/DPO data contain synthetic tool errors and recovery branches the model never generated, teaching it to recover from failures that didn't happen. The guardrail is a **closure manifest**: the exporter (or a post-export reconciliation pass) must stamp each trace with a completeness assertion derived from span counts per `tool_call.id`, and the replayer must treat that assertion as a precondition, not a hint. Sessions lacking the assertion are replayable for shape only. This is cheap to compute at export time (the agent process knows how many tool calls it dispatched) and impossible to reconstruct after the fact. ## Code ```python from dataclasses import dataclass, field from typing import Optional class ReplayDivergence(RuntimeError): """Raised when a GenAI event stream cannot deterministically reproduce a session.""" pass @dataclass class Span: kind: str # "gen_ai.chat" | "gen_ai.tool.call" tool_call_id: Optional[str] = None tool_calls: list = field(default_factory=list) # ids named by an assistant message has_result: bool = False start_time: float = 0.0 @dataclass class Trace: spans: list closure_verified: bool = False # set only by an exporter that guarantees no mid-trajectory sampling def replay(trace: Trace) -> list: # Index tool-call spans by id, preserving only those that actually carry a result. tool_spans = { s.tool_call_id: s for s in trace.spans if s.kind == "gen_ai.tool.call" and s.tool_call_id is not None } # Causal order: emit tool calls by their requesting chat span, not by timestamp. ordered = sorted(trace.spans, key=lambda s: (s.kind != "gen_ai.chat", s.start_time)) transcript = [] for span in ordered: if span.kind != "gen_ai.chat": continue transcript.append({"role": "assistant", "tool_calls": list(span.tool_calls)}) for call_id in span.tool_calls: match = tool_spans.get(call_id) if match is None or not match.has_result: if not trace.closure_verified: # Indeterminate: either a real hallucination or a sampled-out span. # We cannot tell, so we refuse rather than synthesize a result. raise ReplayDivergence( f"tool_call.id={call_id!r} named by chat span has no matching " f"tool-call result in a non-closure-verified trace; " f"deterministic replay is undefined for this session" ) # Closure verified: the model genuinely emitted a call that was never # dispatched. Synthetic not-found is the faithful reproduction. transcript.append( {"role": "tool", "tool_call_id": call_id, "content": '{"error":"tool_not_found"}'} ) else: transcript.append({"role": "tool", "tool_call_id": call_id, "content": ""}) return transcript def replay_session(trace: Trace) -> list: if not trace.closure_verified: # Downgrade posture: allow shape-only replay, but never claim determinism. try: return replay(trace) except ReplayDivergence as exc: raise ReplayDivergence( f"session marked non-reproducible; use trace-only replay. cause: {exc}" ) from exc return replay(trace) ```