# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-an-opentelemetry-genai-span-whose-token-counts-disagree-with-its-own-completion-accounting.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-an-opentelemetry-genai-span-whose-token-counts-disagree-with-its-own-completion-accounting.warrant.json
# Markdown SHA-256:   77620db8ae65ee586f9b474c7aed079a71ebb11986952e6abc580dcf22a80bee
# Code AST SHA-256:   b9fe90afc4ec98a6ce2f6b5c1fd0153b69e7ba74ac61550d8617635afcf53d05
# Verified Classes:   SpanAuthorityViolation, GenAISpan, LedgerEntry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanAuthorityViolation(RuntimeError):
    """Raised when a GenAI span is used as control-plane authority but fails the enclosure invariant."""


@dataclass
class GenAISpan:
    span_id: str
    conversation_id: str
    input_tokens: int
    output_tokens: int
    closed_before_terminal: bool
    provider_strips_reasoning: bool
    authority: str  # "descriptive" | "authoritative"


@dataclass
class LedgerEntry:
    conversation_id: str
    span_ids: set[str]
    input_tokens: int
    output_tokens: int


NORMALIZATION_ENVELOPE = 0.03  # 3% documented provider normalization ceiling


def assert_span_is_authoritative(span: GenAISpan, ledger: LedgerEntry) -> None:
    if span.authority != "authoritative":
        raise SpanAuthorityViolation(
            f"span {span.span_id} is tagged descriptive; cannot gate budget on it"
        )
    if span.closed_before_terminal:
        raise SpanAuthorityViolation(
            f"span {span.span_id} closed before terminal generation event; "
            "token attributes cannot enclose all consuming events"
        )
    if span.span_id not in ledger.span_ids:
        raise SpanAuthorityViolation(
            f"span {span.span_id} absent from ledger for conversation "
            f"{span.conversation_id}; dedup keys diverge (retry span likely dropped)"
        )
    if span.provider_strips_reasoning:
        raise SpanAuthorityViolation(
            f"span {span.span_id} originates from a provider that normalizes "
            "reasoning tokens out of usage; attribute is tokenizer-divergent"
        )
    span_total = span.input_tokens + span.output_tokens
    ledger_total = ledger.input_tokens + ledger.output_tokens
    if ledger_total == 0:
        return
    delta = abs(span_total - ledger_total) / ledger_total
    if delta > NORMALIZATION_ENVELOPE:
        raise SpanAuthorityViolation(
            f"span {span.span_id} diverges from ledger by {delta:.2%}, "
            f"exceeding normalization envelope {NORMALIZATION_ENVELOPE:.2%}; "
            "fall back to internal ledger, do not average"
        )


def budget_gate(span: GenAISpan, ledger: LedgerEntry, remaining_budget: int) -> int:
    try:
        assert_span_is_authoritative(span, ledger)
        charge = span.input_tokens + span.output_tokens
    except SpanAuthorityViolation:
        charge = ledger.input_tokens + ledger.output_tokens
    if charge > remaining_budget:
        raise SpanAuthorityViolation(
            f"budget exhausted: charge {charge} > remaining {remaining_budget}"
        )
    return remaining_budget - charge
