# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-child-span-when-the-parent-semantic-convention-span-has-been-orphaned-by-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-child-span-when-the-parent-semantic-convention-span-has-been-orphaned-by-context-compaction.warrant.json
# Markdown SHA-256:   ec01fdf3ee80cc630783869419869c9b8be1c73c2850c42efb35915e85e8cc5a
# Code AST SHA-256:   d0e08cc3afc147208a99ec74a3827c43ef24eede2175b292ca8bae2086105ad7
# Verified Classes:   SpanLinkRefused, SpanHandle, EmitContext
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpanLinkRefused(RuntimeError):
    """Raised when a child span cannot be linked to an intact parent handle."""


@dataclass(frozen=True)
class SpanHandle:
    trace_id: str
    span_id: str
    end_time_ns: Optional[int]  # None while the span is still open
    link_status: str = "intact"  # "intact" | "compacted" | "missing"


@dataclass(frozen=True)
class EmitContext:
    parent_handle: Optional[SpanHandle]
    child_start_time_ns: int
    operation_name: str


def resolve_parent_link(ctx: EmitContext) -> Optional[SpanHandle]:
    """
    Decide whether a child span may be linked to a parent.
    Returns the parent handle to link, or None to emit an orphan span.
    Raises SpanLinkRefused when the caller is about to infer a parent.
    """
    handle = ctx.parent_handle

    if handle is None:
        # Absence is broken, not root. Emit orphan; never infer.
        return None

    if handle.link_status in ("compacted", "missing"):
        return None

    if handle.end_time_ns is not None and handle.end_time_ns < ctx.child_start_time_ns:
        # Parent already closed before this child began: stale or skewed.
        # Refuse rather than attach a child to a dead parent window.
        raise SpanLinkRefused(
            f"parent span {handle.span_id} closed at {handle.end_time_ns} "
            f"before child {ctx.operation_name} start {ctx.child_start_time_ns}"
        )

    return handle


def emit_child_span(ctx: EmitContext, emitter) -> None:
    try:
        parent = resolve_parent_link(ctx)
    except SpanLinkRefused:
        # Do not fall back to inference. Emit orphan with explicit marker.
        emitter.emit(
            operation_name=ctx.operation_name,
            parent=None,
            attributes={
                "gen_ai.parent.link_status": "broken",
                "gen_ai.parent.orphan_reason": "parent_closed_before_child",
            },
        )
        return

    if parent is None:
        emitter.emit(
            operation_name=ctx.operation_name,
            parent=None,
            attributes={
                "gen_ai.parent.link_status": "broken",
                "gen_ai.parent.orphan_reason": "handle_missing_or_compacted",
            },
        )
        return

    emitter.emit(
        operation_name=ctx.operation_name,
        parent=parent,
        attributes={"gen_ai.parent.link_status": "intact"},
    )
