# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-when-replayed-from-an-otel-genai-trace-that-recorded-tool-arguments-post-serialization.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-when-replayed-from-an-otel-genai-trace-that-recorded-tool-arguments-post-serialization.warrant.json
# Markdown SHA-256:   3dfea590513ecbe4172c9181b45cb0c388c947b8a723bfa787320315ded2a790
# Code AST SHA-256:   e9792e5439166ac2a6e9093bb342b2297c1c396436cc07731a0b93d0e82d05f7
# Verified Classes:   ReplayNotAdmissibleError, SpanRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class ReplayNotAdmissibleError(RuntimeError):
    """Raised when a trace span cannot support model-faithful replay."""


@dataclass(frozen=True)
class SpanRecord:
    span_id: str
    tool_name: str
    arguments: dict[str, Any]          # post-serialization, canonicalized by exporter
    arguments_raw: str | None          # byte-exact model output, pre-canonicalization
    result_sha256: str | None          # hash of untruncated result
    result_truncated: bool


def admit_span_for_model_faithful_replay(span: SpanRecord) -> None:
    if span.arguments_raw is None:
        raise ReplayNotAdmissibleError(
            f"span {span.span_id} ({span.tool_name}): missing gen_ai.tool.call.arguments.raw; "
            "recorded arguments are a post-serialization projection and cannot be inverted "
            "into the model's emitted arguments. Refusing model-faithful replay."
        )
    if span.result_sha256 is None:
        raise ReplayNotAdmissibleError(
            f"span {span.span_id} ({span.tool_name}): missing gen_ai.tool.call.result.sha256; "
            "cannot verify sandboxed tool reproduced the original result."
        )
    if span.result_truncated:
        raise ReplayNotAdmissibleError(
            f"span {span.span_id} ({span.tool_name}): result was truncated at export; "
            "downstream model calls consumed a prefix the original model never saw. "
            "Halt replay chain at this span."
        )
    # Sanity: raw must hash-consistently round-trip through the exporter's canonicalizer.
    try:
        reparsed = json.loads(span.arguments_raw)
    except json.JSONDecodeError as e:
        raise ReplayNotAdmissibleError(
            f"span {span.span_id}: arguments.raw is not valid JSON ({e}); "
            "exporter corrupted the raw payload."
        ) from e
    if reparsed != span.arguments:
        # Not fatal on its own, but the divergence must be logged: it means the
        # exporter applied a lossy canonicalization and any trace-faithful
        # fallback for this span is testing a different program.
        raise ReplayNotAdmissibleError(
            f"span {span.span_id}: arguments.raw does not round-trip to recorded arguments; "
            f"exporter canonicalization is lossy. raw={span.arguments_raw!r} "
            f"recorded={span.arguments!r}"
        )


def verify_replayed_result(span: SpanRecord, sandbox_result: bytes) -> None:
    if span.result_sha256 is None:
        raise ReplayNotAdmissibleError(
            f"span {span.span_id}: no result hash to verify against."
        )
    actual = hashlib.sha256(sandbox_result).hexdigest()
    if actual != span.result_sha256:
        raise ReplayNotAdmissibleError(
            f"span {span.span_id} ({span.tool_name}): sandboxed tool produced a different "
            f"result than the original run (expected {span.result_sha256[:12]}…, "
            f"got {actual[:12]}…). Replay diverged at the tool layer, not the model layer — "
            "investigate tool determinism before blaming the model."
        )
