# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-child-span-token-usage-to-the-wrong-genai-semantic-convention-generation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-child-span-token-usage-to-the-wrong-genai-semantic-convention-generation.warrant.json
# Markdown SHA-256:   904029e340589676a4b20461fae57c1c43571a23929b1b02ae2645ffd0222312
# Code AST SHA-256:   bef895ba016d47460598fa0ecfdc1efaf5b8c7e232f0be57c80b0092002e5f45
# Verified Classes:   TokenAccountingInvariantError, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a trace's GenAI usage attributes violate the
    leaf-sum == rollup invariant under the exclusive-accounting model."""


@dataclass
class Span:
    name: str
    operation: str  # "invoke_agent" | "chat" | "execute_tool"
    input_tokens: int = 0
    output_tokens: int = 0
    children: list["Span"] = field(default_factory=list)
    disambiguator: bool = False  # gen_ai.usage.aggregate == true


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


def verify_token_accounting(root: Span) -> None:
    """Enforce: sum of leaf chat usage == any rollup usage on non-leaf spans,
    and every non-leaf span carrying usage must carry a disambiguator."""
    leaf_input = leaf_output = 0
    rollup_input = rollup_output = 0

    for span in _walk(root):
        has_usage = span.input_tokens or span.output_tokens
        if not has_usage:
            continue
        is_leaf = not span.children
        if is_leaf:
            leaf_input += span.input_tokens
            leaf_output += span.output_tokens
        else:
            if not span.disambiguator:
                raise TokenAccountingInvariantError(
                    f"non-leaf span {span.name!r} ({span.operation}) carries "
                    f"gen_ai.usage.* without a disambiguator; backend leaf-sum "
                    f"aggregation will double-count it"
                )
            rollup_input += span.input_tokens
            rollup_output += span.output_tokens

    if rollup_input and rollup_input != leaf_input:
        raise TokenAccountingInvariantError(
            f"input token mismatch: leaf-sum={leaf_input} rollup={rollup_input} "
            f"(delta {rollup_input - leaf_input}); retry attempts may be "
            f"stamped on a wrapper span instead of as sibling chat spans"
        )
    if rollup_output and rollup_output != leaf_output:
        raise TokenAccountingInvariantError(
            f"output token mismatch: leaf-sum={leaf_output} rollup={rollup_output}"
        )


def enforce_or_halt(root: Span, budget_input: int) -> None:
    try:
        verify_token_accounting(root)
    except TokenAccountingInvariantError:
        # Do not feed a corrupt total into budget enforcement; halt the run
        # rather than let the agent silently under-spend against phantom usage.
        raise
    total = sum(s.input_tokens for s in _walk(root) if not s.children)
    if total > budget_input:
        raise TokenAccountingInvariantError(
            f"budget exceeded on verified total: {total} > {budget_input}"
        )
