# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-valid-genai-semantic-convention-spans-that-nonetheless-cannot-be-causally-linked-into-a-replayable-incident-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-valid-genai-semantic-convention-spans-that-nonetheless-cannot-be-causally-linked-into-a-replayable-incident-chain.warrant.json
# Markdown SHA-256:   3dc1d801cf06eeb65bfeae37c83b7ddc6bef1a428975eca98bc9b3e69334faa0
# Code AST SHA-256:   e30a128f04300235a5b029607aef5e77277deb6c4da0c6749161be82fd6ad0ed
# Verified Classes:   DanglingParentError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable, Optional

class DanglingParentError(RuntimeError):
    """Raised when a span's parent_span_id does not resolve within the exported span set
    and no explicit out-of-band link record bridges the edge."""
    pass

@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation: str
    link_parent_trace_id: Optional[str] = None
    link_parent_span_id: Optional[str] = None
    link_edge_kind: Optional[str] = None  # delegation | resume | tool_return

def assert_closed_forest(spans: Iterable[Span]) -> None:
    """Enforce the closure invariant required for causal replay.

    Every non-null parent_span_id MUST resolve to an exported span, OR the span
    MUST carry an explicit link record bridging the cross-trace edge.
    Otherwise the replay would soft-re-root and misattribute root cause.
    """
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.parent_span_id is None:
            continue
        if s.parent_span_id in by_id:
            continue
        bridged = (
            s.link_parent_span_id == s.parent_span_id
            and s.link_parent_trace_id is not None
            and s.link_edge_kind in {"delegation", "resume", "tool_return"}
        )
        if not bridged:
            raise DanglingParentError(
                f"span {s.span_id} (trace {s.trace_id}, op={s.operation}) "
                f"references parent {s.parent_span_id} absent from exported set "
                f"and carries no explicit link record; causal replay would "
                f"soft-re-root and misattribute root cause"
            )

def replay_chain(spans: Iterable[Span]) -> list[Span]:
    spans = list(spans)
    assert_closed_forest(spans)  # hard-fail before any causal claim
    # ... topological walk over the now-closed forest ...
    return spans
