# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-tool-call-span-the-gen-ai-tool-call-id-correlation-invariant-and-the-orphaned-child-span-hazard.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-tool-call-span-the-gen-ai-tool-call-id-correlation-invariant-and-the-orphaned-child-span-hazard.warrant.json
# Markdown SHA-256:   bf836d351b5d3c63e3d036e1407829081eaf0b094b5c813ae4e743c05c209b57
# Code AST SHA-256:   e6154c2f59040de1405ef1d72a1b79aea5970838c4e3a0115bf69532903447a5
# Verified Classes:   OrphanedToolSpanError, Span, SpanBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class OrphanedToolSpanError(RuntimeError):
    """Raised when a tool-call span would reference an evicted parent span."""
    pass


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: Optional[str]
    gen_ai_tool_call_id: Optional[str] = None
    start_time: float = field(default_factory=time.monotonic)
    end_time: Optional[float] = None


class SpanBuffer:
    """Models an async exporter buffer with eviction."""

    def __init__(self, retention_seconds: float) -> None:
        self.retention_seconds = retention_seconds
        self._retained: dict[str, Span] = {}
        self._evicted: set[str] = set()

    def retain(self, span: Span) -> None:
        self._retained[span.span_id] = span

    def evict(self, span: Span) -> None:
        self._retained.pop(span.span_id, None)
        self._evicted.add(span.span_id)

    def is_retained(self, span_id: str) -> bool:
        return span_id in self._retained

    def was_evicted(self, span_id: str) -> bool:
        return span_id in self._evicted


def finalize_tool_span(
    buffer: SpanBuffer,
    parent: Span,
    tool_span: Span,
    tool_deadline: float,
    now: float,
) -> Span:
    """
    Enforce the correlation invariant before emitting a GenAI tool-call span.

    Boundary: if (now - parent.start_time) > buffer.retention_seconds, the parent
    has been (or will be) evicted and the child cannot carry a correlating
    gen_ai.tool.call.id.
    """
    if tool_span.gen_ai_tool_call_id is None:
        raise OrphanedToolSpanError(
            f"tool span {tool_span.span_id} has no gen_ai.tool.call.id; "
            "cannot correlate token accounting"
        )

    parent_age = now - parent.start_time
    parent_retained = buffer.is_retained(parent.span_id)

    if parent_age > buffer.retention_seconds and not parent_retained:
        # Parent already flushed/evicted: emitting a correlating child is invalid.
        if tool_span.gen_ai_tool_call_id == parent.gen_ai_tool_call_id:
            raise OrphanedToolSpanError(
                f"tool span {tool_span.span_id} references call_id "
                f"{tool_span.gen_ai_tool_call_id!r} whose parent {parent.span_id} "
                f"was evicted after {parent_age:.1f}s "
                f"(retention={buffer.retention_seconds:.1f}s); "
                "demote to detached span or extend parent retention"
            )

    if tool_span.start_time < parent.start_time:
        raise OrphanedToolSpanError(
            f"tool span {tool_span.span_id} start_time precedes parent "
            f"{parent.span_id} start_time; ordering invariant violated"
        )

    tool_span.end_time = now
    return tool_span
