# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-level-trace-propagation-failure-at-the-agent-span-boundary-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-level-trace-propagation-failure-at-the-agent-span-boundary-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   0db9d44b9eeddeacd6c3c92610d3457e5a13fbcaae0bc999af5e36d3bf982c2b
# Code AST SHA-256:   1d142ebfbad1bbd9567a148406ccd8522eab653780e20e07e3ac6b6082914738
# Verified Classes:   GenAITraceInvariantError, SpanRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class GenAITraceInvariantError(RuntimeError):
    """Raised when a GenAI trace violates the token-propagation invariant."""


@dataclass(frozen=True)
class SpanRecord:
    span_id: str
    parent_id: str | None
    operation_name: str | None
    tool_call_id: str | None
    input_tokens: int
    output_tokens: int


def validate_token_propagation(spans: Iterable[SpanRecord]) -> None:
    spans = list(spans)
    by_id = {s.span_id: s for s in spans}

    # Condition 1: every usage-emitting span must declare an operation name.
    for s in spans:
        if (s.input_tokens or s.output_tokens) and not s.operation_name:
            raise GenAITraceInvariantError(
                f"span {s.span_id} emits gen_ai.usage.* without "
                f"gen_ai.operation.name; token totals are not aggregatable"
            )

    # Condition 2: no span may be both execute_tool and chat.
    for s in spans:
        if s.operation_name not in (None, "execute_tool", "chat",
                                    "text_completion", "embeddings"):
            raise GenAITraceInvariantError(
                f"span {s.span_id} has unknown operation {s.operation_name!r}"
            )

    # Condition 3: distinct tool.call.id for nested model invocations.
    seen_call_ids: dict[str, str] = {}
    for s in spans:
        if s.tool_call_id is None:
            continue
        if s.tool_call_id in seen_call_ids:
            raise GenAITraceInvariantError(
                f"duplicate gen_ai.tool.call.id {s.tool_call_id!r} on spans "
                f"{seen_call_ids[s.tool_call_id]} and {s.span_id}; "
                f"re-entrant model invocation must mint a new call id"
            )
        seen_call_ids[s.tool_call_id] = s.span_id

    # Condition 4: parent aggregate must not be less than any child aggregate
    # for spans that are direct model invocations (leaf-sum consistency).
    for s in spans:
        if s.operation_name != "execute_tool":
            continue
        children = [c for c in spans if c.parent_id == s.span_id]
        child_tokens = sum(c.input_tokens + c.output_tokens for c in children)
        parent_tokens = s.input_tokens + s.output_tokens
        if child_tokens > parent_tokens:
            raise GenAITraceInvariantError(
                f"span {s.span_id} aggregate ({parent_tokens}) is less than "
                f"sum of children ({child_tokens}); token propagation across "
                f"the agent boundary is broken"
            )


def aggregate_agent_tokens(spans: Iterable[SpanRecord], agent_span_id: str) -> int:
    spans = list(spans)
    validate_token_propagation(spans)
    by_id = {s.span_id: s for s in spans}
    if agent_span_id not in by_id:
        raise GenAITraceInvariantError(f"unknown agent span {agent_span_id}")

    # Authoritative total = sum over leaves only, to avoid double counting.
    child_ids = {s.parent_id for s in spans if s.parent_id}
    total = 0
    for s in spans:
        if s.span_id in child_ids:
            continue
        total += s.input_tokens + s.output_tokens
    return total
