# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-gen-ai-usage-input-tokens-value-when-a-tool-call-span-is-nested-inside-a-reasoning-span.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-gen-ai-usage-input-tokens-value-when-a-tool-call-span-is-nested-inside-a-reasoning-span.warrant.json
# Markdown SHA-256:   201bcdd52a83cab7e0fe07e4a450edf2b9ed9396896f9095e63457c4eabcd786
# Code AST SHA-256:   ea3ad9161279aedd5f4d1c9a14fa9af57bec5925cd9741843097d9cec969851a
# Verified Classes:   UsageAttributionError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

INFERENCE_OPS = frozenset({"chat", "text_completion", "embeddings"})
TOOL_OPS = frozenset({"execute_tool"})


class UsageAttributionError(RuntimeError):
    """Raised when usage attributes would be emitted on a span that did not perform an inference."""


@dataclass
class Span:
    name: str
    operation: str
    parent: Optional["Span"] = None
    children: list["Span"] = None
    attributes: dict = None

    def __post_init__(self):
        self.children = self.children or []
        self.attributes = self.attributes or {}


def should_emit_usage(span: Span) -> bool:
    if span.operation in INFERENCE_OPS:
        return True
    # A tool span may legitimately parent an inference span; usage belongs to the child,
    # never to the tool span itself. So even with an inference child, the tool refuses.
    return False


def assign_usage(span: Span, input_tokens: int, output_tokens: int) -> None:
    if not should_emit_usage(span):
        raise UsageAttributionError(
            f"refusing to emit gen_ai.usage on span {span.name!r} "
            f"(operation={span.operation!r}); usage belongs to the inference span that "
            f"represents the model invocation, not to a tool-call span"
        )
    span.attributes["gen_ai.usage.input_tokens"] = input_tokens
    span.attributes["gen_ai.usage.output_tokens"] = output_tokens


def on_start(span: Span, inherited_usage: Optional[dict]) -> None:
    # Guard against the classic inheritance bug: a span processor copying parent usage down.
    if inherited_usage and not should_emit_usage(span):
        raise UsageAttributionError(
            f"span {span.name!r} received inherited gen_ai.usage={inherited_usage!r} "
            f"but is not an inference span; inheritance of usage attributes is forbidden"
        )
    if inherited_usage:
        span.attributes.update(inherited_usage)
