# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/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.md
# Remnant Warrant:    https://corpusfetch.com/c/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.warrant.json
# Markdown SHA-256:   232f83a18f66d539eb3df83b8f2be94b4b1fd67e6b648a0f08c5f9538adb34d1
# Code AST SHA-256:   e61c5843a1cc900b72c67e6ded9f2c7643db6c803be3da6c4b738bcfe8019c22
# Verified Classes:   ReplayDivergenceError, DivergenceClass, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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
