# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-level-hallucination-attribution-from-collapsing-under-genai-semantic-convention-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-level-hallucination-attribution-from-collapsing-under-genai-semantic-convention-drift.warrant.json
# Markdown SHA-256:   48e68da9f79e41066bd45d69fa857a487af80a49e93c324442d764404d61f765
# Code AST SHA-256:   44f4b7f80f4b9461c25ce1285cd7ca2fa4358b729ada82278cb771840d68a5d1
# Verified Classes:   TraceAttributionRefused, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class TraceAttributionRefused(RuntimeError):
    """Raised when a trace cannot be soundly attributed due to cross-span invariant violation."""


@dataclass(frozen=True)
class Span:
    span_id: str
    trace_id: str
    ordering_key: int          # monotonic, collision-free required
    convention_rev: str        # e.g. "A" or "B"
    is_retry: bool
    retry_of: str | None
    completion_text: str
    finish_reasons: tuple[str, ...]


def assert_attribution_invariants(spans: Sequence[Span]) -> None:
    if not spans:
        raise TraceAttributionRefused("empty trace: nothing to attribute")

    trace_ids = {s.trace_id for s in spans}
    if len(trace_ids) != 1:
        raise TraceAttributionRefused(f"multi-trace batch: {trace_ids}")

    # Ordering invariant: collision-free ordering key across the whole trace.
    keys = [s.ordering_key for s in spans]
    if len(keys) != len(set(keys)):
        dupes = sorted({k for k in keys if keys.count(k) > 1})
        raise TraceAttributionRefused(
            f"ordering collision on keys {dupes}; refusing (tie-break is non-deterministic)"
        )

    # Topology invariant: retries must be explicitly linked, not inferred by timestamp.
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.is_retry and (s.retry_of is None or s.retry_of not in by_id):
            raise TraceAttributionRefused(
                f"retry span {s.span_id} lacks resolvable retry_of={s.retry_of!r}"
            )

    # Convention-revision skew invariant: refuse mixed-revision traces that
    # change retry/usage semantics rather than silently reinterpreting.
    revs = {s.convention_rev for s in spans}
    if len(revs) > 1:
        raise TraceAttributionRefused(
            f"mixed convention revisions {sorted(revs)} in one trace; "
            "pin to lowest revision or reject"
        )


def attribute_hallucination(spans: Sequence[Span], claim: str) -> tuple[str, str]:
    """Return (blamed_span_id, rationale). Raises if the graph is unsound."""
    assert_attribution_invariants(spans)

    # Provenance invariant: match only surviving (non-superseded) causal ancestors.
    superseded = {s.retry_of for s in spans if s.is_retry and s.retry_of}
    survivors = [s for s in spans if s.span_id not in superseded]

    matches = [s for s in survivors if claim in s.completion_text]
    if not matches:
        raise TraceAttributionRefused(
            f"claim {claim!r} not found in surviving spans; cannot attribute"
        )

    # Deterministic: earliest surviving match by ordering key.
    source = min(matches, key=lambda s: s.ordering_key)
    digest = hashlib.sha256(claim.encode()).hexdigest()[:12]
    return source.span_id, f"claim#{digest} matched surviving span {source.span_id}"
