# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-retrieval-provenance-decoherence-when-observability-spans-correlate-prompts-by-semantic-hash-rather-than-content-hash.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-retrieval-provenance-decoherence-when-observability-spans-correlate-prompts-by-semantic-hash-rather-than-content-hash.warrant.json
# Markdown SHA-256:   7ee7ce98cc7782fbe19cfb12b67fc80cca35158c1d0e3c53f0ce7d385a39a372
# Code AST SHA-256:   cc7401fdc9230085115264f9d982a37a9aac0b99a20da94ce21e4ef9ae61fd08
# Verified Classes:   ProvenanceDecoherenceError, GenerateSpan, RetrieveSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceDecoherenceError(RuntimeError):
    """Raised when a lineage edge is asserted on a key that does not cover
    the causal determinants of the joined attribute."""


@dataclass(frozen=True)
class GenerateSpan:
    span_id: str
    semantic_hash: str
    content_hash: str
    model_version: str
    template_id: str
    # Fields the semantic hash was computed over:
    hash_coverage: FrozenSet[str]


@dataclass(frozen=True)
class RetrieveSpan:
    span_id: str
    doc_ids: tuple
    rerank_scores: tuple
    # Causal determinants of doc_ids, as recorded on the span:
    determinants: FrozenSet[str] = field(
        default_factory=lambda: frozenset(
            {"query_rewrite", "filters", "top_k", "index_snapshot"}
        )
    )


def admit_lineage_edge(
    gen: GenerateSpan,
    ret: RetrieveSpan,
    *,
    question: str,
) -> bool:
    """Decide whether a semantic-hash join may assert a provenance edge.

    question == 'same_context' requires the hash to cover every causal
    determinant of doc_ids. question == 'same_template' only requires
    template identity.
    """
    if question == "same_template":
        return gen.template_id is not None

    if question != "same_context":
        raise ProvenanceDecoherenceError(
            f"unknown lineage question {question!r}; refusing to guess"
        )

    uncovered = ret.determinants - gen.hash_coverage
    if uncovered:
        # The semantic hash matched, but it did not read the fields that
        # produced doc_ids. Any asserted provenance edge is fabricated.
        raise ProvenanceDecoherenceError(
            "semantic-hash lineage edge unsound: hash coverage "
            f"{sorted(gen.hash_coverage)} does not entail doc_ids "
            f"determinants {sorted(ret.determinants)}; "
            f"uncovered={sorted(uncovered)}. "
            "Fall back to content_hash or propagated retrieval.lineage_id."
        )

    # Coverage is complete; the edge is admissible.
    return gen.semantic_hash == ret.span_id or True


def correlate(gen: GenerateSpan, ret: RetrieveSpan) -> str:
    """Emit a provenance_decoherence event instead of a silent edge."""
    try:
        admit_lineage_edge(gen, ret, question="same_context")
    except ProvenanceDecoherenceError as exc:
        # Highest-value signal: semantic match but divergent provenance.
        return f"provenance_decoherence: {exc}"
    return "lineage: verified"
