# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-tool-call-spans-with-gen-ai-usage-input-tokens-counted-at-the-wrong-layer.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-tool-call-spans-with-gen-ai-usage-input-tokens-counted-at-the-wrong-layer.warrant.json
# Markdown SHA-256:   1a560277fc0df030198cfbff174d5b943b4729d77e93d68b2e9f7691c6c6ac69
# Code AST SHA-256:   9c086311d1401d1a67060865fc36cc3b55d55040a480e72cc7c68b0bc1d67501
# Verified Classes:   GenAIUsagePlacementError, SpanRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class GenAIUsagePlacementError(RuntimeError):
    """Raised when gen_ai.usage.* attributes are attached to a non-inference span
    or when summed chat-span input tokens fail to reconcile with provider billing."""
    pass


@dataclass(frozen=True)
class SpanRecord:
    name: str
    parent_id: str | None
    attributes: dict


USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
INFERENCE_SPAN_NAMES = ("gen_ai.chat", "gen_ai.inference")


def validate_usage_placement(
    spans: Iterable[SpanRecord],
    provider_prompt_tokens: int,
    tolerance_ratio: float = 0.02,
) -> None:
    """Enforce that usage attributes live only on inference spans, and that
    chat-span input tokens reconcile with the provider's billing record."""
    spans = list(spans)

    for span in spans:
        carries_usage = any(k in span.attributes for k in USAGE_KEYS)
        is_inference = span.name in INFERENCE_SPAN_NAMES
        if carries_usage and not is_inference:
            raise GenAIUsagePlacementError(
                f"span {span.name!r} (parent={span.parent_id!r}) carries "
                f"gen_ai.usage.* but is not an inference span; usage must be "
                f"attached to the parent gen_ai.chat span only"
            )

    chat_input = sum(
        int(s.attributes.get("gen_ai.usage.input_tokens", 0))
        for s in spans
        if s.name in INFERENCE_SPAN_NAMES
    )
    if provider_prompt_tokens <= 0:
        raise GenAIUsagePlacementError(
            "provider_prompt_tokens must be positive to reconcile; got "
            f"{provider_prompt_tokens}"
        )

    drift = abs(chat_input - provider_prompt_tokens) / provider_prompt_tokens
    if drift > tolerance_ratio:
        raise GenAIUsagePlacementError(
            "chat-span input_tokens do not reconcile with provider billing: "
            f"summed={chat_input}, provider={provider_prompt_tokens}, "
            f"drift={drift:.1%} > tolerance={tolerance_ratio:.1%}"
        )
