# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-a-semantically-valid-span-that-no-downstream-consumer-can-reconstruct-into-a-trace-tree.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-a-semantically-valid-span-that-no-downstream-consumer-can-reconstruct-into-a-trace-tree.warrant.json
# Markdown SHA-256:   6560190b8c6ef1457fc2c6ad8e4b13d734628fd757b7dae43a7c9c141560ba99
# Code AST SHA-256:   edb1ac43e6b95b4672a698d62761730d1112db970e792c8806d55dfb046bdf43
# Verified Classes:   TraceClosureViolation, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class TraceClosureViolation(RuntimeError):
    """Raised when an exported span set is not closed under the parent relation."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    # Per-span semantic-convention attributes are assumed already validated.


def assert_trace_closure(spans: Iterable[Span]) -> None:
    """
    Enforce the invariant that makes per-span conformance a valid proxy
    for trace integrity:

        exported is closed under parent_span_id, and each trace_id has
        exactly one root (parent_span_id is None).

    A span can be individually schema-valid and still fail here; that is
    the whole point. Do not weaken this to a per-span check.
    """
    by_trace: dict[str, list[Span]] = {}
    for s in spans:
        by_trace.setdefault(s.trace_id, []).append(s)

    for trace_id, group in by_trace.items():
        ids = {s.span_id for s in group}
        roots = [s for s in group if s.parent_span_id is None]

        if len(roots) != 1:
            raise TraceClosureViolation(
                f"trace {trace_id}: expected exactly 1 root, found {len(roots)} "
                f"(root span_ids={[r.span_id for r in roots]}). "
                "Multiple roots indicate dangling-parent fragmentation."
            )

        orphans = [
            s for s in group
            if s.parent_span_id is not None and s.parent_span_id not in ids
        ]
        if orphans:
            detail = ", ".join(
                f"{s.span_id}->{s.parent_span_id}" for s in orphans
            )
            raise TraceClosureViolation(
                f"trace {trace_id}: {len(orphans)} span(s) reference a parent "
                f"not present in the exported set: {detail}. "
                "Per-span conformance may still be 100%; the trace is not "
                "reconstructable. Check sampler drops, exporter backpressure, "
                "and async contextvar capture order."
            )


def run_conformance_gate(spans: list[Span]) -> None:
    # Phase 1 (per-span attribute/type checks) is assumed to have passed.
    # Phase 2 is the gate that actually protects downstream queries.
    try:
        assert_trace_closure(spans)
    except TraceClosureViolation as exc:
        # Hard fail: never let the collector's "orphan -> synthesize root"
        # repair path turn a violation into a green run.
        raise TraceClosureViolation(
            f"topological conformance failed: {exc}"
        ) from exc
