# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-tool-call-span-s-gen-ai-usage-input-tokens-is-mutated-after-span-end-by-a.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-tool-call-span-s-gen-ai-usage-input-tokens-is-mutated-after-span-end-by-a.warrant.json
# Markdown SHA-256:   0dcc6134a2ca3e5b9798807753e1e74261bc9d40069a811f40e5d1aa84e91c97
# Code AST SHA-256:   381e5e69c4afaa2ccd6533ce68d7ec3a0b8b9ec5c7712b632e8b0c237ee4bb5f
# Verified Classes:   TokenAccountingInvariantError, SpanAttrs
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a GenAI span violates the one-span-one-invocation contract."""
    pass


@dataclass
class SpanAttrs:
    span_id: str
    operation_name: str
    has_input_tokens: bool
    attempt: int
    retry_count: int
    response_id: str | None


def validate_genai_span(attrs: SpanAttrs) -> None:
    # Invariant 1: usage attributes must not coexist with multi-attempt markers.
    if attrs.has_input_tokens and (attrs.attempt > 1 or attrs.retry_count > 0):
        raise TokenAccountingInvariantError(
            f"span {attrs.span_id}: gen_ai.usage.input_tokens present on a "
            f"multi-attempt span (attempt={attrs.attempt}, "
            f"retry.count={attrs.retry_count}); usage would be last-attempt only "
            f"and the sum invariant is broken. Emit one span per attempt or "
            f"suppress gen_ai.usage.* and use an aggregate attribute."
        )


def dedup_key(attrs: SpanAttrs) -> str:
    # Invariant 2: dedup key must be unique per invocation, not per logical op.
    if attrs.response_id is None:
        raise TokenAccountingInvariantError(
            f"span {attrs.span_id}: dedup requires gen_ai.response.id; "
            f"missing key would collapse distinct invocations."
        )
    if attrs.attempt > 1:
        # Retries must not share a dedup key with the original invocation.
        return f"{attrs.response_id}#attempt{attrs.attempt}"
    return attrs.response_id


def export_batch(spans: list[SpanAttrs]) -> dict[str, int]:
    totals: dict[str, int] = {}
    seen: set[str] = set()
    for s in spans:
        validate_genai_span(s)
        k = dedup_key(s)
        if k in seen:
            raise TokenAccountingInvariantError(
                f"duplicate dedup key {k!r} at span {s.span_id}; "
                f"distinct invocations would be collapsed."
            )
        seen.add(k)
        if s.has_input_tokens:
            totals[s.operation_name] = totals.get(s.operation_name, 0) + 1
    return totals
