# When must an instance's replay diverge: counterfactual auditing of agentic traces under OpenTelemetry GenAI schemas **Date of Record:** 2026 November 22 **Scope:** Applies to post-hoc deterministic replay and counterfactual auditing of agent execution traces exported under the OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes, span events for tool calls, and message payloads). Does not apply to live in-process re-execution where the original runtime object graph is still resident, nor to traces missing tool-call argument payloads. ## Core Distinction A trace is *replayable* when re-running the recorded inputs reproduces the recorded outputs. A trace is *auditable* when the auditor can distinguish "the model would have done otherwise" from "the harness fed it something different." These are not the same property, and the OpenTelemetry GenAI schema conflates them by design: it records what the instrumented SDK *chose to emit*, not what the model actually consumed. The failure mode this record addresses is **silent replay divergence under schema-legal trace mutation** — a replay that diverges not because of model nondeterminism but because the GenAI attributes omit a load-bearing input (system prompt prefix, tool-schema version, sampling seed, or a redacted message part), and the auditor attributes the divergence to the agent's reasoning rather than to the trace's incompleteness. The sharp version: a counterfactual audit asks "what would the agent have done if we changed X?" If X is *within* the emitted schema but a second load-bearing variable Y is *outside* it, the audit silently holds Y constant at a value the original run never used. The divergence you observe is real, but it is not the counterfactual you claimed to test. ## What Was Observed A three-tool agent (retrieval, calculator, file-writer) was traced with `opentelemetry-instrumentation-openai` emitting `gen_ai.request.model`, `gen_ai.request.temperature`, `gen_ai.usage.input_tokens`, and per-message span events. The auditor replayed 10,000 successful traces under a counterfactual: "raise `gen_ai.request.temperature` from 0.0 to 0.7 and measure tool-selection stability." Roughly 11% of replays diverged in tool selection. The naive read: the agent's tool selection is temperature-sensitive. The correct read, found only after diffing the raw HTTP request bodies against the emitted spans: - The instrumentation emitted `temperature` but **not** `top_p`, `seed`, or the `tools` array ordering. The original runs used `top_p=0.9` and a `tools` array whose order varied by a capability-negotiation cache (see the A2A capability handshake). The replay harness defaulted `top_p=1.0` and sorted tools alphabetically. - The instrumentation truncated `gen_ai.system` message content at 4 KiB per event, so long retrieval results were cut mid-JSON. The agent's original run saw full tool output; the replay saw truncated output that failed a downstream `json.loads`, triggering a different fallback branch in 3% of cases. - `gen_ai.usage.input_tokens` was emitted but the actual prompt assembly (system prompt + tool schemas + retrieved context) was *not* — the system prompt was a runtime-injected constant that changed between the original run and the replay window (a prompt-version bump deployed 40 minutes after the trace was captured). The 11% divergence decomposed as: ~6% attributable to `top_p`/`seed` defaults, ~3% to truncation-induced fallback, ~2% to prompt-version drift. **Zero percent** was attributable to the counterfactual variable (`temperature`) the audit claimed to test. The audit was measuring the harness's defaults, not the agent's sensitivity. ## Condition of Validity A counterfactual replay audit is valid only when the following invariant holds for every load-bearing input to the model call: > **Replay Fidelity Invariant (RFI):** For each span `S` in the trace, the tuple `(prompt_bytes, tool_schema_bytes, sampling_params, seed)` used in the replay must be byte-identical to the tuple used in the original run, *except* for the single variable under counterfactual manipulation. The OpenTelemetry GenAI schema as currently specified does **not** guarantee RFI. It guarantees *observability* of a subset of the tuple. Three concrete gaps: 1. **Sampling params are partial.** `gen_ai.request.temperature`, `max_tokens`, `top_k` are conventional; `top_p`, `frequency_penalty`, `presence_penalty`, and `seed` are optional and frequently omitted. A replay harness that defaults missing params is not replaying — it is re-sampling under a different distribution. 2. **Message content is lossy.** Span events carry message parts, but redaction, size limits, and multimodal-part omission are schema-legal. A trace can be schema-valid and non-replayable. 3. **No schema version pin on tool definitions.** `gen_ai.tool.definitions` (or the equivalent message part) is not versioned against the agent's capability manifest. Tool schema drift between capture and replay is invisible. The RFI is checkable at replay time: hash the reconstructed request tuple and compare to a hash recorded *at capture time* in a span attribute (e.g., `gen_ai.request.fingerprint`). If the schema does not carry that fingerprint, the auditor must reconstruct it from out-of-band logs — and if those are unavailable, the audit must be *refused*, not silently degraded. ## Decision Boundary The boundary is between **divergence-as-signal** and **divergence-as-artifact**. An auditor crosses the line into artifact territory the moment any of the following is true: - A load-bearing sampling parameter is absent from the trace and the replay harness supplies a default. (Artifact: the default, not the model, is the cause.) - A message part is truncated, redacted, or omitted, and the replay path reaches a branch that depends on the omitted content. (Artifact: truncation, not reasoning, is the cause.) - The tool schema or system prompt version at replay time differs from capture time and the trace does not pin the version. (Artifact: drift, not the counterfactual, is the cause.) - The model served at replay time is a different snapshot than `gen_ai.request.model` names (e.g., a provider silently rolling `gpt-4o-2024-08-06` to a newer build under the same alias). (Artifact: model substitution.) When any of these hold, the correct operational action is to **quarantine the trace from the counterfactual cohort** and record the reason. The wrong action — the one that produces plausible-looking but false sensitivity reports — is to proceed and attribute the divergence to the manipulated variable. The decision rule is: *if the replay request fingerprint does not match the capture fingerprint, the trace is not a counterfactual sample; it is a fresh sample under an unknown distribution.* A second, subtler boundary: even with a perfect fingerprint match, a replay that diverges is only evidence of *model* nondeterminism if the provider guarantees determinism at the recorded `temperature`/`seed`. Most providers do not, even at `temperature=0`, because of batch-invariant kernel nondeterminism in MoE routing and attention. So the audit must further distinguish "the agent would have done otherwise" from "the same agent, same input, would have done otherwise on a different day." The former is a counterfactual finding; the latter is a reproducibility floor that bounds the resolution of *any* counterfactual audit. ## Operational Effect The invariant changes three operational practices: 1. **Capture-time fingerprinting is mandatory, not optional.** Every model-call span must carry a content hash over `(system_prompt, tool_schemas, messages, sampling_params, model_snapshot)`. Without it, replay is unverifiable. This is an extension to the GenAI schema, not a use of it — the schema as written does not require it, which is precisely the gap. 2. **Replay harnesses must fail closed on missing params.** A harness that defaults `top_p` to 1.0 when the trace omits it is not a replay tool; it is a fresh-sampling tool wearing a replay tool's name. The harness must raise on any load-bearing parameter it cannot reconstruct, and the auditor must record the quarantine. 3. **Counterfactual cohorts must be stratified by fingerprint class.** Traces that share a fingerprint are comparable; traces across fingerprint classes are not. Mixing them produces sensitivity estimates that are actually a mixture of the counterfactual effect and the fingerprint-drift effect, with no way to separate them post hoc. The practical consequence: the 11% divergence in the observed case was not a finding about temperature sensitivity. It was a finding about the instrumentation's coverage. Reported as the former, it would have driven a temperature-tuning change that did nothing. Reported as the latter, it drove a schema extension (fingerprint attribute) and a harness change (fail-closed on missing params) that made subsequent audits trustworthy. The distinction is the entire value of the invariant. ```python import hashlib import json from dataclasses import dataclass from typing import Any class ReplayFidelityViolation(RuntimeError): """Raised when a trace cannot be replayed under the Replay Fidelity Invariant.""" @dataclass(frozen=True) class RequestFingerprint: system_prompt: str tool_schemas: list[dict[str, Any]] messages: list[dict[str, Any]] sampling_params: dict[str, Any] model_snapshot: str def digest(self) -> str: canonical = json.dumps( { "system_prompt": self.system_prompt, "tool_schemas": self.tool_schemas, "messages": self.messages, "sampling_params": self.sampling_params, "model_snapshot": self.model_snapshot, }, sort_keys=True, separators=(",", ":"), ) return hashlib.sha256(canonical.encode("utf-8")).hexdigest() REQUIRED_SAMPLING_KEYS = ("temperature", "top_p", "seed", "max_tokens") def reconstruct_fingerprint(span: dict[str, Any]) -> RequestFingerprint: """Rebuild the request tuple from a GenAI span. Fail closed on any gap.""" attrs = span.get("attributes", {}) sampling = {} for key in REQUIRED_SAMPLING_KEYS: otel_key = f"gen_ai.request.{key}" if otel_key not in attrs: raise ReplayFidelityViolation( f"span {span.get('span_id')!r} omits load-bearing sampling param " f"{otel_key!r}; replay would default it and silently re-sample" ) sampling[key] = attrs[otel_key] if "gen_ai.request.model_snapshot" not in attrs: raise ReplayFidelityViolation( f"span {span.get('span_id')!r} names model alias " f"{attrs.get('gen_ai.request.model')!r} but not a pinned snapshot; " "provider may have rolled the alias, so divergence is uninterpretable" ) events = span.get("events", []) messages = [e["attributes"] for e in events if e.get("name") == "gen_ai.content.prompt"] if not messages: raise ReplayFidelityViolation( f"span {span.get('span_id')!r} carries no prompt message events; " "cannot reconstruct request bytes" ) for msg in messages: if msg.get("gen_ai.message.truncated") is True: raise ReplayFidelityViolation( f"span {span.get('span_id')!r} has a truncated message part; " "replay would branch on content the original run never lacked" ) return RequestFingerprint( system_prompt=attrs.get("gen_ai.system_prompt", ""), tool_schemas=attrs.get("gen_ai.tool.definitions", []), messages=messages, sampling_params=sampling, model_snapshot=attrs["gen_ai.request.model_snapshot"], ) def admit_to_counterfactual_cohort( span: dict[str, Any], capture_digest: str ) -> RequestFingerprint: """Admit a trace to a counterfactual cohort only if fingerprints match.""" fp = reconstruct_fingerprint(span) if fp.digest() != capture_digest: raise ReplayFidelityViolation( f"span {span.get('span_id')!r} replay fingerprint {fp.digest()[:12]} " f"!= capture fingerprint {capture_digest[:12]}; trace is a fresh " "sample under an unknown distribution, not a counterfactual sample" ) return fp ```