# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-parent-child-span-correlation-across-llm-calls-retrievals-and-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-parent-child-span-correlation-across-llm-calls-retrievals-and-agent-handoffs.warrant.json
# Markdown SHA-256:   f8db7ca6136968f6c36891dc548b96ecb4c6c9b98b861bac16846a043ea29486
# Code AST SHA-256:   80e47c2477fd5cb333a5faaf18d51edd6577e19660d971b1b46165ed0a991bf8
# Verified Classes:   SpanCorrelationError, Span, Trace
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpanCorrelationError(RuntimeError):
    """Raised when a trace's parent-child invariant is violated."""
    pass


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    name: str
    start_ns: int
    end_ns: int


@dataclass
class Trace:
    trace_id: str
    spans: list[Span] = field(default_factory=list)


def validate_trace_invariant(trace: Trace) -> None:
    """
    Enforce: every non-root span has a parent present in the same trace,
    and parent.start_ns < child.end_ns. A trace with >1 root is a
    propagation defect, not a display artifact.
    """
    if not trace.spans:
        raise SpanCorrelationError(f"trace {trace.trace_id} has no spans")

    by_id = {s.span_id: s for s in trace.spans}
    roots = [s for s in trace.spans if s.parent_span_id is None]

    if len(roots) > 1:
        root_names = ", ".join(sorted(r.name for r in roots))
        raise SpanCorrelationError(
            f"trace {trace.trace_id} has {len(roots)} roots ({root_names}); "
            f"span context was lost at a heterogeneous boundary "
            f"(process hop / thread-pool hop / retry reuse). "
            f"Do not heuristic-stitch; locate the missing carrier."
        )

    for span in trace.spans:
        if span.parent_span_id is None:
            continue
        parent = by_id.get(span.parent_span_id)
        if parent is None:
            raise SpanCorrelationError(
                f"span {span.span_id} ({span.name}) references parent "
                f"{span.parent_span_id} absent from trace {trace.trace_id}; "
                f"collector dropped the parent or carrier was never populated."
            )
        if parent.start_ns >= span.end_ns:
            raise SpanCorrelationError(
                f"span {span.span_id} ({span.name}) ends at {span.end_ns} "
                f"before parent {parent.span_id} starts at {parent.start_ns}; "
                f"clock domain mismatch across the boundary."
            )


def assemble_and_quarantine(trace: Trace) -> Trace:
    """Validate before any metric derives from the trace."""
    try:
        validate_trace_invariant(trace)
    except SpanCorrelationError:
        # Quarantine: do not emit cost/latency metrics for this trace.
        trace.spans = [s for s in trace.spans if s.parent_span_id is None]
        raise
    return trace
