# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-parent-agent-span-when-opentelemetry-genai-tool-call-events-are-still-in-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-parent-agent-span-when-opentelemetry-genai-tool-call-events-are-still-in-flight.warrant.json
# Markdown SHA-256:   73548f583669c8afe16bea593537862e75238473ce30d18652efafaa9752ee1b
# Code AST SHA-256:   a2331cd20f90386e0963ce5a9c210fc117ff95964a9a8dd41d567deb0f5a4bf6
# Verified Classes:   SpanDrainViolation, AgentSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class SpanDrainViolation(RuntimeError):
    """Raised when a parent agent span would close with tool-call children still in flight."""
    pass


@dataclass
class AgentSpan:
    name: str
    in_flight_tools: int = 0
    ended: bool = False
    drain_incomplete: bool = False
    abandoned_children: int = 0
    cost_accumulated: float = 0.0


def dispatch_tool(parent: AgentSpan) -> None:
    if parent.ended:
        raise SpanDrainViolation(
            f"tool dispatched against ended span {parent.name!r}; "
            "parent must not close before children are dispatched"
        )
    parent.in_flight_tools += 1


def close_tool(parent: AgentSpan, tool_cost: float) -> None:
    parent.in_flight_tools = max(0, parent.in_flight_tools - 1)
    parent.cost_accumulated += tool_cost


def end_agent_span(parent: AgentSpan, terminal_turn: bool, drain_deadline_s: float) -> None:
    if not terminal_turn:
        raise SpanDrainViolation(
            f"end_agent_span called for {parent.name!r} on a non-terminal model turn"
        )
    if parent.in_flight_tools > 0:
        # bounded drain: wait, but never indefinitely
        deadline = time.monotonic() + drain_deadline_s
        while parent.in_flight_tools > 0 and time.monotonic() < deadline:
            time.sleep(0.01)
        if parent.in_flight_tools > 0:
            parent.drain_incomplete = True
            parent.abandoned_children = parent.in_flight_tools
    parent.ended = True
