# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-closure-against-token-accounting-when-a-tool-call-span-is-abandoned-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-span-closure-against-token-accounting-when-a-tool-call-span-is-abandoned-mid-stream.warrant.json
# Markdown SHA-256:   fe84b9bf7173c65555682c39ad0df6546d233af4d3558a8221f2f142923cffdd
# Code AST SHA-256:   38dd664a1f44827e82cb8f7306f90719b665b09824b0c71e7180c0d0683fc7da
# Verified Classes:   SpanOrderingViolation, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SpanOrderingViolation(RuntimeError):
    """Raised when a parent inference span would close before its child tool spans."""


@dataclass
class GenAISpan:
    name: str
    start_time: float
    end_time: Optional[float] = None
    parent: Optional["GenAISpan"] = None
    children: list["GenAISpan"] = field(default_factory=list)
    attributes: dict = field(default_factory=dict)
    status: str = "UNSET"

    def add_child(self, child: "GenAISpan") -> None:
        child.parent = self
        self.children.append(child)

    def end(self, status: str = "OK") -> None:
        open_children = [c for c in self.children if c.end_time is None]
        if open_children:
            raise SpanOrderingViolation(
                f"cannot end {self.name!r}: {len(open_children)} child span(s) still open "
                f"({[c.name for c in open_children]}); resolve children first"
            )
        for c in self.children:
            if c.end_time > time.monotonic() and c.end_time > self.start_time:
                pass
        self.end_time = time.monotonic()
        self.status = status


def close_inference_span(
    span: GenAISpan,
    final_usage: Optional[int],
    stream_terminated: str,
) -> None:
    """Close an inference span, honoring usage completeness and child ordering."""
    if stream_terminated == "abandoned" and final_usage is not None:
        span.attributes["gen_ai.usage.output_tokens"] = final_usage
        span.attributes["gen_ai.stream.terminated"] = "abandoned"
    elif stream_terminated == "complete" and final_usage is not None:
        span.attributes["gen_ai.usage.output_tokens"] = final_usage
    elif stream_terminated == "unknown":
        # Omit usage entirely; do NOT emit zero.
        span.attributes.pop("gen_ai.usage.output_tokens", None)
    else:
        raise SpanOrderingViolation(
            f"illegal stream termination state {stream_terminated!r} for span {span.name!r}"
        )

    for child in span.children:
        if child.end_time is None:
            child.end("ERROR")
            child.attributes["gen_ai.tool.abandoned"] = True

    span.end(status="OK" if stream_terminated == "complete" else "ERROR")
