# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-usage-attributes-before-span-export-or-the-recorded-cost-of-an-agent-turn-silently-diverges.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-usage-attributes-before-span-export-or-the-recorded-cost-of-an-agent-turn-silently-diverges.warrant.json
# Markdown SHA-256:   29cd8abe2537b83f493100826834a2f7b0bcc50f17a770a736f868273626abc7
# Code AST SHA-256:   3ae8e76a404a5c80372bb3de4d9383f76b1750521e7cf26f7ed80a6c1590dba7
# Verified Classes:   TokenAccountingDivergence, SpanUsage
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable, Optional


class TokenAccountingDivergence(RuntimeError):
    """Raised when span-derived token usage diverges from provider-reported
    usage beyond tolerance, or when a usage-bearing span is missing attributes
    that the aggregation class requires. Gates irreversible actions."""

    pass


@dataclass(frozen=True)
class SpanUsage:
    span_name: str
    status_ok: bool
    input_tokens: Optional[int]
    output_tokens: Optional[int]
    estimated: bool = False


def reconcile_turn_usage(
    spans: Iterable[SpanUsage],
    provider_input: int,
    provider_output: int,
    aggregation_class: str = "gen_ai.chat",
    tolerance: float = 0.02,
) -> int:
    """Return the reconciled total token count for a turn, or raise.

    Invariant: for every billable request there is exactly one span in the
    aggregation class carrying usage; no span carries usage for >1 request.
    """
    total = 0
    missing = []
    for s in spans:
        if s.span_name != aggregation_class:
            continue
        if s.input_tokens is None or s.output_tokens is None:
            # A non-OK span with no usage is the retry-collapse / abort case.
            missing.append(s)
            continue
        total += s.input_tokens + s.output_tokens

    # Missing usage on a failed/aborted span means the sum under-counts.
    if missing:
        raise TokenAccountingDivergence(
            f"{len(missing)} span(s) in class {aggregation_class!r} lack usage "
            f"attributes (retry collapse or aborted stream); span sum is a "
            f"lower bound and cannot gate irreversible actions: "
            f"{[m.span_name for m in missing]}"
        )

    provider_total = provider_input + provider_output
    if provider_total == 0:
        return total
    gap = abs(total - provider_total) / provider_total
    if gap > tolerance:
        raise TokenAccountingDivergence(
            f"span sum {total} diverges from provider-reported {provider_total} "
            f"by {gap:.1%} (tolerance {tolerance:.1%}); possible double-count "
            f"from tool-call wrapper spans or dropped usage-bearing spans under "
            f"sampling"
        )
    return total
