# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-a-genai-agent-span-when-a-tool-call-child-span-is-orphaned-by-context-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-close-a-genai-agent-span-when-a-tool-call-child-span-is-orphaned-by-context-propagation.warrant.json
# Markdown SHA-256:   8ae724dae2466110cf71a43c5e08342b15c02591430fb215692997fff508dcd9
# Code AST SHA-256:   4f9ed5b0ed5e8950a05bf5eddc7a13f016ad901ef8d0c57e336dc0be6b03e161
# Verified Classes:   OrphanedToolSpanError, SpanRef, AgentSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class OrphanedToolSpanError(RuntimeError):
    """Raised when a tool-call span cannot be proven to belong to the agent span's trace."""


@dataclass
class SpanRef:
    trace_id: str
    span_id: str
    ended: bool
    exported_locally: bool = True


@dataclass
class AgentSpan:
    trace_id: str
    span_id: str
    tool_call_id: str
    closed: bool = False


def close_agent_span(
    agent: AgentSpan,
    tool_span: SpanRef | None,
    tool_deadline_exceeded: bool,
) -> None:
    """
    Enforce the closure invariant: an agent span may not close OK unless every
    locally-exported tool span it initiated shares its trace_id and has ended.
    """
    if agent.closed:
        raise OrphanedToolSpanError(
            f"agent span {agent.span_id} already closed; double-close would corrupt usage"
        )

    # Remote tools export elsewhere; the agent cannot assert on their trace.
    if tool_span is not None and not tool_span.exported_locally:
        agent.closed = True
        return

    if tool_span is None:
        if not tool_deadline_exceeded:
            raise OrphanedToolSpanError(
                f"agent span {agent.span_id} attempted to close before tool "
                f"{agent.tool_call_id} reported any span; refusing to close early"
            )
        # Tool never emitted a span at all within its deadline: real defect.
        raise OrphanedToolSpanError(
            f"tool {agent.tool_call_id} produced no span within deadline; "
            f"agent span {agent.span_id} cannot claim trace completeness"
        )

    if not tool_span.ended:
        raise OrphanedToolSpanError(
            f"tool span {tool_span.span_id} still in flight; "
            f"closing agent span {agent.span_id} now would split the trace"
        )

    if tool_span.trace_id != agent.trace_id:
        raise OrphanedToolSpanError(
            f"tool span {tool_span.span_id} has trace_id={tool_span.trace_id} "
            f"but agent span {agent.span_id} has trace_id={agent.trace_id}; "
            f"context propagation lost across handoff (tool_call_id={agent.tool_call_id})"
        )

    agent.closed = True
