# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-double-count-tokens-when-a-tool-call-span-is-retried-under-opentelemetry-genai-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-double-count-tokens-when-a-tool-call-span-is-retried-under-opentelemetry-genai-semantics.warrant.json
# Markdown SHA-256:   fc514bb3b4ce6fd69d27fbb3f709cb7d2392435c16de1ab4e22a0235c5f1c34c
# Code AST SHA-256:   8135d215e9c22cbb5ca9413acb76845c0a24593f321b9d9a7b6ced1293be2f79
# Verified Classes:   ReplayAccountingError, Origin, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ReplayAccountingError(RuntimeError):
    """Raised when a span's usage cannot be safely attributed to an episode total."""


class Origin(Enum):
    FRESH = "fresh"
    REPLAY = "replay"


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    invocation_id: str          # stable across retries/replays of the same logical call
    origin: Origin
    input_tokens: int
    output_tokens: int


def attribute_usage(spans: list[GenAISpan]) -> dict[str, int]:
    """
    Sum usage for an episode, counting each logical invocation exactly once.
    Replay spans are excluded from cost but retained for trace continuity upstream.
    """
    seen: dict[str, GenAISpan] = {}
    total_in = total_out = 0

    for span in spans:
        if span.origin is Origin.REPLAY:
            # Re-observation of an already-counted call: never add to totals.
            if span.invocation_id not in seen:
                raise ReplayAccountingError(
                    f"replay span {span.span_id} references invocation "
                    f"{span.invocation_id!r} with no fresh origin span; "
                    "cannot deduplicate — emitter dropped the original or "
                    "invocation_id is not stable across resume"
                )
            continue

        prior = seen.get(span.invocation_id)
        if prior is not None:
            raise ReplayAccountingError(
                f"duplicate FRESH span for invocation {span.invocation_id!r}: "
                f"{prior.span_id} and {span.span_id}. A retry that re-spends "
                "must mint a new attempt id; a re-emission must be marked REPLAY."
            )

        seen[span.invocation_id] = span
        total_in += span.input_tokens
        total_out += span.output_tokens

    return {"input_tokens": total_in, "output_tokens": total_out}
