# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-undercount-prompt-tokens-when-an-otel-gen-ai-span-is-reopened-after-mid-stream-tool-call-interruption.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-undercount-prompt-tokens-when-an-otel-gen-ai-span-is-reopened-after-mid-stream-tool-call-interruption.warrant.json
# Markdown SHA-256:   768786bd0056dd672e0e0be4cb76cd69521f5d4e15e45f6f6e945970411432d8
# Code AST SHA-256:   eece00337a4b3dc039bb8b09d1fa1c43d6a0aba98ef6f20e90f86ca183ab34b6
# Verified Classes:   GenAIUsageInvariantError, GenAISpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class GenAIUsageInvariantError(RuntimeError):
    """Raised when span-level usage accounting cannot reconcile to billing."""


@dataclass(frozen=True)
class GenAISpan:
    conversation_id: str
    request_model: str
    response_id: str | None
    input_tokens: int | None
    status_code: str  # "OK" | "ERROR"
    is_resumed: bool


def reconcile_input_tokens(spans: Iterable[GenAISpan]) -> int:
    """
    Sum gen_ai.usage.input_tokens across a conversation, collapsing only
    spans that share a gen_ai.response.id (same completion, prefix re-reported).

    Invariant: retries after transport failure carry a NEW response_id and
    MUST be counted, even if input_tokens is byte-identical to a prior span.
    ERROR spans with no response_id are billable and MUST be counted.
    """
    seen_response_ids: set[str] = set()
    total = 0
    for span in spans:
        if span.input_tokens is None:
            continue
        if span.response_id is not None:
            if span.response_id in seen_response_ids:
                # Same completion observed twice -> collapse prefix re-report.
                continue
            seen_response_ids.add(span.response_id)
            total += span.input_tokens
            continue
        # No response_id: completion never materialized (ERROR/timeout) or
        # provider omitted it. Billable; do not dedup on token equality.
        if span.status_code == "ERROR" and span.input_tokens == 0:
            raise GenAIUsageInvariantError(
                f"ERROR span in conversation {span.conversation_id} "
                f"reports input_tokens=0; provider billed prompt but harness "
                f"recorded nothing — usage attribute was dropped before span end."
            )
        total += span.input_tokens
    return total
