# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-opentelemetry-genai-token-accounting-has-already-diverged-from-provider-billing-at-the-span-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-opentelemetry-genai-token-accounting-has-already-diverged-from-provider-billing-at-the-span-boundary.warrant.json
# Markdown SHA-256:   35dda290e4a330b376a44490af2f3beef6c78c8a0311bcac62dc2b0378d8d5ab
# Code AST SHA-256:   3f7f6f10ab7315b745a2713a1ba2605006b5a05cfb21904e6f889ba0741aa612
# Verified Classes:   TokenAccountingDivergence, GenAISpan
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass
from typing import Optional


class TokenAccountingDivergence(RuntimeError):
    """Raised when a GenAI chat span's usage attributes fail the trace-layer identity check."""
    pass


@dataclass
class GenAISpan:
    operation_name: str
    status_code: str
    model: str
    input_tokens: Optional[int]
    output_tokens: Optional[int]
    prompt_event_text: str
    preceding_tool_outputs: str
    has_retry_event: bool
    retry_attempt_sibling: bool
    tokenizer_count_input: int
    tokenizer_count_output: int


TOKENIZER_TOLERANCE = 0.03


def validate_span_accounting(span: GenAISpan) -> None:
    if span.operation_name not in ("chat", "text_completion"):
        return

    if span.status_code == "ERROR":
        raise TokenAccountingDivergence(
            f"span status=ERROR; usage may be partial or absent, route to ledger reconciliation"
        )

    if span.has_retry_event or span.retry_attempt_sibling:
        raise TokenAccountingDivergence(
            "retry-shadowed span: billing identity is not singular; "
            "provider may bill attempted prompts the trace does not capture"
        )

    if span.input_tokens is None or span.output_tokens is None:
        raise TokenAccountingDivergence(
            "usage attributes absent (typically streamed-output abort before terminal chunk); "
            "absent must not be summed as zero"
        )

    expected_input = span.tokenizer_count_input
    if expected_input == 0:
        raise TokenAccountingDivergence(
            "no prompt content tokenized; cannot validate input_tokens arithmetic"
        )

    drift = abs(span.input_tokens - expected_input) / expected_input
    if drift > TOKENIZER_TOLERANCE:
        raise TokenAccountingDivergence(
            f"input_tokens={span.input_tokens} vs tokenizer={expected_input} "
            f"drift={drift:.1%} exceeds {TOKENIZER_TOLERANCE:.0%}; "
            "instrumentor likely estimating rather than reporting provider usage"
        )

    expected_output = span.tokenizer_count_output
    if expected_output > 0:
        out_drift = abs(span.output_tokens - expected_output) / expected_output
        if out_drift > TOKENIZER_TOLERANCE:
            raise TokenAccountingDivergence(
                f"output_tokens={span.output_tokens} vs tokenizer={expected_output} "
                f"drift={out_drift:.1%}; possible stream truncation with stale terminal usage"
            )
