# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-double-counts-cached-prompt-tokens-across-a-retried-tool-call-span.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-double-counts-cached-prompt-tokens-across-a-retried-tool-call-span.warrant.json
# Markdown SHA-256:   6fd30680b1a1235d606e4fd2076c9596a277abcf57fe46bf8a4a1161cd1a9cb7
# Code AST SHA-256:   36517b71f09662b57acaa89315e547dfce7fa5d6759d7e7e56f16391f865a006
# Verified Classes:   TokenConservationError, TokenSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenConservationError(RuntimeError):
    """Raised when span-level token attribution would violate the
    conservation invariant sum(attributed) == provider_billed."""
    pass


@dataclass(frozen=True)
class TokenSpan:
    request_id: str | None
    agent_id: str
    input_tokens: int
    cache_read_input_tokens: int
    is_attempt_span: bool


def attribute_window(spans: list[TokenSpan], provider_billed_tokens: int,
                     epsilon: float = 1e-3) -> dict[str, int]:
    """Attribute tokens per agent, deduplicating by request_id and
    asserting conservation against the provider ledger."""
    seen: set[str] = set()
    attributed: dict[str, int] = {}

    for span in spans:
        if span.request_id is None:
            # Never fall back to summing a span with no request identity;
            # that is exactly the duplication vector.
            raise TokenConservationError(
                f"span for agent {span.agent_id!r} lacks request_id; "
                "refusing to attribute by span-sum"
            )
        if span.request_id in seen:
            # Duplicate emission (SDK + gateway, or retry re-emission).
            # Billable tokens for this request were already counted.
            continue
        seen.add(span.request_id)
        billable = span.input_tokens + span.cache_read_input_tokens
        attributed[span.agent_id] = attributed.get(span.agent_id, 0) + billable

    total = sum(attributed.values())
    residual = abs(total - provider_billed_tokens) / max(provider_billed_tokens, 1)
    if residual > epsilon:
        raise TokenConservationError(
            f"conservation residual {residual:.4%} exceeds {epsilon:.4%}: "
            f"attributed={total} billed={provider_billed_tokens} "
            f"(likely cached-prefix duplication across retries)"
        )
    return attributed
