# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-agent-spans-from-double-counting-tokens-across-nested-tool-call-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-agent-spans-from-double-counting-tokens-across-nested-tool-call-spans.warrant.json
# Markdown SHA-256:   eb7e27da4284043b14b5ab9eef8b3d216fdff86c06a9ae860485d92ca2957977
# Code AST SHA-256:   8aa69d4ce8e07ef488580f81e76a1d37be3b31b18b35f1629e752388cbaf2ff8
# Verified Classes:   UsageAttributionError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class UsageAttributionError(RuntimeError):
    """Raised when a span violates the leaf-attribution invariant for GenAI usage."""

@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation: str            # "invoke_agent" | "chat" | "execute_tool"
    kind: str                 # "CLIENT" | "SERVER" | "INTERNAL"
    input_tokens: int | None = None
    output_tokens: int | None = None
    children: list["Span"] = field(default_factory=list)

def validate_leaf_attribution(span: Span) -> None:
    has_usage = span.input_tokens is not None or span.output_tokens is not None
    model_call_children = [c for c in span.children if c.operation == "chat"]
    if has_usage and model_call_children and span.operation != "chat":
        raise UsageAttributionError(
            f"span {span.span_id} ({span.operation}) carries usage attributes "
            f"but has {len(model_call_children)} chat descendants; "
            f"usage must be leaf-attributed only"
        )
    for child in span.children:
        validate_leaf_attribution(child)

def fold_usage(root: Span) -> tuple[int, int]:
    """Tree-fold over chat spans only; never a flat sum over the trace."""
    validate_leaf_attribution(root)
    total_in = total_out = 0
    stack = [root]
    while stack:
        s = stack.pop()
        if s.operation == "chat" and s.kind == "CLIENT":
            total_in += s.input_tokens or 0
            total_out += s.output_tokens or 0
        stack.extend(s.children)
    return total_in, total_out
