# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-causal-span-links-from-parent-child-delegation-in-genai-multi-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-causal-span-links-from-parent-child-delegation-in-genai-multi-agent-traces.warrant.json
# Markdown SHA-256:   a368815b834259c2d6334baf807e85daefe047790384a1d667bed0916be97dd8
# Code AST SHA-256:   f9b1d3e844372ae3bab51037958b4b38673e63ed1d5e4c3edd2321babad4222d
# Verified Classes:   CausalEdgeInvariantError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class CausalEdgeInvariantError(RuntimeError):
    """Raised when a parent-child edge violates containment semantics."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    start_ns: int
    end_ns: int
    links: tuple[str, ...] = ()


def validate_parent_child(child: Span, parent: Span) -> None:
    """Enforce child.end <= parent.end and child.start >= parent.start.

    Any violation means the relationship is a reference, not containment,
    and must be recorded as a span link instead of a parent-child edge.
    """
    if child.parent_id != parent.span_id:
        raise CausalEdgeInvariantError(
            f"span {child.span_id} does not declare {parent.span_id} as parent"
        )
    if child.start_ns < parent.start_ns:
        raise CausalEdgeInvariantError(
            f"child {child.span_id} starts before parent {parent.span_id}; "
            "use a span link, not a parent edge"
        )
    if child.end_ns > parent.end_ns:
        raise CausalEdgeInvariantError(
            f"child {child.span_id} outlives parent {parent.span_id} "
            f"({child.end_ns - parent.end_ns} ns past parent end); "
            "detach context and record a span link"
        )


def reclassify_as_link(child: Span, parent: Span) -> Span:
    """Detach a mis-nested child and attach the former parent as a link."""
    try:
        validate_parent_child(child, parent)
    except CausalEdgeInvariantError:
        return Span(
            span_id=child.span_id,
            parent_id=None,
            start_ns=child.start_ns,
            end_ns=child.end_ns,
            links=child.links + (parent.span_id,),
        )
    return child
