# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-when-tool-calls-span-multiple-token-accounting-domai.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-when-tool-calls-span-multiple-token-accounting-domai.warrant.json
# Markdown SHA-256:   2d6f08e3dcbc1efc9a64bd502ca0e5888c9f8374dbe38ad717859933b3e17444
# Code AST SHA-256:   1a8f374e8c82d82e863fa69fc0879f3cd6090a4a386f9aafbfbbf7dee1ab162a
# Verified Classes:   NonAggregatableSubtreeError, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class NonAggregatableSubtreeError(RuntimeError):
    """Raised when a GenAI span subtree cannot be safely aggregated for cost."""


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    parent_span_id: str | None
    model: str | None            # gen_ai.request.model, may be None
    system: str | None           # gen_ai.system
    tokenizer: str | None        # gen_ai.tokenizer.name (extension), may be None
    input_tokens: int
    output_tokens: int
    attempt_id: str | None       # transport-propagated retry key, may be None
    status: str = "OK"


def aggregate_cost(
    spans: Iterable[GenAISpan],
    price_table: dict[str, float],
) -> tuple[int, int, float]:
    """
    Aggregate token and cost attributes over a span subtree.

    Returns (input_tokens, output_tokens, cost). Raises if any leaf span is
    not admissible for cost aggregation, rather than emitting a wrong sum.
    """
    seen_attempts: set[tuple[str, str]] = set()
    total_in = 0
    total_out = 0
    total_cost = 0.0

    for span in spans:
        if span.status != "OK":
            # Error spans may still have partial usage; exclude from cost.
            continue

        if span.model is None or span.model not in price_table:
            raise NonAggregatableSubtreeError(
                f"span {span.span_id}: model {span.model!r} not in price table; "
                f"cannot attribute cost (system={span.system!r})"
            )

        if span.tokenizer is None:
            raise NonAggregatableSubtreeError(
                f"span {span.span_id}: missing tokenizer identity; "
                f"token counts from {span.model!r} may not match price-table tokenizer"
            )

        if span.attempt_id is not None:
            key = (span.span_id.rsplit("-", 1)[0], span.attempt_id)
            if key in seen_attempts:
                # Duplicate attempt already counted; skip.
                continue
            seen_attempts.add(key)

        rate = price_table[span.model]
        total_in += span.input_tokens
        total_out += span.output_tokens
        total_cost += (span.input_tokens + span.output_tokens) * rate

    return total_in, total_out, total_cost
