# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-agent-spans-as-non-authoritative-for-token-accounting-when-tool-calls-cross-process-bound.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-agent-spans-as-non-authoritative-for-token-accounting-when-tool-calls-cross-process-bound.warrant.json
# Markdown SHA-256:   1245b4ebeb533da79862601b2b6f247394944af0af5aba37a547e200a02100c8
# Code AST SHA-256:   6e572d489b739ec9a4469d1bf81013b8a751972e75476665139144f342de7f05
# Verified Classes:   NonAuthoritativeTokenRollupError, SpanUsage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class NonAuthoritativeTokenRollupError(RuntimeError):
    """Raised when an agent-span token rollup is consumed as billing-grade truth
    despite crossing a process/sampling/convention boundary."""


@dataclass
class SpanUsage:
    span_id: str
    service_name: str
    usage_convention: str  # "stable" | "legacy"
    input_tokens: int
    output_tokens: int
    sampled: bool


def assert_rollup_is_authoritative(
    agent_service: str,
    children: Iterable[SpanUsage],
    require_exact: bool,
) -> int:
    """Validate that an agent span's token rollup may be trusted.

    Returns the total token count only when the rollup is authoritative.
    Raises NonAuthoritativeTokenRollupError otherwise.
    """
    total = 0
    for child in children:
        if child.service_name != agent_service:
            if require_exact:
                raise NonAuthoritativeTokenRollupError(
                    f"child span {child.span_id} from service "
                    f"'{child.service_name}' crosses a process boundary; "
                    f"rollup is not billing-grade"
                )
        if child.usage_convention != "stable":
            if require_exact:
                raise NonAuthoritativeTokenRollupError(
                    f"child span {child.span_id} uses legacy usage convention "
                    f"'{child.usage_convention}'; names do not match stable "
                    f"gen_ai.usage.input_tokens"
                )
        if not child.sampled:
            if require_exact:
                raise NonAuthoritativeTokenRollupError(
                    f"child span {child.span_id} was not sampled; rollup is a "
                    f"lower bound with unknown error"
                )
        total += child.input_tokens + child.output_tokens
    return total


def meter_for_billing(agent_service: str, children: list[SpanUsage]) -> int:
    # Billing path demands exactness; any boundary invalidates the rollup.
    return assert_rollup_is_authoritative(agent_service, children, require_exact=True)
