# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-span-link-severance-when-a-delegated-agent-hop-re-emits-opentelemetry-spans-under-a-fresh-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-span-link-severance-when-a-delegated-agent-hop-re-emits-opentelemetry-spans-under-a-fresh-trace-context.warrant.json
# Markdown SHA-256:   7980c4351cba7625292acc3db96b19fad26ce82b8537d8f34e381cf085ad0af4
# Code AST SHA-256:   fb4b1ce12b77db9fc5eedfb771b23ded334c811a462c098c43bc4d6629236b17
# Verified Classes:   SpanLinkSeveranceError, SpanRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanLinkSeveranceError(RuntimeError):
    """Raised when a delegated agent hop emits a span whose parentage
    crosses trace boundaries, or whose delegation link cannot be
    reconciled from the out-of-band delegation_id."""


@dataclass(frozen=True)
class SpanRecord:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    delegation_id: str | None
    operation_name: str


def reconcile_delegated_hop(
    delegating_span: SpanRecord,
    child_span: SpanRecord,
    expected_delegation_id: str,
) -> None:
    # Case 1: same trace, genuine parentage -- fine.
    if child_span.trace_id == delegating_span.trace_id:
        if child_span.parent_span_id == delegating_span.span_id:
            return
        # Same trace but wrong parent: mis-parented, not severed.
        raise SpanLinkSeveranceError(
            f"child span {child_span.span_id} in trace {child_span.trace_id} "
            f"is parented to {child_span.parent_span_id}, not delegating "
            f"span {delegating_span.span_id}"
        )

    # Case 2: different trace -- parentage across traces is invalid.
    if child_span.parent_span_id == delegating_span.span_id:
        raise SpanLinkSeveranceError(
            f"cross-trace parentage: child span {child_span.span_id} in "
            f"trace {child_span.trace_id} claims parent "
            f"{delegating_span.span_id} in trace {delegating_span.trace_id}; "
            f"this must be a link, not a child"
        )

    # Case 3: different trace, no parentage -- require out-of-band link.
    if child_span.delegation_id != expected_delegation_id:
        raise SpanLinkSeveranceError(
            f"delegated hop {expected_delegation_id} has no reconcilable "
            f"link: child span {child_span.span_id} carries delegation_id="
            f"{child_span.delegation_id!r}; causal edge is severed"
        )
    # Link reconciled via delegation_id; assembly-time linker attaches it.
    return
