# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-silent-token-accounting-gaps-when-genai-spans-are-closed-after-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-silent-token-accounting-gaps-when-genai-spans-are-closed-after-context-compaction.warrant.json
# Markdown SHA-256:   6b4a964fcb30e832b4badc07a60761517326c66cd11b61cc96aebee83da79480
# Code AST SHA-256:   6ba7508f1f246e16d3f38f8bd15394d2e09588cbc128c6edd8e1e9441c479227
# Verified Classes:   UsageInvariantViolation, UsageSnapshot, GenAISpan
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageInvariantViolation(RuntimeError):
    """Raised when a GenAI span's usage attributes violate the bracketing invariant."""
    pass


@dataclass(frozen=True)
class UsageSnapshot:
    input_tokens: int
    output_tokens: int
    model: str
    source: str  # "provider" | "tokenizer"


@dataclass
class GenAISpan:
    name: str
    model: str
    max_tokens: Optional[int] = None
    _usage: Optional[UsageSnapshot] = None
    _child_input_tokens: int = 0
    _ended: bool = False

    def record_usage(self, snapshot: UsageSnapshot) -> None:
        if self._ended:
            raise UsageInvariantViolation(
                f"span {self.name!r}: usage recorded after end()"
            )
        if self._usage is not None:
            raise UsageInvariantViolation(
                f"span {self.name!r}: usage already snapshotted "
                f"({self._usage.input_tokens} in); refusing to overwrite with "
                f"{snapshot.input_tokens} in. A second model call inside one span "
                f"must open its own span."
            )
        if snapshot.source != "provider":
            raise UsageInvariantViolation(
                f"span {self.name!r}: usage source={snapshot.source!r}; "
                f"tokenizer estimates cannot be mixed with authoritative counts"
            )
        self._usage = snapshot

    def add_child_usage(self, child: "GenAISpan") -> None:
        if child._usage is None:
            raise UsageInvariantViolation(
                f"child span {child.name!r} closed without usage snapshot"
            )
        self._child_input_tokens += child._usage.input_tokens

    def end(self) -> None:
        if self._usage is None:
            raise UsageInvariantViolation(
                f"span {self.name!r}: ended with no usage snapshot; "
                f"a model call must record provider usage before close"
            )
        if self.max_tokens is not None and self._usage.input_tokens > self.max_tokens:
            raise UsageInvariantViolation(
                f"span {self.name!r}: input_tokens={self._usage.input_tokens} "
                f"exceeds max_tokens={self.max_tokens}; usage does not describe "
                f"the payload this span claims to bracket"
            )
        if self._child_input_tokens > self._usage.input_tokens:
            raise UsageInvariantViolation(
                f"span {self.name!r}: child input sum={self._child_input_tokens} "
                f"exceeds parent input={self._usage.input_tokens}; "
                f"tokens were double-counted across spans"
            )
        self._ended = True
