# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-otel-genai-span-trees-from-silently-double-counting-tokens-when-an-agent-retries-a-tool-call-inside-a-nested-span.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-otel-genai-span-trees-from-silently-double-counting-tokens-when-an-agent-retries-a-tool-call-inside-a-nested-span.warrant.json
# Markdown SHA-256:   332566438a02ca549add4ec38f1b51f0cbc3576d80b2a8e0a094f95d3fb52360
# Code AST SHA-256:   afaa3c9cb32c043fe68ef12fd73cad2d128e0b7e0cb448d8bf2b170d9b76f888
# Verified Classes:   GenAiSpanInvariantError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class GenAiSpanInvariantError(RuntimeError):
    """Raised when an agent span violates the GenAI token-accounting invariant."""


@dataclass
class Span:
    name: str
    operation: str
    attributes: dict = field(default_factory=dict)
    children: list = field(default_factory=list)

    def set_usage(self, input_tokens: int, output_tokens: int) -> None:
        self.attributes["gen_ai.usage.input_tokens"] = input_tokens
        self.attributes["gen_ai.usage.output_tokens"] = output_tokens


def assert_leaf_only_usage(span: Span) -> None:
    """Enforce: only operation spans carry gen_ai.usage.*; invoke_agent spans carry none."""
    usage_keys = {"gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens"}
    has_usage = usage_keys & set(span.attributes)
    if span.operation == "invoke_agent" and has_usage:
        raise GenAiSpanInvariantError(
            f"agent span {span.name!r} carries {sorted(has_usage)}; "
            "usage must be leaf-attributed to chat/execute_tool spans only"
        )
    for child in span.children:
        assert_leaf_only_usage(child)


def sum_billable_tokens(root: Span) -> int:
    """Sum usage over leaf operation spans only, never over invoke_agent parents."""
    assert_leaf_only_usage(root)  # fail fast before any aggregation
    total = 0
    stack = [root]
    while stack:
        s = stack.pop()
        if s.operation != "invoke_agent":
            total += s.attributes.get("gen_ai.usage.input_tokens", 0)
            total += s.attributes.get("gen_ai.usage.output_tokens", 0)
        stack.extend(s.children)
    return total


def build_retry_trace(violating: bool) -> Span:
    agent = Span(name="researcher", operation="invoke_agent")
    attempt1 = Span(name="search", operation="execute_tool")
    attempt1.set_usage(812, 44)
    attempt1.attributes["gen_ai.retry.attempt"] = 1
    attempt2 = Span(name="search", operation="execute_tool")
    attempt2.set_usage(812, 51)
    attempt2.attributes["gen_ai.retry.attempt"] = 2
    agent.children.extend([attempt1, attempt2])
    if violating:
        # framework retry wrapper leaks aggregate onto the parent
        agent.set_usage(1624, 95)
    return agent


if __name__ == "__main__":
    good = build_retry_trace(violating=False)
    print("billable:", sum_billable_tokens(good))  # 1719, correct

    bad = build_retry_trace(violating=True)
    try:
        sum_billable_tokens(bad)
    except GenAiSpanInvariantError as e:
        print("rejected:", e)
