# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-agent-span-has-silently-double-counted-tokens-across-a-retried-model-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-agent-span-has-silently-double-counted-tokens-across-a-retried-model-invocation.warrant.json
# Markdown SHA-256:   67cbf7f6bf22c49e81c1236ab625c33b6e7c525759e500f323df473f8fd7bbad
# Code AST SHA-256:   1a2802f7178a19bad03bcfd30c036152bed826333fc462b2572aed34f9852823
# Verified Classes:   TokenAccountingInvariantError, InferenceEvent, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a GenAI span's usage attributes cannot be reconciled
    to a single physical model invocation via its event stream."""


@dataclass
class InferenceEvent:
    attempt: int
    input_tokens: int
    output_tokens: int
    cached_input_tokens: int = 0


@dataclass
class GenAISpan:
    name: str
    input_tokens_attr: Optional[int]
    output_tokens_attr: Optional[int]
    events: list[InferenceEvent]
    retry_attempt_attr: Optional[int] = None


def reconcile_span(span: GenAISpan) -> dict:
    """Enforce: attribute usage == usage of exactly one physical attempt.

    The structural signal of silent double-counting is attribute/event
    cardinality mismatch: the scalar attribute sums multiple attempts
    while only one inference.operation.details event was emitted.
    """
    if span.input_tokens_attr is None or span.output_tokens_attr is None:
        raise TokenAccountingInvariantError(
            f"span {span.name!r} missing gen_ai.usage.* attributes; "
            "cannot reconcile against events"
        )

    if not span.events:
        raise TokenAccountingInvariantError(
            f"span {span.name!r} has usage attributes but zero "
            "gen_ai.client.inference.operation.details events; "
            "attribute is an accumulator, not a measurement"
        )

    event_input = sum(e.input_tokens for e in span.events)
    event_output = sum(e.output_tokens for e in span.events)

    if span.input_tokens_attr != event_input or span.output_tokens_attr != event_output:
        raise TokenAccountingInvariantError(
            f"span {span.name!r} attribute/event mismatch: "
            f"attr=({span.input_tokens_attr},{span.output_tokens_attr}) "
            f"events=({event_input},{event_output}) across "
            f"{len(span.events)} attempt(s); silent retry double-count suspected"
        )

    distinct_attempts = {e.attempt for e in span.events}
    if len(distinct_attempts) > 1 and span.retry_attempt_attr is None:
        raise TokenAccountingInvariantError(
            f"span {span.name!r} folded {len(distinct_attempts)} attempts "
            "into one span without retry.attempt attribute; "
            "retry boundary is unrecoverable downstream"
        )

    return {
        "logical_input_tokens": event_input,
        "logical_output_tokens": event_output,
        "physical_attempts": len(distinct_attempts),
        "billable_input_tokens": sum(e.input_tokens for e in span.events),
        "cache_hit_tokens": sum(e.cached_input_tokens for e in span.events),
    }
