# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-broken-parent-child-span-linkage-across-nested-sub-agent-invocations-when-the-semantic-convention-requires-trace-context-p.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-broken-parent-child-span-linkage-across-nested-sub-agent-invocations-when-the-semantic-convention-requires-trace-context-p.warrant.json
# Markdown SHA-256:   e8b82e7731584902fa9722f48f8de1658fa78fac49e4efbdc89c570abac69cd1
# Code AST SHA-256:   d90aeb4532494cd3895d491a5eacd35469d897ab82f2cc9c15c9934b78fad511
# Verified Classes:   SpanLinkageError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

_TRACEPARENT = re.compile(
    r"^(?P<trace_id>[0-9a-f]{32})-(?P<span_id>[0-9a-f]{16})-(?P<flags>[0-9a-f]{2})$"
)


class SpanLinkageError(RuntimeError):
    """Raised when a child span's causal linkage to its declared parent is broken."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_span_id: str | None
    trace_id: str
    start_s: float
    end_s: float
    operation: str
    traceparent: str | None = None


def validate_linkage(child: Span, parent: Span, *, delegating: bool) -> None:
    # 1. Causal linkage is mandatory on every path. This is the invariant
    #    that survives async dispatch and interval overrun.
    if child.trace_id != parent.trace_id:
        raise SpanLinkageError(
            f"trace-id mismatch: child {child.span_id} trace={child.trace_id} "
            f"declares parent {parent.span_id} trace={parent.trace_id}"
        )
    if child.parent_span_id != parent.span_id:
        raise SpanLinkageError(
            f"parent edge broken: child {child.span_id} "
            f"parent_span_id={child.parent_span_id} != {parent.span_id}"
        )
    if child.traceparent is not None:
        m = _TRACEPARENT.match(child.traceparent)
        if not m:
            raise SpanLinkageError(f"malformed traceparent on {child.span_id}: {child.traceparent!r}")
        if m.group("trace_id") != parent.trace_id:
            raise SpanLinkageError(
                f"traceparent trace-id {m.group('trace_id')} != parent trace {parent.trace_id}"
            )

    # 2. Interval containment is enforced ONLY on blocking paths.
    #    On delegating paths an interval overrun is expected, not an error.
    if not delegating:
        if child.start_s < parent.start_s or child.end_s > parent.end_s:
            raise SpanLinkageError(
                f"nesting violated on blocking path: child [{child.start_s},{child.end_s}] "
                f"not within parent [{parent.start_s},{parent.end_s}]"
            )


def effective_inclusive_duration(parent: Span, children: list[Span]) -> float:
    # Inclusive duration must account for children that outlive the parent
    # span on delegating paths; otherwise orchestrator latency understates work.
    if not children:
        return parent.end_s - parent.start_s
    tail = max(c.end_s for c in children)
    return max(parent.end_s, tail) - parent.start_s
