# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-genai-tool-call-span-the-parent-child-span-timing-invariant-and-its-silent-violation-under-streaming-token-acc.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-a-genai-tool-call-span-the-parent-child-span-timing-invariant-and-its-silent-violation-under-streaming-token-acc.warrant.json
# Markdown SHA-256:   77e8193f8e0d72a5460ae57a3655a272486dd08d34f05334580551da10116eb3
# Code AST SHA-256:   640e601bad074d9e3a317d43c042ed365d6ca77e4f104318f4e52841fb0ac75b
# Verified Classes:   GenAISpanInvariantError, Span, GuardedSpanProcessor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class GenAISpanInvariantError(RuntimeError):
    """Raised when a tool-call span would be exported before its parent model
    span has committed end_time and gen_ai.usage.* accounting."""


@dataclass
class Span:
    name: str
    parent_id: Optional[str]
    start_ns: int
    end_ns: Optional[int] = None
    attrs: dict = field(default_factory=dict)

    @property
    def is_model_span(self) -> bool:
        return self.attrs.get("gen_ai.operation.name") == "chat"

    @property
    def is_tool_span(self) -> bool:
        return self.attrs.get("gen_ai.operation.name") == "execute_tool"

    def has_usage(self) -> bool:
        return (
            "gen_ai.usage.input_tokens" in self.attrs
            and "gen_ai.usage.output_tokens" in self.attrs
        )


class GuardedSpanProcessor:
    """Buffers tool spans whose parent model span has not yet committed
    end_time + usage. Refuses to export an orphaned tool span."""

    def __init__(self) -> None:
        self._ended: dict[str, Span] = {}
        self._pending_children: dict[str, list[Span]] = {}
        self._exported: list[Span] = []

    def on_end(self, span: Span) -> None:
        if span.end_ns is None:
            raise GenAISpanInvariantError(f"span {span.name} ended without end_ns")
        self._ended[span.name] = span

        if span.is_model_span and not span.has_usage():
            # Force-closed at timeout: usage is unknown. We must still emit a
            # value so reconciliation holds; zero + error marker is the only
            # convention-compatible way to stay summable.
            span.attrs.setdefault("gen_ai.usage.input_tokens", 0)
            span.attrs.setdefault("gen_ai.usage.output_tokens", 0)
            span.attrs.setdefault("error.type", "stream_incomplete")

        if span.is_model_span:
            for child in self._pending_children.pop(span.name, []):
                self._export(child, parent=span)

    def try_export_child(self, child: Span) -> None:
        if not child.is_tool_span:
            self._export(child, parent=None)
            return
        parent = self._ended.get(child.parent_id or "")
        if parent is None or not parent.is_model_span:
            self._pending_children.setdefault(child.parent_id or "", []).append(child)
            return
        if parent.end_ns is None or not parent.has_usage():
            raise GenAISpanInvariantError(
                f"tool span {child.name} cannot export: parent model span "
                f"{parent.name} has end_ns={parent.end_ns} usage={parent.has_usage()}"
            )
        if child.end_ns is None or child.end_ns > parent.end_ns:
            raise GenAISpanInvariantError(
                f"tool span {child.name} ends after parent {parent.name}; "
                f"containment invariant violated"
            )
        self._export(child, parent=parent)

    def _export(self, span: Span, parent: Optional[Span]) -> None:
        self._exported.append(span)


def reconcile_token_totals(processor: GuardedSpanProcessor) -> int:
    """Sum input tokens across all exported model spans. Must equal the
    provider's billed total; any orphaned tool span breaks this."""
    total = 0
    for span in processor._exported:
        if span.is_model_span:
            if not span.has_usage():
                raise GenAISpanInvariantError(
                    f"model span {span.name} exported without usage attributes"
                )
            total += span.attrs["gen_ai.usage.input_tokens"]
    return total
