# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-when-genai-span-attributes-silently-mis-account-tokens-across-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-when-genai-span-attributes-silently-mis-account-tokens-across-tool-call-boundaries.warrant.json
# Markdown SHA-256:   75d5ebd5f36b51ebfe2666767f2338fd0626d7a2d088fbcbb6de8f34ac0d372b
# Code AST SHA-256:   52915625ce8c9b8e4d471c937bb351b7a773f23a30088a56b7049d8eca177334
# Verified Classes:   TokenAccountingInvariantError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a GenAI span tree violates the usage-summation invariant."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation: str                      # gen_ai.operation.name
    input_tokens: int | None = None     # gen_ai.usage.input_tokens
    output_tokens: int | None = None    # gen_ai.usage.output_tokens
    status: str = "OK"
    children: list["Span"] = field(default_factory=list)


INFERENCE_OPS = {"chat", "text_completion", "generate_content"}


def audit_usage_summation(root: Span) -> int:
    """
    Walk the span tree and return the true billed input-token total.
    Raises TokenAccountingInvariantError if the summation invariant is violated.
    """
    billed_input = 0
    # path_usage tracks, for the current root-to-leaf path, which span owns usage.
    def walk(span: Span, path_usage_owner: str | None) -> None:
        nonlocal billed_input
        carries_usage = span.input_tokens is not None or span.output_tokens is not None

        if carries_usage and span.operation == "execute_tool":
            raise TokenAccountingInvariantError(
                f"tool span {span.span_id} ({span.operation}) carries gen_ai.usage.* "
                f"attributes; this is context propagation, not billing, and will "
                f"double-count in any tree-sum aggregate."
            )

        if carries_usage and span.operation in INFERENCE_OPS:
            if path_usage_owner is not None:
                raise TokenAccountingInvariantError(
                    f"usage double-count on path: span {span.span_id} "
                    f"({span.operation}) and ancestor {path_usage_owner} both "
                    f"carry gen_ai.usage.*; tree-sum will inflate the billed total."
                )
            if span.status != "ERROR":
                billed_input += span.input_tokens or 0
            path_usage_owner = span.span_id

        for child in span.children:
            walk(child, path_usage_owner)

    walk(root, None)
    return billed_input


def governed_budget_check(root: Span, budget: int) -> int:
    """Refuse to hand a tree-sum to a budget governor unless the invariant holds."""
    billed = audit_usage_summation(root)
    if billed > budget:
        raise TokenAccountingInvariantError(
            f"billed input {billed} exceeds budget {budget}; "
            f"agent will enter truncation mode."
        )
    return budget - billed
