# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-hallucination-attribution-when-a-trace-linked-eval-scorer-re-scores-a-span-whose-parent-context-was-compacted-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-hallucination-attribution-when-a-trace-linked-eval-scorer-re-scores-a-span-whose-parent-context-was-compacted-mid-run.warrant.json
# Markdown SHA-256:   51b588d4c0cdbea7d2d2dde0cf34746cc690de23706d319ec0160e56f7fc6be8
# Code AST SHA-256:   69555878970605f0fa03e766110155194a235be83d22e8dfdd0b7afa7d2c36c5
# Verified Classes:   AttributionEvidenceError, Span, Claim
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable, Optional


class AttributionEvidenceError(RuntimeError):
    """Raised when a scorer's evidence set is not provably closed over the recorded trace."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: Optional[str]
    input_tokens: str
    supersedes: tuple[str, ...] = ()


@dataclass(frozen=True)
class Claim:
    text: str
    cited_span_ids: tuple[str, ...]


def attribute_claim(
    claim: Claim,
    scored_span: Span,
    trace: dict[str, Span],
    replayed_evidence: Iterable[str] = (),
) -> str:
    """Return 'supported' | 'hallucinated' | 'indeterminate'.

    Valid attribution requires every cited span to be either:
      - the scored span itself, or
      - reachable via recorded supersedes edges from the scored span.
    Replayed (re-derived) evidence is never attributable.
    """
    admissible: set[str] = {scored_span.span_id}
    frontier = list(scored_span.supersedes)
    while frontier:
        sid = frontier.pop()
        if sid in admissible:
            continue
        span = trace.get(sid)
        if span is None:
            # Cited evidence was compacted away with no supersedes edge recorded.
            raise AttributionEvidenceError(
                f"cited span {sid!r} absent from trace and not superseded by "
                f"{scored_span.span_id!r}; attribution would be counterfactual"
            )
        admissible.add(sid)
        frontier.extend(span.supersedes)

    for cited in claim.cited_span_ids:
        if cited not in admissible:
            raise AttributionEvidenceError(
                f"claim cites span {cited!r} outside admissible evidence set "
                f"{sorted(admissible)}; scorer is walking replayed context, not "
                f"recorded context"
            )

    if any(replayed_evidence):
        # Re-fetched evidence cannot ground a claim about what the model saw.
        return "indeterminate"

    haystack = " ".join(trace[s].input_tokens for s in admissible)
    if claim.text.strip().lower() in haystack.lower():
        return "supported"
    return "hallucinated"
