# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-span-across-a-delegate-hop-and-what-breaks-if-it-does.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-span-across-a-delegate-hop-and-what-breaks-if-it-does.warrant.json
# Markdown SHA-256:   d176476feebaace76c7355ecedc4a244b138ab2933bc2fd97747dc885bf5fcd9
# Code AST SHA-256:   bc27822bc8fa23389e8d21d9da9d864ff8450d88d164ba401f8b84c24a3dc216
# Verified Classes:   SpanRef, CausalityViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    start_ns: int
    end_ns: int | None  # None == still open
    kind: str  # "CLIENT" | "SERVER" | "INTERNAL"


class CausalityViolation(RuntimeError):
    """Raised when a span is about to be parented to a span that closed before it began."""


def emit_child_span(child: SpanRef, parent: SpanRef | None) -> None:
    """Guardrail invoked before a child span is exported to the collector.

    Enforces: a closed parent span may be *linked* to, never *parented* to.
    """
    if parent is None:
        return  # root span, nothing to check

    if child.trace_id != parent.trace_id:
        raise CausalityViolation(
            f"child span {child.span_id} trace {child.trace_id} != "
            f"parent span {parent.span_id} trace {parent.trace_id}"
        )

    if child.parent_span_id != parent.span_id:
        raise CausalityViolation(
            f"child {child.span_id} declares parent {child.parent_span_id}, "
            f"but guardrail was given {parent.span_id}"
        )

    # The boundary condition: parent must still be open, or child must start
    # no earlier than the parent's end. A closed parent with a later-starting
    # child is the premature-closure / context-re-entry failure.
    if parent.end_ns is not None and child.start_ns < parent.end_ns:
        raise CausalityViolation(
            f"span {child.span_id} (start={child.start_ns}) would be parented to "
            f"closed span {parent.span_id} (end={parent.end_ns}); "
            f"this is the delegate-hop re-entry failure. Emit a Link instead, "
            f"or keep the delegate span open across the await."
        )


def close_delegate_span(delegate: SpanRef, now_ns: int) -> SpanRef:
    """Close a delegate span only after the child's root span is known closed."""
    if delegate.end_ns is not None:
        raise CausalityViolation(
            f"delegate span {delegate.span_id} already closed at {delegate.end_ns}"
        )
    if now_ns < delegate.start_ns:
        raise CausalityViolation(
            f"delegate span {delegate.span_id} close time {now_ns} precedes start "
            f"{delegate.start_ns}"
        )
    return SpanRef(
        trace_id=delegate.trace_id,
        span_id=delegate.span_id,
        parent_span_id=delegate.parent_span_id,
        start_ns=delegate.start_ns,
        end_ns=now_ns,
        kind=delegate.kind,
    )
