# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-the-opentelemetry-genai-agent-span-silently-lose-tool-call-attributes-and-token-cost-metrics-when-a-sub-agent-executes-a-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-the-opentelemetry-genai-agent-span-silently-lose-tool-call-attributes-and-token-cost-metrics-when-a-sub-agent-executes-a-tool.warrant.json
# Markdown SHA-256:   0300bd6542296f407e77fca7e8fe6c4a5ee97fa85f9c1cfaf2b0b08ed02d804c
# Code AST SHA-256:   6d3a72d44f18e95977aca81a0b583fe84241f0f2c5d14a1aff1722848195d86b
# Verified Classes:   GenAIUsageAttributionError, SpanRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class GenAIUsageAttributionError(RuntimeError):
    """Raised when a trace violates the single-usage-span invariant for a tool call."""


@dataclass(frozen=True)
class SpanRecord:
    trace_id: str
    span_id: str
    operation_name: str | None          # gen_ai.operation.name
    tool_call_id: str | None            # gen_ai.tool.call.id
    input_tokens: int                   # gen_ai.usage.input_tokens
    output_tokens: int                  # gen_ai.usage.output_tokens


_USAGE_OWNER_OPS = frozenset({"chat", "inference"})


def enforce_single_usage_span(spans: list[SpanRecord]) -> None:
    """
    For every (trace_id, tool_call_id), assert exactly one span carries usage
    and that span's operation is a chat/inference span, never execute_tool.
    """
    by_call: dict[tuple[str, str], list[SpanRecord]] = {}
    for s in spans:
        if s.tool_call_id is None:
            continue
        if s.input_tokens or s.output_tokens:
            by_call.setdefault((s.trace_id, s.tool_call_id), []).append(s)

    for (trace_id, call_id), owners in by_call.items():
        if len(owners) > 1:
            raise GenAIUsageAttributionError(
                f"trace {trace_id} call {call_id}: {len(owners)} spans carry "
                f"gen_ai.usage.* ({[o.span_id for o in owners]}); "
                "context propagation across the tool boundary is likely broken "
                "and cost will be double-counted."
            )
        owner = owners[0]
        if owner.operation_name not in _USAGE_OWNER_OPS:
            raise GenAIUsageAttributionError(
                f"trace {trace_id} call {call_id}: usage carried by span "
                f"{owner.span_id} with operation {owner.operation_name!r}; "
                "usage must live on a chat/inference span, not on the "
                "agent/tool span that merely declared the call."
            )
