# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-retrieved-document-to-the-wrong-causal-span-in-a-rag-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-retrieved-document-to-the-wrong-causal-span-in-a-rag-trace.warrant.json
# Markdown SHA-256:   7efa728bbe9f880e46ee851cf4494e43b5c60586d65301d1bbef83e6b0c94b95
# Code AST SHA-256:   b4916decfdbc7cc9ece4cdf1055cc54ab0cc1f89ceba444d9596b0566ffbda78
# Verified Classes:   CausalLinkError, RetrievalSpan, GenerationSpan, Edge
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalLinkError(RuntimeError):
    """Raised when a retrieval->generation edge cannot be justified by provenance."""


@dataclass
class RetrievalSpan:
    span_id: str
    backend: str
    doc_ids: list[str]
    src_handles: dict[str, str]  # doc_id -> provenance handle injected into prompt


@dataclass
class GenerationSpan:
    span_id: str
    received_handles: set[str]        # handles actually present in the input
    cited_doc_ids: list[str] = field(default_factory=list)


@dataclass
class Edge:
    retrieval_span_id: str
    generation_span_id: str
    doc_id: str
    kind: str          # "verified" | "inferred"
    heuristic: Optional[str] = None


def link(retrieval: RetrievalSpan,
         generation: GenerationSpan,
         allow_inference: bool = False,
         heuristic: Optional[str] = None) -> list[Edge]:
    edges: list[Edge] = []
    for doc_id in generation.cited_doc_ids:
        handle = retrieval.src_handles.get(doc_id)
        if handle is None:
            continue  # this retrieval span did not return the doc; not its edge
        if handle in generation.received_handles:
            edges.append(Edge(retrieval.span_id, generation.span_id, doc_id, "verified"))
        else:
            # Handle existed but was stripped before the generation saw it.
            if not allow_inference:
                raise CausalLinkError(
                    f"provenance_gap: doc {doc_id} has handle {handle} in "
                    f"retrieval {retrieval.span_id} but generation "
                    f"{generation.span_id} did not receive it; refusing to "
                    f"fabricate a causal edge"
                )
            if heuristic is None:
                raise CausalLinkError(
                    f"inferred edge for doc {doc_id} requires an explicit "
                    f"heuristic label; timestamp tie-break alone is not admissible"
                )
            edges.append(Edge(retrieval.span_id, generation.span_id, doc_id,
                              "inferred", heuristic))
    return edges


def link_multi_backend(retrievals: list[RetrievalSpan],
                       generation: GenerationSpan,
                       allow_inference: bool = False,
                       heuristic: Optional[str] = None) -> list[Edge]:
    all_edges: list[Edge] = []
    for r in retrievals:
        all_edges.extend(link(r, generation, allow_inference, heuristic))
    # Invariant: a verified edge must be unique per (doc_id, generation).
    verified = [e for e in all_edges if e.kind == "verified"]
    seen: dict[str, str] = {}
    for e in verified:
        if e.doc_id in seen and seen[e.doc_id] != e.retrieval_span_id:
            raise CausalLinkError(
                f"ambiguous provenance: doc {e.doc_id} verified against both "
                f"{seen[e.doc_id]} and {e.retrieval_span_id}; handle collision"
            )
        seen[e.doc_id] = e.retrieval_span_id
    return all_edges
