# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-the-tool-call-attribute-cardinality-invariant-and-token-accounting-double-coun.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-close-an-opentelemetry-genai-agent-span-the-tool-call-attribute-cardinality-invariant-and-token-accounting-double-coun.warrant.json
# Markdown SHA-256:   e554e87d105af68edc87f27459898e06a024e1617d9cc614a83ae57d2b7006c7
# Code AST SHA-256:   5796843dea9860e74fb5099ea8d66f9536e4e93af420a9f2739ae9db134f78a8
# Verified Classes:   GenAISpanInvariantError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class GenAISpanInvariantError(RuntimeError):
    """Raised when a span would violate the GenAI token-accounting invariant."""
    pass


@dataclass
class Span:
    operation_name: str
    attributes: dict = field(default_factory=dict)
    tool_call_ids_seen: set = field(default_factory=set)


def close_span(span: Span) -> Span:
    usage_keys = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
    has_usage = any(span.attributes.get(k, 0) for k in usage_keys)

    if span.operation_name == "execute_tool" and has_usage:
        raise GenAISpanInvariantError(
            f"execute_tool span carries usage attributes {span.attributes}; "
            "usage belongs to the originating chat span and re-attaching it "
            "double-counts every tool-call turn in trace aggregation."
        )

    if span.operation_name == "execute_tool":
        call_id = span.attributes.get("gen_ai.tool.call.id")
        if call_id is None:
            raise GenAISpanInvariantError(
                "execute_tool span missing gen_ai.tool.call.id; cannot join "
                "to originating chat span, orphaned tool call."
            )
        if call_id not in span.tool_call_ids_seen:
            raise GenAISpanInvariantError(
                f"execute_tool span call.id={call_id} does not resolve to any "
                "tool_call_id in sibling chat span output; retry or fabricated "
                "call — must not participate in usage aggregation."
            )

    return span


def aggregate_input_tokens(spans: list[Span]) -> int:
    total = 0
    for s in spans:
        if s.operation_name in ("chat", "text_completion", "embeddings"):
            total += s.attributes.get("gen_ai.usage.input_tokens", 0)
    return total
