# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-double-counted-token-usage-when-otel-genai-spans-nest-across-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-double-counted-token-usage-when-otel-genai-spans-nest-across-tool-call-boundaries.warrant.json
# Markdown SHA-256:   469b61be83842e4dd5606f46e3d5fa77d2a6275805d66016a791a62cf14dc585
# Code AST SHA-256:   2b12a5b5fd5d7e0db1a4aad30ac695437af87a88fa9f6c057668717332ee492e
# Verified Classes:   TokenAccountingInvariantError, ChatSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a span tree's usage attributes cannot be reconciled
    under the declared context mode."""


@dataclass
class ChatSpan:
    operation_name: str
    input_tokens: int
    output_tokens: int


def aggregate_agent_input_tokens(
    spans: list[ChatSpan],
    context_mode: str,
    truncations: int = 0,
) -> int:
    chat_spans = [s for s in spans if s.operation_name == "chat"]
    if not chat_spans:
        raise TokenAccountingInvariantError(
            "invoke_agent span has no chat children; cannot attribute input tokens"
        )

    if context_mode == "cumulative":
        if truncations != 0:
            raise TokenAccountingInvariantError(
                f"context_mode=cumulative but truncations={truncations}; "
                "last-span heuristic would undercount discarded prefix"
            )
        return chat_spans[-1].input_tokens

    if context_mode == "reconstructed":
        total = chat_spans[0].input_tokens
        for prev, cur in zip(chat_spans, chat_spans[1:]):
            delta = cur.input_tokens - prev.input_tokens - prev.output_tokens
            if delta < 0:
                # Truncation or summarization collapsed the context.
                # Clamp to the span's own input and require an annotation.
                if truncations == 0:
                    raise TokenAccountingInvariantError(
                        "negative delta observed but truncations=0; "
                        "context mode mislabeled"
                    )
                delta = cur.input_tokens
            total += delta
        return total

    if context_mode == "parallel_fanout":
        raise TokenAccountingInvariantError(
            "parallel fan-out cannot be reduced to a single scalar; "
            "emit per-branch subtotals"
        )

    raise TokenAccountingInvariantError(f"unknown context_mode={context_mode!r}")
