# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-token-counts-as-non-additive-across-agent-handoffs-and-how-does-the-gen-ai-usage.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-span-token-counts-as-non-additive-across-agent-handoffs-and-how-does-the-gen-ai-usage.warrant.json
# Markdown SHA-256:   76bf670f5d39f8fc340eb7bcac7c2f1a7e45ace9b27a04889fa9de380df72a16
# Code AST SHA-256:   aa66692a7f519e9d3e865120bd1a46707c01000c3e8511bc14efb6f3dfcbb0aa
# Verified Classes:   TokenAccountingInvariantError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

class TokenAccountingInvariantError(RuntimeError):
    """Raised when per-span GenAI usage attributes cannot be summed safely."""

@dataclass(frozen=True)
class GenAISpan:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    operation_name: str          # gen_ai.operation.name
    tool_call_id: str | None     # gen_ai.tool.call.id
    input_tokens: int | None     # gen_ai.usage.input_tokens
    output_tokens: int | None    # gen_ai.usage.output_tokens

_MODEL_OPS = {"invoke_agent", "chat", "text_completion"}

def safe_token_rollup(spans: Iterable[GenAISpan]) -> int:
    spans = list(spans)
    seen_tool_calls: set[tuple[str, str]] = set()
    total = 0
    for s in spans:
        if s.input_tokens is None:
            continue
        if s.operation_name not in _MODEL_OPS:
            # tool span carrying usage => inherited attribute, not a model event
            raise TokenAccountingInvariantError(
                f"span {s.span_id} op={s.operation_name} carries "
                f"input_tokens={s.input_tokens}; attribute inherited across "
                f"re-parent, not summable"
            )
        if s.tool_call_id is not None:
            key = (s.trace_id, s.tool_call_id)
            if key in seen_tool_calls:
                raise TokenAccountingInvariantError(
                    f"duplicate tool_call_id {s.tool_call_id} in trace "
                    f"{s.trace_id}: span re-parented, dedupe before summing"
                )
            seen_tool_calls.add(key)
        total += s.input_tokens
    return total

def assert_root_anchored(spans: list[GenAISpan]) -> int:
    roots = [s for s in spans if s.parent_span_id is None]
    if len(roots) != 1:
        raise TokenAccountingInvariantError(
            f"expected exactly one root span, found {len(roots)}; "
            f"trace may have been split by mid-run exporter flush"
        )
    root = roots[0]
    if root.input_tokens is None:
        raise TokenAccountingInvariantError(
            f"root span {root.span_id} missing gen_ai.usage.input_tokens; "
            f"cannot anchor accounting"
        )
    return root.input_tokens
