# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-semantic-convention-metric-instrument-silently-lose-token-cost-attribution-when-the-tokenizer-boundary-is-renegotiated-mid-stre.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-semantic-convention-metric-instrument-silently-lose-token-cost-attribution-when-the-tokenizer-boundary-is-renegotiated-mid-stre.warrant.json
# Markdown SHA-256:   392c39857d05742ad47567b4680f09261ddfcb34f36b617ed29abce132b3abf5
# Code AST SHA-256:   d73380789a312fb325b23faabdfd6a1fe15bebde4baa4fe55037458914e45f34
# Verified Classes:   TokenizerUnitDriftError, TokenUsageInstrument
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TokenizerUnitDriftError(RuntimeError):
    """Raised when a token-usage emission would be added to a series whose
    unit (tokenizer identity) differs from the emission's tokenizer."""
    pass


# Immutable identity of a tokenizer regime. Two emissions are only
# commensurable if these fields match exactly.
TOKENIZER_IDENTITY_FIELDS = (
    "name",
    "version",
    "vocab_size",
    "merge_table_hash",
    "byte_fallback",
    "normalization",
)


def tokenizer_identity(tokenizer) -> tuple:
    return tuple(getattr(tokenizer, f) for f in TOKENIZER_IDENTITY_FIELDS)


class TokenUsageInstrument:
    """A GenAI token-usage counter that refuses to blend tokenizer regimes.

    Invariant: every emission added to this instrument's series must share the
    same tokenizer identity as the series' founding emission. A unit-changing
    tokenizer swap must fork the series (new instrument) rather than continue
    accumulating into the old one.
    """

    def __init__(self, instrument_name: str, base_attributes: dict, tokenizer):
        self.name = instrument_name
        self.attributes = dict(base_attributes)
        self._series_identity = tokenizer_identity(tokenizer)
        self._accumulated = 0
        self._sealed = False

    def add(self, usage_tokens: int, emission_tokenizer) -> None:
        if self._sealed:
            raise TokenizerUnitDriftError(
                f"instrument {self.name!r} is sealed at a tokenizer boundary; "
                "emissions must target a forked instrument"
            )

        incoming = tokenizer_identity(emission_tokenizer)
        if incoming != self._series_identity:
            # The unit changed mid-series. Do NOT sum incommensurable tokens.
            raise TokenizerUnitDriftError(
                f"tokenizer unit drift on instrument {self.name!r}: "
                f"series founded under {self._series_identity!r}, "
                f"emission carries {incoming!r}. "
                "Fork the instrument or add gen_ai.tokenizer.* attributes "
                "to the series key before emitting."
            )

        if usage_tokens < 0:
            raise TokenizerUnitDriftError(
                f"negative token usage {usage_tokens} on {self.name!r}"
            )

        self._accumulated += usage_tokens

    def seal_at_boundary(self) -> int:
        """Called immediately before a tokenizer swap. Freezes the series so
        no post-swap emission can be blended into the pre-swap unit."""
        self._sealed = True
        return self._accumulated

    def fork(self, new_tokenizer, new_attributes: dict) -> "TokenUsageInstrument":
        """Create a fresh instrument for the post-swap tokenizer regime."""
        merged = dict(self.attributes)
        merged.update(new_attributes)
        return TokenUsageInstrument(self.name, merged, new_tokenizer)
