# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-agent-span-s-token-accounting-as-authoritative-across-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-genai-agent-span-s-token-accounting-as-authoritative-across-tool-call-boundaries.warrant.json
# Markdown SHA-256:   eb568142721b66c1160d9785aed216f95c1abb1dd1364880586c6db7fec8b604
# Code AST SHA-256:   f94300d84fefb12ead53d8278516ec2f6c3b4284941e3b179abea98588ffd663
# Verified Classes:   NonAuthoritativeUsageError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class NonAuthoritativeUsageError(RuntimeError):
    """Raised when usage attributes are aggregated across a boundary that
    makes them non-authoritative (tool spans, nested agents, or error spans)."""


MODEL_OPS = {"chat", "text_completion", "embeddings"}


@dataclass
class Span:
    name: str
    operation: str
    attributes: dict = field(default_factory=dict)
    status: str = "OK"
    children: list["Span"] = field(default_factory=list)

    def has_usage(self) -> bool:
        return any(k.startswith("gen_ai.usage.") for k in self.attributes)


def aggregate_authoritative_usage(root: Span) -> int:
    """Sum input_tokens only over model-invocation spans owned by *this*
    process, refusing to fold in tool spans or nested agent containers."""
    total = 0
    stack = [root]
    while stack:
        span = stack.pop()
        if span.operation == "execute_tool" and span.has_usage():
            raise NonAuthoritativeUsageError(
                f"tool span {span.name!r} carries gen_ai.usage.*; "
                "these are tool-side tokens, not agent tokens"
            )
        if span.operation in MODEL_OPS:
            if span.status == "ERROR" and "gen_ai.usage.input_tokens" not in span.attributes:
                raise NonAuthoritativeUsageError(
                    f"model span {span.name!r} failed with unknown usage; "
                    "absent != zero and must not be summed"
                )
            total += int(span.attributes.get("gen_ai.usage.input_tokens", 0))
            # Do not descend into children of a model span: they belong to
            # a different ownership boundary (e.g., a tool the model called).
            continue
        stack.extend(span.children)
    return total
