# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-the-token-accounting-invariant-that-breaks-under-streaming-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-the-token-accounting-invariant-that-breaks-under-streaming-tool-call-fan-out.warrant.json
# Markdown SHA-256:   5602822a79e587bcc06901769de02e2aaeb811fdf94dcfdcb01efb98f259f425
# Code AST SHA-256:   e09dc58a79f85bb389c2c59cc22d5ffd65706c8058a166a810410a340bd732f7
# Verified Classes:   SpanClosureInvariantError, UsageAccumulator, AgentSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import threading
import time
from dataclasses import dataclass, field


class SpanClosureInvariantError(RuntimeError):
    """Raised when an invoke_agent span is asked to close while its
    GenAI child spans (model invocations / tool calls) are not quiesced
    or token usage has not reconciled. Exporting here would violate the
    parent/child terminal-state and token-sum invariants."""
    pass


@dataclass
class UsageAccumulator:
    input_tokens: int = 0
    output_tokens: int = 0
    expected_children: int = 0
    completed_children: int = 0
    open_tool_spans: int = 0
    _lock: threading.Lock = field(default_factory=threading.Lock)

    def register_child(self) -> None:
        with self._lock:
            self.expected_children += 1

    def record_model_usage(self, in_tok: int, out_tok: int) -> None:
        with self._lock:
            self.input_tokens += in_tok
            self.output_tokens += out_tok
            self.completed_children += 1

    def tool_open(self) -> None:
        with self._lock:
            self.open_tool_spans += 1

    def tool_close(self) -> None:
        with self._lock:
            self.open_tool_spans -= 1

    def is_quiesced(self) -> bool:
        with self._lock:
            return (
                self.completed_children == self.expected_children
                and self.open_tool_spans == 0
            )


class AgentSpan:
    def __init__(self, name: str):
        self.name = name
        self.usage = UsageAccumulator()
        self._closed = False
        self._violation = False

    def close(self, deadline_s: float = 2.0, force: bool = False) -> None:
        if self._closed:
            raise SpanClosureInvariantError(
                f"span {self.name!r} closed twice"
            )
        waited = 0.0
        step = 0.01
        while not self.usage.is_quiesced():
            if force and waited >= deadline_s:
                # shutdown path: export partial but TOMBSTONE it
                self._violation = True
                self._export(violation=True)
                self._closed = True
                return
            if waited >= deadline_s:
                raise SpanClosureInvariantError(
                    f"refusing to close {self.name!r}: "
                    f"{self.usage.expected_children - self.usage.completed_children} "
                    f"model children pending, {self.usage.open_tool_spans} tool spans open"
                )
            time.sleep(step)
            waited += step
        self._export(violation=False)
        self._closed = True

    def _export(self, violation: bool) -> None:
        attrs = {
            "gen_ai.usage.input_tokens": self.usage.input_tokens,
            "gen_ai.usage.output_tokens": self.usage.output_tokens,
            "gen_ai.agent.closure_invariant_violated": violation,
        }
        # exporter call omitted; in production this is append-only
        _ = attrs


def run_agent_turn(span: AgentSpan, stream_chunks, tool_invocations):
    span.usage.register_child()
    span.usage.register_child()  # second model turn registered up-front
    for chunk in stream_chunks:
        if chunk.get("type") == "usage":
            span.usage.record_model_usage(
                chunk["input_tokens"], chunk["output_tokens"]
            )
        if chunk.get("type") == "tool_call":
            span.usage.tool_open()
            tool_invocations.append(chunk["tool_call_id"])
    # caller must close tool spans; if any remain open, close() rejects


def close_agent_span_safely(span: AgentSpan, force: bool = False) -> None:
    try:
        span.close(deadline_s=2.0, force=force)
    except SpanClosureInvariantError:
        # do not swallow: propagate so orchestrator quarantines the trace
        raise
