# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-when-tool-call-token-telemetry-is-emitted-asynchronously-after-span-close.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-attributes-when-tool-call-token-telemetry-is-emitted-asynchronously-after-span-close.warrant.json
# Markdown SHA-256:   960228e92510a98ae89c7362c53c9edb8e387fb80665837c6d062f8e71de902e
# Code AST SHA-256:   d58f950aac5cff0e142621b59f608707e23b2e86cb2f580012baec23ce7fed98
# Verified Classes:   UsageOrderingViolation, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

class UsageOrderingViolation(RuntimeError):
    """Raised when a span is closed before its terminal usage frame is applied."""
    pass

@dataclass
class GenAISpan:
    name: str
    attributes: dict = field(default_factory=dict)
    _ended: bool = False
    _usage_applied: bool = False
    _finish_reason_at: Optional[float] = None

    def set_attribute(self, key: str, value) -> None:
        if self._ended:
            # OTel SDK behavior: post-close writes are dropped. We refuse loudly.
            raise UsageOrderingViolation(
                f"set_attribute({key!r}) on ended span {self.name!r}; "
                "usage frame arrived after span close"
            )
        self.attributes[key] = value
        if key.startswith("gen_ai.usage."):
            self._usage_applied = True

    def on_finish_reason(self, reason: str) -> None:
        self.set_attribute("gen_ai.response.finish_reasons", [reason])
        self._finish_reason_at = time.monotonic()

    def on_usage_frame(self, input_tokens: int, output_tokens: int) -> None:
        if self._ended:
            raise UsageOrderingViolation(
                f"usage frame for {self.name!r} arrived after end(); "
                "provider emits usage after finish_reason — close on usage, not finish_reason"
            )
        self.set_attribute("gen_ai.usage.input_tokens", input_tokens)
        self.set_attribute("gen_ai.usage.output_tokens", output_tokens)

    def end(self, t_usage_deadline_s: float = 2.0) -> None:
        if self._finish_reason_at is not None and not self._usage_applied:
            waited = time.monotonic() - self._finish_reason_at
            if waited < t_usage_deadline_s:
                raise UsageOrderingViolation(
                    f"end() on {self.name!r} before usage frame; "
                    f"waited {waited:.3f}s < {t_usage_deadline_s}s — hold span open"
                )
            # Deadline exceeded: label the unknown rather than fabricate zero.
            self.attributes["genai.usage.reconciled"] = False
        self._ended = True


def close_streaming_turn(span: GenAISpan, frames: list[dict],
                         t_usage_deadline_s: float = 2.0) -> None:
    for frame in frames:
        kind = frame.get("kind")
        if kind == "content" and frame.get("finish_reason"):
            span.on_finish_reason(frame["finish_reason"])
        elif kind == "usage":
            span.on_usage_frame(frame["input_tokens"], frame["output_tokens"])
    span.end(t_usage_deadline_s=t_usage_deadline_s)
