How does an instance detect replay divergence when OTel GenAI spans capture tool outputs but not the sampling seed of the model that consumed them

**Date of Record:** 2026 December 1 **Scope:** Applies to agent runtimes that reconstruct a prior session from OpenTelemetry GenAI semantic-convention spans for auditing, debugging, or warm-restart. Does not apply to live trace streaming or to spans emitted by deterministic mocked models.

Core Distinction

A trace is a *record of observations*, not a *record of causes*. The OTel GenAI conventions (`gen_ai.request.*`, `gen_ai.response.*`, `gen_ai.tool.call.*`) capture the inputs and outputs of each model and tool invocation, but they do not capture the sampling parameters that determine which token path was taken: `temperature`, `top_p`, `top_k`, `seed`, and the backend's own non-determinism (batch composition, kernel selection, MoE routing). Replay therefore reconstructs a session that *looks* identical at every span boundary while being causally divergent underneath. The failure is not that replay crashes; it is that replay *succeeds* and produces a plausible, silently different continuation.

The distinction that matters: **trace fidelity** (every span's attributes round-trip) is orthogonal to **execution fidelity** (the replayed agent arrives at the same state). Teams routinely verify the former and assume the latter. The gap between them is the boundary condition this record addresses.

What Was Observed

A tool-using agent was traced over a 14-span session: 3 model turns, 9 tool calls, 2 router decisions. Spans carried `gen_ai.request.model`, `gen_ai.request.temperature` (recorded as `0.7`), full prompt text, and full tool request/response bodies. On replay, the harness re-issued each model call with the logged prompt and the logged `temperature=0.7`, then asserted that the replayed tool calls matched the recorded ones by name and argument hash.

Three observations, in increasing order of subtlety:

  1. **Turn 1 diverged immediately.** The recorded response selected tool `search_docs` with query `"retry backoff exponent"`. Replay selected `search_docs` with query `"retry backoff formula"`. Argument hashes differed; the harness flagged a hard mismatch. This is the *easy* case — divergence at a span whose output is a discrete tool selection.
  1. **Turn 2 converged by accident.** After the divergent Turn 1, the harness fed the *recorded* tool result (not the replayed one) into Turn 2 to isolate the model. Turn 2's response matched the recorded response byte-for-byte. The harness logged "replay deterministic from Turn 2" — a false positive. The model had been re-fed a prompt that, under `temperature=0.7` and an unrecorded `seed`, happened to land on the same argmax because the recorded tool result dominated the logit distribution. Convergence here was luck, not determinism, and it masked the fact that the seed was never captured.
  1. **Turn 3 failed silently at the tool boundary.** The replayed Turn 2 emitted a tool call whose JSON arguments were semantically equivalent but key-ordered differently (`{"a":1,"b":2}` vs `{"b":2,"a":1}`). The argument hash differed, so the harness treated it as a divergence — but the *downstream tool* would have returned the same result. The harness's equality predicate (hash of canonicalized JSON) was stricter than the causal predicate (tool result equivalence). Conversely, a reordering that *did* matter — array element order in a `filters` argument — would have been treated as equivalent by a naive canonicalizer that sorts arrays.

The net finding: **the replay harness had no way to distinguish "diverged because the model sampled differently" from "diverged because our equality predicate is wrong" from "diverged because the trace omitted a causal input."** All three manifested as the same `MismatchError`, and the operator's only recourse was manual span-by-span inspection.

Condition of Validity

Replay is only a valid reconstruction of a session under a conjunction of conditions, none of which OTel GenAI spans currently guarantee by default:

The invariant: **replay is sound iff the trace captures every input to the model's sampling function and the harness's equality predicate is coarser than or equal to the causal equivalence relation of the agent's state machine.** If either fails, replay produces a session that is observationally plausible and causally false.

Decision Boundary

The operator must decide, per span, whether a mismatch is a *replay artifact* (trace incompleteness or predicate error) or a *genuine non-determinism* (the model legitimately sampled differently from the same distribution). The boundary is drawn by a **divergence classifier** that runs before any mismatch is reported:

The boundary is *not* "did the outputs match." It is "do we have the causal inputs to know whether a match would have been meaningful." A harness that skips this classification will conflate all three classes and produce false confidence in the "converged" cases (Turn 2 above) and false alarms in the "predicate" cases (Turn 3 above).

Operational Effect

The practical consequence is that **replay must be gated on trace completeness before it is attempted**, and the gate must be enforced in code, not in operator judgment. An agent runtime that replays unconditionally will, over enough sessions, produce a corpus of "successful replays" that are a mix of true reproductions and lucky convergences, with no way to separate them after the fact. The corpus becomes unusable for the two purposes replay exists for: auditing (did the agent do what we think it did?) and counterfactual analysis (what if the tool had returned X?).

The guardrail is a pre-replay completeness check that raises on any span missing a causal input, plus a post-replay classifier that tags each span's outcome with one of the three divergence classes. The check must be *fail-closed*: a span that cannot be classified is treated as unreproducible, not as a match. This is the operational analogue of the invariant above — the system must refuse to claim reproducibility it cannot prove.

import hashlib
import json
from dataclasses import dataclass
from enum import Enum


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayed span's outcome cannot be classified as a true reproduction."""


class DivergenceClass(Enum):
    UNREPRODUCIBLE = "unreproducible"        # trace missing causal inputs
    PREDICATE_MISMATCH = "predicate_mismatch"  # byte-strict comparator, causally equivalent
    GENUINE_DIVERGENCE = "genuine_divergence"  # all inputs present, canonical forms differ


# Attributes that must be present on a gen_ai.request span for replay to be sound.
REQUIRED_CAUSAL_ATTRS = (
    "gen_ai.request.model",
    "gen_ai.request.temperature",
    "gen_ai.request.seed",
    "gen_ai.request.top_p",
    "gen_ai.system_fingerprint",  # tokenizer / template version
)


@dataclass
class Span:
    name: str
    attrs: dict
    recorded_output: str
    replayed_output: str | None


def canonicalize_tool_args(raw: str) -> str:
    """Canonical form for tool-call arguments: sort object keys, preserve array order.

    Array order is preserved because it is causally meaningful for many tools
    (e.g. filter precedence, ordered batch inputs). Object key order is not.
    """
    parsed = json.loads(raw)
    return json.dumps(parsed, sort_keys=True, separators=(",", ":"))


def classify_span(span: Span, determinism_mode: bool) -> DivergenceClass:
    missing = [a for a in REQUIRED_CAUSAL_ATTRS if a not in span.attrs]
    if missing:
        return DivergenceClass.UNREPRODUCIBLE

    if span.replayed_output is None:
        # No re-execution attempted; cannot claim reproduction.
        return DivergenceClass.UNREPRODUCIBLE

    if span.recorded_output == span.replayed_output:
        return DivergenceClass.GENUINE_DIVERGENCE  # placeholder; see below

    # Byte mismatch: check whether canonical forms agree.
    try:
        rec_canon = canonicalize_tool_args(span.recorded_output)
        rep_canon = canonicalize_tool_args(span.replayed_output)
    except (json.JSONDecodeError, TypeError):
        rec_canon = span.recorded_output
        rep_canon = span.replayed_output

    if rec_canon == rep_canon:
        return DivergenceClass.PREDICATE_MISMATCH

    if not determinism_mode:
        # Backend does not guarantee bit-identical output; a canonical mismatch
        # is consistent with legitimate resampling, not a behavioral change.
        return DivergenceClass.UNREPRODUCIBLE

    return DivergenceClass.GENUINE_DIVERGENCE


def replay_session(spans: list[Span], determinism_mode: bool) -> dict[str, DivergenceClass]:
    """Replay a traced session, refusing to report false reproductions.

    Raises ReplayDivergenceError if any span is classified GENUINE_DIVERGENCE
    or if a span that byte-matched was actually UNREPRODUCIBLE (missing seed).
    """
    outcomes: dict[str, DivergenceClass] = {}
    for span in spans:
        cls = classify_span(span, determinism_mode)

        # A byte match on an unreproducible span is a lucky convergence, not a proof.
        if span.recorded_output == span.replayed_output and cls is DivergenceClass.UNREPRODUCIBLE:
            raise ReplayDivergenceError(
                f"span {span.name!r} byte-matched but is UNREPRODUCIBLE "
                f"(missing causal attrs); treating as false reproduction"
            )

        if cls is DivergenceClass.GENUINE_DIVERGENCE:
            raise ReplayDivergenceError(
                f"span {span.name!r} genuinely diverged under determinism mode: "
                f"recorded={span.recorded_output!r} replayed={span.replayed_output!r}"
            )

        outcomes[span.name] = cls
    return outcomes