# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-token-accounting-attributes-as-non-additive-across-a-resumed-agent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-opentelemetry-genai-token-accounting-attributes-as-non-additive-across-a-resumed-agent-span.warrant.json
# Markdown SHA-256:   76233b6a31d5d9f0909eb47dafefa1ad77c8da00610100e600ff3516266ca102
# Code AST SHA-256:   8fb434995e45c8b6883e9fcdba7981a9509c3aacbac699bfe476fa43bfcaf469
# Verified Classes:   GenAISpan, NonAdditiveTokenAccountingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import dataclasses
from typing import Iterable

@dataclasses.dataclass
class GenAISpan:
    span_id: str
    conversation_id: str
    checkpoint_id: str | None
    input_tokens: int
    output_tokens: int
    is_resume: bool

class NonAdditiveTokenAccountingError(RuntimeError):
    pass

def sum_billed_input_tokens(spans: Iterable[GenAISpan]) -> int:
    """Sum input tokens across GenAI spans, deduplicating replayed prefixes.

    Raises NonAdditiveTokenAccountingError if a resume span lacks a
    checkpoint_id, because without it the replayed prefix cannot be
    identified and the sum would silently overcount.
    """
    by_conversation: dict[str, list[GenAISpan]] = {}
    for s in spans:
        by_conversation.setdefault(s.conversation_id, []).append(s)

    total = 0
    for conv_id, conv_spans in by_conversation.items():
        committed_prefix = 0
        for s in conv_spans:
            if s.is_resume:
                if s.checkpoint_id is None:
                    raise NonAdditiveTokenAccountingError(
                        f"resume span {s.span_id} in conversation {conv_id} "
                        f"has no checkpoint_id; replayed prefix is "
                        f"unidentifiable and summation would overcount "
                        f"input_tokens by the committed prefix total"
                    )
                # Resumed span re-sends the committed prefix; count only the delta.
                delta = s.input_tokens - committed_prefix
                if delta < 0:
                    raise NonAdditiveTokenAccountingError(
                        f"resume span {s.span_id} reports "
                        f"{s.input_tokens} input tokens, less than the "
                        f"committed prefix {committed_prefix}; accounting "
                        f"is inconsistent and cannot be bounded"
                    )
                total += delta
                committed_prefix = s.input_tokens
            else:
                total += s.input_tokens
                committed_prefix = s.input_tokens
    return total
