# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-nondeterministic-span-replay-when-sampling-decisions-not-model-outputs-are-the-hidden-state-that-breaks-incident-forensics.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-nondeterministic-span-replay-when-sampling-decisions-not-model-outputs-are-the-hidden-state-that-breaks-incident-forensics.warrant.json
# Markdown SHA-256:   2d370c3728b06456441bb8d372332f14330f0794cdcaf866b709729ec4352a21
# Code AST SHA-256:   38165e72c2f9c3c678ad0ff55b6f46692666c59fca3e32409d6f43ec5d6203c5
# Verified Classes:   ReplayStateIncomplete, ReplayToolDrift, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReplayStateIncomplete(RuntimeError):
    """Raised when a span lacks the decode config or model revision required for forensic replay."""


class ReplayToolDrift(RuntimeError):
    """Raised when a recorded tool payload no longer matches its captured content hash."""


@dataclass
class GenAISpan:
    span_id: str
    prompt: str
    recorded_output: str
    temperature: Optional[float]
    top_p: Optional[float]
    seed: Optional[int]
    model_revision: Optional[str]
    tool_result_hash: Optional[str]
    expected_tool_result_hash: Optional[str]


def replay_for_forensics(span: GenAISpan, execute_fn) -> str:
    # Absence of config is not "use default"; it is unreplayable.
    missing = [
        name
        for name, val in (
            ("temperature", span.temperature),
            ("top_p", span.top_p),
            ("model_revision", span.model_revision),
        )
        if val is None
    ]
    if missing:
        raise ReplayStateIncomplete(
            f"span {span.span_id} missing decode state {missing}; "
            f"refusing to substitute defaults for forensic replay"
        )

    if span.tool_result_hash != span.expected_tool_result_hash:
        raise ReplayToolDrift(
            f"span {span.span_id} tool payload hash mismatch: "
            f"recorded={span.tool_result_hash!r} expected={span.expected_tool_result_hash!r}"
        )

    replayed = execute_fn(
        prompt=span.prompt,
        temperature=span.temperature,
        top_p=span.top_p,
        seed=span.seed,
        model_revision=span.model_revision,
    )

    if replayed != span.recorded_output:
        # Config was complete, so divergence is genuine model-side drift,
        # not a replay artifact. Surface it, do not silently accept it.
        raise ReplayStateIncomplete(
            f"span {span.span_id} diverged under pinned config "
            f"(revision={span.model_revision}); classify as MODEL_DRIFT"
        )
    return replayed
