# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-double-counted-token-usage-when-opentelemetry-genai-agent-spans-and-child-llm-spans-both-carry-gen-ai-usage-attributes-acr.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-double-counted-token-usage-when-opentelemetry-genai-agent-spans-and-child-llm-spans-both-carry-gen-ai-usage-attributes-acr.warrant.json
# Markdown SHA-256:   3e738df1715ac475cd81090ce390c0fa4600044d858121d2d661a91e5eba4bc1
# Code AST SHA-256:   a7a43cbb55e6a7debc6363bccae5dcb0d1ff8f064e04437b3511da00f5df256d
# Verified Classes:   TokenDoubleCountError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class TokenDoubleCountError(RuntimeError):
    """Raised when a span carries gen_ai.usage.* while a descendant also does."""


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    name: str
    operation: str | None  # gen_ai.operation.name
    has_usage: bool        # carries gen_ai.usage.input_tokens or output_tokens
    children: list["Span"] = field(default_factory=list)


def _descendant_has_usage(span: Span) -> bool:
    stack = list(span.children)
    while stack:
        node = stack.pop()
        if node.has_usage:
            return True
        stack.extend(node.children)
    return False


def assert_no_double_counted_usage(root: Span) -> None:
    """Walk the assembled trace and reject summable-usage violations.

    A span that carries usage attributes is only summable if no descendant
    span also carries them. Agent spans that accumulate child usage violate
    this invariant and must be tagged as aggregates before any cost query.
    """
    stack = [root]
    while stack:
        span = stack.pop()
        if span.has_usage and _descendant_has_usage(span):
            raise TokenDoubleCountError(
                f"span {span.span_id!r} ({span.name!r}, "
                f"operation={span.operation!r}) carries gen_ai.usage.* "
                f"while a descendant also carries it; summing this trace "
                f"will double-count tokens. Tag the span as an aggregate "
                f"or strip its usage attributes before export."
            )
        stack.extend(span.children)
