# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-opentelemetry-genai-span-attribute-invariants-break-at-the-tool-call-boundary-when-token-accounting-and-agent-invocat.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-opentelemetry-genai-span-attribute-invariants-break-at-the-tool-call-boundary-when-token-accounting-and-agent-invocat.warrant.json
# Markdown SHA-256:   8f4a820ce2a8c4f2b209765bad78a8100b7a45294e4c9ebdf40729a05083919a
# Code AST SHA-256:   804458177776880c2f259101af5ddc107565ee1fe3bd361445f0143b36704def
# Verified Classes:   GenAISpanInvariantError, GenAISpan
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping, Optional


class GenAISpanInvariantError(RuntimeError):
    """Raised when a GenAI span violates per-operation semantic invariants."""
    pass


@dataclass(frozen=True)
class GenAISpan:
    operation_name: str
    attributes: Mapping[str, object]
    parent_span_id: Optional[str] = None
    span_id: str = ""


_TOKEN_ATTRS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
_TOOL_ATTRS = ("gen_ai.tool.name", "gen_ai.tool.call.id")
_AGENT_ATTRS = ("gen_ai.agent.name",)


def validate_genai_span(span: GenAISpan) -> None:
    op = span.operation_name
    attrs = span.attributes

    if op == "chat":
        # Chat spans own token accounting; tool attrs are optional.
        if not any(a in attrs for a in _TOKEN_ATTRS):
            # Allowed only for cached/empty responses; require explicit marker.
            if attrs.get("gen_ai.response.cached") is not True:
                raise GenAISpanInvariantError(
                    f"chat span {span.span_id} missing token usage and no cache marker"
                )
        return

    if op == "execute_tool":
        for a in _TOOL_ATTRS:
            if a not in attrs:
                raise GenAISpanInvariantError(
                    f"execute_tool span {span.span_id} missing required {a}"
                )
        for a in _TOKEN_ATTRS:
            if a in attrs:
                raise GenAISpanInvariantError(
                    f"execute_tool span {span.span_id} must not carry {a}; "
                    "tokens belong to the parent chat span"
                )
        if span.parent_span_id is None:
            raise GenAISpanInvariantError(
                f"execute_tool span {span.span_id} orphaned: no parent chat span"
            )
        return

    if op == "invoke_agent":
        if not any(a in attrs for a in _AGENT_ATTRS):
            raise GenAISpanInvariantError(
                f"invoke_agent span {span.span_id} missing gen_ai.agent.name"
            )
        for a in _TOKEN_ATTRS:
            if a in attrs:
                raise GenAISpanInvariantError(
                    f"invoke_agent span {span.span_id} must not carry {a}; "
                    "wrapper spans must not duplicate child token usage"
                )
        return

    raise GenAISpanInvariantError(
        f"unknown gen_ai.operation.name={op!r} on span {span.span_id}"
    )


def validate_trace(spans: list[GenAISpan]) -> None:
    chat_call_ids = {
        s.attributes.get("gen_ai.tool.call.id")
        for s in spans
        if s.operation_name == "chat"
    }
    for s in spans:
        validate_genai_span(s)
        if s.operation_name == "execute_tool":
            cid = s.attributes.get("gen_ai.tool.call.id")
            if cid not in chat_call_ids:
                raise GenAISpanInvariantError(
                    f"tool span {s.span_id} call_id={cid!r} has no matching chat span; "
                    "promote the call id to a span attribute on the chat span"
                )
