# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-otel-genai-span-undercount-tokens-when-a-tool-call-loop-re-enters-the-same-span-context-across-a-retry-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-otel-genai-span-undercount-tokens-when-a-tool-call-loop-re-enters-the-same-span-context-across-a-retry-boundary.warrant.json
# Markdown SHA-256:   8a6528b858962841c46622d55709604f349e751966e14e531478606faef114bb
# Code AST SHA-256:   6be033057b857be8f9c287573fb64fccfdb38b6786da8d3d292571045b13b9e6
# Verified Classes:   TokenAccountingInvariantError, SpanTokenState, GenAIUsageAccumulator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a reused GenAI span would overwrite cumulative usage."""


@dataclass
class SpanTokenState:
    input_tokens: int = 0
    output_tokens: int = 0
    writes: int = 0


class GenAIUsageAccumulator:
    """
    Enforces: token usage on a reused span context is additive over billable
    attempts. set_attribute-style overwrite on a span that has already recorded
    usage is a boundary violation and must fail loudly.
    """

    def __init__(self) -> None:
        self._state: Dict[str, SpanTokenState] = {}

    def record_attempt(
        self,
        span_ctx: str,
        input_tokens: int,
        output_tokens: int,
        *,
        overwrite: bool = False,
    ) -> Tuple[int, int]:
        if input_tokens < 0 or output_tokens < 0:
            raise TokenAccountingInvariantError(
                f"negative token count on span {span_ctx!r}: "
                f"in={input_tokens} out={output_tokens}"
            )
        st = self._state.setdefault(span_ctx, SpanTokenState())
        if overwrite and st.writes > 0:
            raise TokenAccountingInvariantError(
                f"span {span_ctx!r} already recorded {st.writes} billable "
                f"attempt(s) (in={st.input_tokens}, out={st.output_tokens}); "
                f"refusing overwrite with in={input_tokens}, out={output_tokens}. "
                f"Emit a child span per attempt or accumulate additively."
            )
        st.input_tokens += input_tokens
        st.output_tokens += output_tokens
        st.writes += 1
        return st.input_tokens, st.output_tokens

    def close(self, span_ctx: str) -> Tuple[int, int]:
        st = self._state.get(span_ctx)
        if st is None:
            raise TokenAccountingInvariantError(
                f"closing span {span_ctx!r} with no recorded usage; "
                f"instrumentation gap or wrong span ownership"
            )
        if st.writes == 0:
            raise TokenAccountingInvariantError(
                f"span {span_ctx!r} closed with zero billable attempts"
            )
        return st.input_tokens, st.output_tokens
