# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-gen-ai-usage-input-tokens-be-attributed-when-an-agent-span-fans-out-to-multiple-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-gen-ai-usage-input-tokens-be-attributed-when-an-agent-span-fans-out-to-multiple-tool-calls.warrant.json
# Markdown SHA-256:   5e402bb36bf80fd5dbd1c263afbb37bc451e1200e5ce906f61e72f194e82e94f
# Code AST SHA-256:   84f47ed34fbf2ce6cfd9a08a65f5c55eeb1609db199b08d2a07789e6459c5620
# Verified Classes:   TokenAttributionError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class TokenAttributionError(RuntimeError):
    """Raised when gen_ai.usage.* attributes are placed on a span that must not own them."""


@dataclass
class Span:
    name: str
    kind: str  # "agent" | "chat" | "tool"
    attributes: dict[str, object] = field(default_factory=dict)
    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 validate_attribution(span: Span) -> None:
    """Enforce single-owner token attribution across an agent span tree."""
    if span.kind == "tool" and span.has_usage():
        raise TokenAttributionError(
            f"tool span {span.name!r} carries gen_ai.usage.* attributes; "
            "tool execution consumes no model tokens"
        )

    if span.kind == "agent" and span.has_usage():
        aggregate_marker = span.attributes.get("gen_ai.usage.aggregate")
        if aggregate_marker != "sum":
            raise TokenAttributionError(
                f"agent container span {span.name!r} carries gen_ai.usage.* without "
                "gen_ai.usage.aggregate='sum'; this double-counts child chat spans"
            )
        if not any(c.kind == "chat" and c.has_usage() for c in span.children):
            raise TokenAttributionError(
                f"agent span {span.name!r} declares aggregate usage but has no "
                "child chat span carrying usage; rollup is unverifiable"
            )

    for child in span.children:
        validate_attribution(child)


def trace_total_tokens(root: Span) -> int:
    """Sum tokens exactly once: prefer leaf chat spans, honor aggregate marker."""
    total = 0
    for span in walk(root):
        if span.kind == "chat" and span.has_usage():
            total += int(span.attributes.get("gen_ai.usage.input_tokens", 0))
            total += int(span.attributes.get("gen_ai.usage.output_tokens", 0))
    return total


def walk(span: Span):
    yield span
    for child in span.children:
        yield from walk(child)


if __name__ == "__main__":
    good = Span(
        name="invoke_agent",
        kind="agent",
        children=[
            Span("chat.turn1", "chat", {"gen_ai.usage.input_tokens": 1000}),
            Span("execute_tool.search", "tool", {}),
            Span("chat.turn2", "chat", {"gen_ai.usage.input_tokens": 1400}),
        ],
    )
    validate_attribution(good)
    assert trace_total_tokens(good) == 2400

    bad = Span(
        name="invoke_agent",
        kind="agent",
        attributes={"gen_ai.usage.input_tokens": 2400},
        children=[Span("chat.turn1", "chat", {"gen_ai.usage.input_tokens": 1000})],
    )
    validate_attribution(bad)  # raises TokenAttributionError
