# What structural signals indicate replay divergence in counterfactual auditing of OpenTelemetry GenAI agent traces **Date of Record:** 2026 November 21 **Scope:** Applies to counterfactual auditing of agent trajectories reconstructed from OpenTelemetry GenAI semantic-convention spans (e.g., `gen_ai.chat`, `gen_ai.tool.call`, `execute_tool`) where the auditor attempts to deterministically re-execute or re-derive a decision point from the trace. Does not apply to live shadow-traffic replay against a serving endpoint, nor to single-span prompt/response logging audits where no agent loop is reconstructed. ## Core Distinction A trace is a *record of what the agent observed*, not a *record of what the agent reasoned over*. The GenAI semantic conventions capture inputs and outputs at each span boundary — the prompt messages sent, the completion text returned, the tool call arguments, the tool result payloads. What they do not capture, and cannot capture without an explicit instrumentation contract, is the *derived state the agent actually conditioned on*: the assembled context window after truncation, the retrieval results that were silently dropped, the system-prompt version hash, the sampling temperature and seed, the exact ordering of tool results that arrived concurrently. Deterministic replay fails at a specific, non-obvious boundary: it succeeds at the *span level* (each recorded completion can be reproduced or diffed) while silently diverging at the *trajectory level* (the reconstructed sequence of decisions no longer corresponds to the one that produced the outcome). The structural signal of this divergence is not an error — it is a **replay that produces a plausible, internally consistent, but counterfactually different trajectory**. The auditor sees no exception. The trace "replays cleanly." The divergence is invisible precisely because it is coherent. The invariant that must hold for counterfactual auditing to be sound is: *every state transition in the reconstructed trajectory must be a function of inputs that are fully recoverable from the trace.* When a transition depends on state that the trace only partially encodes, replay is not deterministic — it is a re-sampling that happens to look like a replay. ## What Was Observed A multi-step agent handling a support-ticket triage task was traced with standard GenAI spans. Each `gen_ai.chat` span recorded `gen_ai.request.model`, `gen_ai.request.temperature`, the input messages, and the output message. Each tool span recorded the tool name, arguments, and the returned payload. The auditor selected a decision point at turn 7 — the agent classified a ticket as "billing" and routed it — and attempted to replay from turn 6's recorded state to test a counterfactual: *what if the retrieval tool had returned the customer's contract document instead of timing out?* Three structural signals indicated the replay had diverged before it produced its answer: 1. **Context-window assembly was not in the trace.** Turn 7's `gen_ai.chat` span recorded the *messages sent*, which included a 4,100-token system prompt and 6 prior turns. It did not record that the runtime had dropped turns 2 and 3 to fit the budget. The replay, reconstructing from the full span history, re-included turns 2 and 3. The counterfactual answer changed — not because of the contract document, but because the replay had a different context than the original. 2. **Tool-result ordering was lossy.** Two tool calls at turn 6 (a CRM lookup and a knowledge-base search) completed within 40ms of each other and were recorded as sibling spans under the same `gen_ai.chat` parent. The trace's span ordering reflects *export* order, not *consumption* order. The original agent consumed the KB result first; the replay consumed the CRM result first. The classification flipped on the ordering alone. 3. **The completion was re-generated, not re-derived.** The replay called the model again with `temperature=0`. Temperature zero is not determinism: it is greedy decoding over a floating-point logit distribution that depends on batch composition, hardware, and inference-engine version. The replayed completion differed from the recorded one at token 312 of 480, and the divergence cascaded through turns 7–9. The counterfactual audit returned a confident, well-formed conclusion — "the contract document would have changed the routing to 'legal'" — that was an artifact of all three divergences and corresponded to no trajectory the original agent could have taken. ## Condition of Validity Counterfactual replay from GenAI traces is valid only when all of the following hold. Each is a checkable precondition, and the audit must *fail closed* when any is unmet rather than proceed with a plausible reconstruction. - **Context assembly is logged.** The trace must record the exact message list *as assembled for the model call*, not the logical conversation history. This means a span attribute capturing the post-truncation, post-summarization payload — or a content hash of it plus a retrievable store. If the runtime truncates, summarizes, or reorders, that transformation must be a span. - **Consumption order is explicit.** Concurrent tool results must carry a monotonically increasing consumption sequence attribute (e.g., `agent.tool.consumed_seq`) assigned by the runtime at the point the agent reads them, not by the exporter. Sibling span order is not a substitute. - **Sampling parameters and model identity are pinned.** `gen_ai.request.temperature`, `top_p`, `seed`, and a model *version* (not just family name) must be present. Absent a seed and a pinned engine, "temperature=0" replay must be treated as non-deterministic and the audit must record the divergence rate rather than assert a single counterfactual. - **The counterfactual is applied at a single, well-typed boundary.** The perturbation (e.g., "tool returned X instead of timeout") must be injected at exactly one span's output and the replay must proceed forward from there. Perturbations that change context assembly are not counterfactuals about the tool — they are counterfactuals about the runtime, and must be labeled as such. - **Divergence is measured, not assumed absent.** Every replayed completion must be diffed against the recorded completion at the token level. Any divergence before the perturbation point invalidates the counterfactual. ## Decision Boundary The boundary between a *sound* counterfactual audit and an *unsound* one is not whether the replay ran without error. It is whether the replay reproduced the recorded trajectory **up to the perturbation point**, token-for-token and state-for-state. This yields a sharp operational rule: - If replay reproduces the recorded trajectory exactly through the perturbation point, the counterfactual result is admissible and can be reported as "the agent would have done X." - If replay reproduces the trajectory through the perturbation point but diverges afterward, the result is admissible *only* as "under replay conditions, the agent did X" — with the divergence rate reported. - If replay diverges *before* the perturbation point, the audit is void. The divergence is the finding, and the finding is that the trace is under-instrumented for the question being asked. The subtle failure is the middle case being reported as the first. A replay that diverges at turn 7 due to context-assembly loss but still produces a coherent turn-8 decision will look, to a downstream consumer, like a valid counterfactual. The structural signal that distinguishes the cases is the **pre-perturbation token diff**: it must be computed and it must be zero. If the instrumentation does not make that diff computable — because context assembly was not logged — the audit must refuse to run, not run and caveat. ## Operational Effect The practical consequence is that counterfactual auditing over GenAI traces is a *trace-quality gate*, not a replay engine. Before any counterfactual is evaluated, the auditor must verify that the trace satisfies the instrumentation contract above; traces that do not are quarantined rather than audited. This inverts the usual workflow: instead of "replay and report," the workflow is "certify replayability, then replay." For agent runtimes, this imposes three concrete instrumentation obligations that are cheap to satisfy and expensive to omit: log the assembled context payload (or its hash plus store reference) per model call; stamp tool results with a runtime-assigned consumption sequence; and pin model version and sampling seed alongside every completion. Without these, the trace is a narrative, not a reproducible record — and a counterfactual audit built on it produces confident fiction. ```python from dataclasses import dataclass from typing import Optional class ReplayDivergenceError(RuntimeError): """Raised when a counterfactual replay cannot be certified sound.""" @dataclass class SpanRecord: span_id: str kind: str # "chat" | "tool" assembled_context_hash: Optional[str] # None if runtime did not log it consumption_seq: Optional[int] # None if runtime did not stamp it model_version: Optional[str] seed: Optional[int] output_tokens: Optional[list] def certify_replayable(spans: list[SpanRecord], perturbation_span_id: str) -> None: """Fail closed unless the trace satisfies the counterfactual-audit contract.""" seen_perturbation = False for span in spans: if span.span_id == perturbation_span_id: seen_perturbation = True break if span.kind == "chat": if span.assembled_context_hash is None: raise ReplayDivergenceError( f"chat span {span.span_id} lacks assembled_context_hash; " "context assembly is not recoverable, replay would re-sample" ) if span.model_version is None or span.seed is None: raise ReplayDivergenceError( f"chat span {span.span_id} lacks pinned model_version/seed; " "temperature=0 is not determinism" ) elif span.kind == "tool": if span.consumption_seq is None: raise ReplayDivergenceError( f"tool span {span.span_id} lacks consumption_seq; " "sibling span order reflects export order, not agent consumption order" ) if not seen_perturbation: raise ReplayDivergenceError( f"perturbation span {perturbation_span_id} not found in trace" ) def run_counterfactual(spans: list[SpanRecord], perturbation_span_id: str, recorded_tokens: list, replayed_tokens: list) -> str: certify_replayable(spans, perturbation_span_id) if recorded_tokens != replayed_tokens: # Divergence before the perturbation point voids the audit. raise ReplayDivergenceError( "replay diverged from recorded trajectory before perturbation; " "counterfactual result is inadmissible" ) return "admissible" ```