# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-replay-divergent-hallucination-attribution-from-silently-re-scoring-a-trajectory-against-a-mutated-tool-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-replay-divergent-hallucination-attribution-from-silently-re-scoring-a-trajectory-against-a-mutated-tool-schema.warrant.json
# Markdown SHA-256:   24266ad9f505fc6599284fe0bd840708d58a4591535b9941738cac43622fdad4
# Code AST SHA-256:   300a41c9ca4e579d0c008bad92886c5332263af365a9adfeefef9fed04dedd2c
# Verified Classes:   ProvenanceDivergenceError, SpanProvenance
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ProvenanceDivergenceError(RuntimeError):
    """Raised when a replay span is not provenance-equivalent to its recorded counterpart."""


@dataclass(frozen=True)
class SpanProvenance:
    tool_schema_hash: str
    model_weights_hash: str
    retrieval_index_id: str
    sampling_seed: int
    sampling_temperature: float
    upstream_context_digest: str


def _digest(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def verify_replay_equivalence(
    recorded: SpanProvenance,
    replayed: SpanProvenance,
    upstream_output_bytes: bytes,
    recorded_upstream_digest: str,
) -> None:
    """Enforce provenance-equivalence before attributing a hallucination label.

    Raises ProvenanceDivergenceError on any mismatch. The caller MUST treat
    the span as UNATTRIBUTABLE, never fall back to the recorded label and
    never adopt the replayed label.
    """
    # Byte-level upstream check: a single whitespace change in a tool
    # description can flip the model's decision.
    if _digest(upstream_output_bytes) != recorded_upstream_digest:
        raise ProvenanceDivergenceError(
            "upstream context bytes diverged from recorded digest; "
            "descendant spans are UNATTRIBUTABLE"
        )

    if recorded.tool_schema_hash != replayed.tool_schema_hash:
        raise ProvenanceDivergenceError(
            f"tool schema drift: recorded={recorded.tool_schema_hash} "
            f"replayed={replayed.tool_schema_hash}"
        )

    if recorded.model_weights_hash != replayed.model_weights_hash:
        raise ProvenanceDivergenceError(
            f"model weights drift: recorded={recorded.model_weights_hash} "
            f"replayed={replayed.model_weights_hash}"
        )

    if recorded.retrieval_index_id != replayed.retrieval_index_id:
        raise ProvenanceDivergenceError(
            f"retrieval index drift: recorded={recorded.retrieval_index_id} "
            f"replayed={replayed.retrieval_index_id}"
        )

    if recorded.sampling_seed != replayed.sampling_seed:
        raise ProvenanceDivergenceError("sampling seed mismatch")

    # Any nonzero temperature makes the replay non-deterministic; the verdict
    # describes a different execution and cannot label the original span.
    if recorded.sampling_temperature != 0.0 or replayed.sampling_temperature != 0.0:
        raise ProvenanceDivergenceError(
            "nonzero temperature: replay is non-deterministic, "
            "attribution would be approximate"
        )


def attribute_hallucination(
    span_id: str,
    recorded: SpanProvenance,
    replayed: SpanProvenance,
    upstream_output_bytes: bytes,
    recorded_upstream_digest: str,
    replayed_verdict: Optional[bool],
) -> str:
    """Return a terminal attribution state for a span.

    States: 'HALLUCINATED', 'CLEAN', 'UNATTRIBUTABLE'.
    """
    try:
        verify_replay_equivalence(
            recorded, replayed, upstream_output_bytes, recorded_upstream_digest
        )
    except ProvenanceDivergenceError:
        # Fail closed: refuse to attribute rather than attribute approximately.
        return "UNATTRIBUTABLE"

    if replayed_verdict is None:
        return "UNATTRIBUTABLE"
    return "HALLUCINATED" if replayed_verdict else "CLEAN"
