# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-agent-span-when-child-tool-call-spans-are-orphaned-by-async-token-accounting.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-close-a-genai-agent-span-when-child-tool-call-spans-are-orphaned-by-async-token-accounting.warrant.json
# Markdown SHA-256:   09a80ccaeb846ee9102b234a626f6a7c32f432ab05fd31868c4065ebb84ac580
# Code AST SHA-256:   b592b02f525d3aa5a47313020bee57601a162f528923514b97b8bad09f88e822
# Verified Classes:   GenAISpanOrderingError, AgentSpanState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class GenAISpanOrderingError(RuntimeError):
    """Raised when a container agent span would be ended before its async
    children and async usage attribution have drained."""
    pass


@dataclass
class AgentSpanState:
    span_id: str
    operation_name: str            # e.g. "invoke_agent"
    is_container: bool
    usage_async: bool
    pending_children: int = 0
    usage_applied: bool = False
    ended: bool = False
    drain_deadline_s: float = 0.250
    _opened_at: float = field(default_factory=time.monotonic)

    def register_child(self) -> None:
        if self.ended:
            raise GenAISpanOrderingError(
                f"child dispatched to already-ended span {self.span_id}; "
                f"would be orphaned or re-parented to ambient ContextVar"
            )
        self.pending_children += 1

    def child_terminal(self) -> None:
        self.pending_children = max(0, self.pending_children - 1)

    def apply_usage(self, input_tokens: int, output_tokens: int) -> None:
        if self.ended:
            # This is the silent-drop path in the SDK; we make it loud.
            raise GenAISpanOrderingError(
                f"usage write to ended span {self.span_id} "
                f"({input_tokens}/{output_tokens} tokens) would be dropped"
            )
        self.usage_applied = True


def end_agent_span(state: AgentSpanState, now: Optional[float] = None) -> str:
    """Attempt to end a container span. Returns the terminal disposition."""
    now = now if now is not None else time.monotonic()

    if not state.is_container:
        state.ended = True
        return "ended"

    drained = state.pending_children == 0 and (
        state.usage_applied or not state.usage_async
    )
    if drained:
        state.ended = True
        return "ended"

    elapsed = now - state._opened_at
    if elapsed < state.drain_deadline_s:
        # Defer: caller must retry after children/usage report in.
        return "pending_drain"

    # Deadline exceeded. End, but stamp usage as UNKNOWN (absent), never zero.
    if state.usage_async and not state.usage_applied:
        # Do NOT write input_tokens=0; absence is the honest signal.
        state.ended = True
        return "ended_usage_unknown"

    if state.pending_children > 0:
        # Children still in flight past deadline: this is the re-parenting hazard.
        raise GenAISpanOrderingError(
            f"span {state.span_id} ending with {state.pending_children} "
            f"orphaned children after {elapsed:.3f}s; children will be "
            f"re-parented to ambient ContextVar and mis-attributed"
        )

    state.ended = True
    return "ended"
