# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-propagate-trace-context-when-an-agent-span-suspends-for-an-asynchronous-tool-call-and-why-the-naive-handoff-silently-orphans-ch.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-propagate-trace-context-when-an-agent-span-suspends-for-an-asynchronous-tool-call-and-why-the-naive-handoff-silently-orphans-ch.warrant.json
# Markdown SHA-256:   c4d0d94bdf2df8bbc3460f105f8c134e80eb95118188049f03c2a954ede10be2
# Code AST SHA-256:   5c6abe6240b26e8e09c3e9c9e647a9f708c15d0f861e34975732b8b5f76edece
# Verified Classes:   TraceContextOrphanError, SpanHandle
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional, Mapping


class TraceContextOrphanError(RuntimeError):
    """Raised when a child span would be parented to a span that is no longer live."""
    pass


@dataclass(frozen=True)
class SpanHandle:
    trace_id: str
    span_id: str
    sampled: bool
    trace_state: str
    is_open: bool


def carrier_from_span(span: SpanHandle) -> Mapping[str, str]:
    # Full carrier: dropping trace_flags or trace_state is the root-split bug.
    return {
        "traceparent": f"00-{span.trace_id}-{span.span_id}-{'01' if span.sampled else '00'}",
        "tracestate": span.trace_state,
    }


def create_child_span(
    parent: SpanHandle,
    name: str,
    *,
    allow_link_fallback: bool,
) -> SpanHandle:
    """Create a child span across an async tool-call boundary.

    The parent agent span may be suspended; it must still be OPEN to be a
    valid parent. If it is closed, we refuse to fabricate a parent and
    require link semantics instead.
    """
    if not parent.is_open:
        if not allow_link_fallback:
            raise TraceContextOrphanError(
                f"cannot parent span {name!r} to closed span {parent.span_id}; "
                "keep the agent span open across the await, or use link semantics"
            )
        # Link semantics: no parent_id, record a link to the closed span.
        return SpanHandle(
            trace_id=parent.trace_id,
            span_id=_new_span_id(),
            sampled=parent.sampled,
            trace_state=parent.trace_state,
            is_open=True,
        )

    if not parent.sampled and parent.trace_state == "":
        # Guard against silently dropping the sampled bit during handoff.
        raise TraceContextOrphanError(
            f"carrier for span {parent.span_id} lost trace_flags/trace_state; "
            "worker would start a new root"
        )

    return SpanHandle(
        trace_id=parent.trace_id,
        span_id=_new_span_id(),
        sampled=parent.sampled,
        trace_state=parent.trace_state,
        is_open=True,
    )


def _new_span_id() -> str:
    import secrets
    return secrets.token_hex(8)


def suspend_agent_span(span: SpanHandle) -> SpanHandle:
    """Mark the agent span suspended but still OPEN — do not end it here."""
    if not span.is_open:
        raise TraceContextOrphanError("suspend on an already-closed span")
    return SpanHandle(
        trace_id=span.trace_id,
        span_id=span.span_id,
        sampled=span.sampled,
        trace_state=span.trace_state,
        is_open=True,  # stays open across the async boundary
    )
