# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-double-counting-of-llm-token-usage-when-an-agent-retries-a-tool-call-span-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-double-counting-of-llm-token-usage-when-an-agent-retries-a-tool-call-span-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   63dd81625c53728dcaa3616a63916dcccbd45bb9994109efcd5bd2064838548b
# Code AST SHA-256:   77cdbe0c7c785fbc98c13d7e8a5ff6caeafdc54584df1921edf4223c830a5029
# Verified Classes:   RetryUsageAmbiguityError, UsageSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class RetryUsageAmbiguityError(RuntimeError):
    """Raised when usage spans cannot be unambiguously attributed to billed requests."""


@dataclass(frozen=True)
class UsageSpan:
    trace_id: str
    span_id: str
    operation: str            # gen_ai.operation.name
    input_tokens: int         # gen_ai.usage.input_tokens
    output_tokens: int        # gen_ai.usage.output_tokens
    attempt: int | None       # app.retry.attempt, None if unmarked
    reached_provider: bool    # app.retry.reached_provider


def sum_billable_tokens(spans: list[UsageSpan], require_attempt_marker: bool = True) -> int:
    """Sum usage only over spans that correspond to provider-billed requests.

    Invariant: every span with usage attributes must carry an attempt marker
    AND a reached_provider flag, or the sum is ambiguous and we refuse.
    """
    total = 0
    for s in spans:
        if s.operation != "chat":
            continue
        if require_attempt_marker and s.attempt is None:
            raise RetryUsageAmbiguityError(
                f"span {s.span_id} in trace {s.trace_id} has usage attributes "
                f"but no app.retry.attempt marker; cannot distinguish "
                f"provider-billed retry from collector-side double count"
            )
        if not s.reached_provider:
            # Local re-parse or client-side reconstruction: not billed.
            continue
        total += s.input_tokens + s.output_tokens
    return total


def reconcile_against_invoice(spans: list[UsageSpan], invoice_tokens: int, tolerance: float = 0.02) -> None:
    observed = sum_billable_tokens(spans)
    if invoice_tokens == 0:
        raise RetryUsageAmbiguityError("invoice baseline is zero; cannot reconcile")
    drift = abs(observed - invoice_tokens) / invoice_tokens
    if drift > tolerance:
        raise RetryUsageAmbiguityError(
            f"telemetry sum {observed} drifts {drift:.1%} from invoice {invoice_tokens}; "
            f"likely unmarked retry spans or deduplication at collector"
        )
