# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-opentelemetry-genai-instrumentation-silently-drop-tool-call-child-spans-when-the-parent-llm-span-closes-before-the-tool-execut.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-opentelemetry-genai-instrumentation-silently-drop-tool-call-child-spans-when-the-parent-llm-span-closes-before-the-tool-execut.warrant.json
# Markdown SHA-256:   51985b005f313826fa889b91e4dcc0e99775b0e572648acea06a74049ab8141e
# Code AST SHA-256:   e58a3ddee138598a5e88b705ed0a4f0ea35351a0b2c37e58facbc375394b5312
# Verified Classes:   OrphanedToolSpanError, SpanRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class OrphanedToolSpanError(RuntimeError):
    """Raised when a tool-call child span would be parented to an already-ended LLM span."""


@dataclass(frozen=True)
class SpanRecord:
    span_id: str
    parent_span_id: str | None
    start_ns: int
    end_ns: int | None
    name: str


def assert_tool_span_exportable(
    llm_span: SpanRecord,
    tool_span: SpanRecord,
    *,
    parent_ended_before_child_started: bool,
) -> None:
    """Validate that a tool span can be reconstructed by a backend as a child of the LLM span.

    The OpenTelemetry GenAI conventions assume tool spans nest inside the model
    invocation that requested them. When the model span is ended before the tool
    executor returns, the child span's start_time exceeds the parent's end_time,
    producing a causally inverted trace that many backends drop or re-root.
    """
    if tool_span.parent_span_id != llm_span.span_id:
        raise OrphanedToolSpanError(
            f"tool span {tool_span.span_id} has parent {tool_span.parent_span_id!r}, "
            f"expected LLM span {llm_span.span_id}"
        )

    if llm_span.end_ns is None:
        # Parent still open: nesting is valid, nothing to check.
        return

    if parent_ended_before_child_started or tool_span.start_ns > llm_span.end_ns:
        raise OrphanedToolSpanError(
            f"tool span {tool_span.span_id} ({tool_span.name}) starts at "
            f"{tool_span.start_ns} but parent LLM span {llm_span.span_id} "
            f"ended at {llm_span.end_ns}; span will be non-recording or "
            f"re-rooted by the backend. Capture the LLM Context before "
            f"ending the span and pass it via start_as_current_span(context=...)."
        )


def emit_tool_span(
    tracer,
    llm_span: SpanRecord,
    captured_context,
    tool_name: str,
    span_id: str,
    start_ns: int,
) -> SpanRecord:
    """Emit a tool span using an explicitly captured parent Context.

    The captured_context MUST be taken from the LLM span *before* it is ended.
    """
    if captured_context is None:
        raise OrphanedToolSpanError(
            f"no captured Context for tool {tool_name!r}; ambient parenting "
            f"under an ended LLM span {llm_span.span_id} will not export"
        )

    with tracer.start_as_current_span(
        name=f"execute_tool {tool_name}",
        context=captured_context,
        attributes={"gen_ai.tool.name": tool_name},
    ) as span:
        record = SpanRecord(
            span_id=span_id,
            parent_span_id=llm_span.span_id,
            start_ns=start_ns,
            end_ns=None,
            name=f"execute_tool {tool_name}",
        )
        assert_tool_span_exportable(llm_span, record, parent_ended_before_child_started=False)
        return record
