# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-emit-a-genai-tool-call-span-when-its-parent-agent-span-has-already-been-closed-by-an-out-of-band-completion-signal.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-emit-a-genai-tool-call-span-when-its-parent-agent-span-has-already-been-closed-by-an-out-of-band-completion-signal.warrant.json
# Markdown SHA-256:   98e67918928cb69328540fcbecac7b8c2b1a022f9353893e63dd76b349f9b909
# Code AST SHA-256:   7b7a8a14d6e080a14614e1cd2fb84d1b455bbf43b8d956c3fbdf126b6274f95f
# Verified Classes:   OrphanedToolSpanError, SpanRef
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class OrphanedToolSpanError(RuntimeError):
    """Raised when a GenAI execute_tool span would be exported under an ended parent."""


@dataclass(frozen=True)
class SpanRef:
    name: str
    start_ns: int
    end_ns: Optional[int]  # None == still open
    operation: str


def validate_tool_span_export(
    tool_span: SpanRef,
    parent_agent_span: Optional[SpanRef],
    *,
    allow_reparent: bool = False,
) -> str:
    """Enforce the parent-containment invariant for gen_ai execute_tool spans.

    Returns a disposition string: "export", "reparent_orphan", or "drop_orphan".
    Raises OrphanedToolSpanError when the span is invalid and no bounded
    disposition was authorized by the caller.
    """
    if tool_span.operation != "execute_tool":
        return "export"

    if parent_agent_span is None:
        # No parent captured at dispatch: cannot attribute; must not silently export.
        if not allow_reparent:
            raise OrphanedToolSpanError(
                f"execute_tool span {tool_span.name!r} has no resolvable parent "
                "invoke_agent span; refusing silent root export"
            )
        return "reparent_orphan"

    if parent_agent_span.end_ns is None:
        # Parent still open: normal, valid nesting.
        return "export"

    if tool_span.start_ns > parent_agent_span.end_ns:
        # The exact failure mode: child started after the parent turn was closed
        # by an out-of-band completion signal (stop sequence, budget cutoff, cancel).
        if not allow_reparent:
            raise OrphanedToolSpanError(
                f"execute_tool span {tool_span.name!r} started at "
                f"{tool_span.start_ns} after parent {parent_agent_span.name!r} "
                f"ended at {parent_agent_span.end_ns}; "
                "parent-containment invariant violated"
            )
        return "reparent_orphan"

    # Child started before parent ended but may still outlive it; that is a
    # latency/attribution concern, not a containment violation.
    return "export"


def emit_tool_span(tool_span: SpanRef, parent: Optional[SpanRef], *, allow_reparent: bool) -> str:
    disposition = validate_tool_span_export(tool_span, parent, allow_reparent=allow_reparent)
    if disposition == "drop_orphan":
        raise OrphanedToolSpanError("orphan drop requested but not wired to counter")
    return disposition
