# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-for-token-accounting-and-tool-call-tracing.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-opentelemetry-genai-span-attributes-as-non-authoritative-for-token-accounting-and-tool-call-tracing.warrant.json
# Markdown SHA-256:   72d05108d95ed35903da6c43821d16a2906467ca01401f1bc3dc5240a3aa0f99
# Code AST SHA-256:   b53de69cfa2e0fe20cc3677a35c0908592c666acc8f7d901e5048f435787f7f0
# Verified Classes:   SpanAccountingMismatch, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class SpanAccountingMismatch(RuntimeError):
    """Raised when a span-derived token/tool record cannot be reconciled to the consumer's unit."""


@dataclass(frozen=True)
class GenAISpan:
    span_id: str
    emitter: str
    tokenizer: str | None
    counting_scope: str | None          # "raw" | "post_cache" | "reasoning_inclusive" | None
    input_tokens: int
    output_tokens: int
    tool_call_id: str | None


CONSUMER_SCOPE = "raw"
CONSUMER_TOKENIZER = "runtime-own-v3"


def sum_authoritative_tokens(spans: Iterable[GenAISpan]) -> int:
    total = 0
    for s in spans:
        if s.tokenizer != CONSUMER_TOKENIZER or s.counting_scope != CONSUMER_SCOPE:
            raise SpanAccountingMismatch(
                f"span {s.span_id} from emitter={s.emitter} "
                f"tokenizer={s.tokenizer} scope={s.counting_scope} "
                f"cannot be summed into consumer unit "
                f"(tokenizer={CONSUMER_TOKENIZER}, scope={CONSUMER_SCOPE}); "
                f"treat as lower bound, do not gate."
            )
        total += s.input_tokens + s.output_tokens
    return total


def join_tool_call(request: GenAISpan, result: GenAISpan) -> None:
    if request.tool_call_id is None or result.tool_call_id is None:
        raise SpanAccountingMismatch(
            f"missing tool_call_id on request={request.span_id} "
            f"or result={result.span_id}; causality is UNKNOWN, not failed."
        )
    if request.tool_call_id != result.tool_call_id:
        raise SpanAccountingMismatch(
            f"tool_call_id regenerated: request={request.tool_call_id} "
            f"result={result.tool_call_id}; retry forbidden, resolve via executor ledger."
        )
