# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-otel-genai-span-tree-divergence-from-token-accounting-under-retry-and-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-otel-genai-span-tree-divergence-from-token-accounting-under-retry-and-compaction.warrant.json
# Markdown SHA-256:   b6f2d91ab0f4e32b029f9874da5b16a7a93ea340544309fbd190f4d6f269c83c
# Code AST SHA-256:   270fff1b22a11f815a8a7b59a3ad5d0d7945bf99c5de86f19bd497b7551791c0
# Verified Classes:   GenAISpanTreeInconsistent, ChatSpan, ToolSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class GenAISpanTreeInconsistent(RuntimeError):
    """Raised when an OTel GenAI span tree is structurally valid but ledger-inconsistent."""


@dataclass(frozen=True)
class ChatSpan:
    span_id: str
    response_id: str
    input_tokens: int | None
    output_tokens: int | None
    is_retry_of: str | None = None
    is_compaction: bool = False
    tool_call_ids_in_output: tuple[str, ...] = ()


@dataclass(frozen=True)
class ToolSpan:
    span_id: str
    tool_call_id: str
    parent_chat_span_id: str


def validate_span_tree(chat_spans: Iterable[ChatSpan], tool_spans: Iterable[ToolSpan]) -> None:
    chats = list(chat_spans)
    tools = list(tool_spans)

    # 1. Usage presence on every billed chat span (compaction included).
    for c in chats:
        if c.input_tokens is None or c.output_tokens is None:
            raise GenAISpanTreeInconsistent(
                f"chat span {c.span_id} (response_id={c.response_id}, compaction={c.is_compaction}) "
                f"is missing gen_ai.usage.* attributes; ledger would silently deflate."
            )

    # 2. response_id uniqueness except for explicit retry links.
    seen: dict[str, str] = {}
    for c in chats:
        if c.response_id in seen and c.is_retry_of != seen[c.response_id]:
            raise GenAISpanTreeInconsistent(
                f"duplicate gen_ai.response.id={c.response_id} across spans "
                f"{seen[c.response_id]} and {c.span_id} without an explicit retry link; "
                f"token aggregation would double-count."
            )
        seen.setdefault(c.response_id, c.span_id)

    # 3. Tool-call reachability: every tool span's call id must be present in exactly
    #    one ancestor chat span's recorded output.
    chat_by_span = {c.span_id: c for c in chats}
    for t in tools:
        parent = chat_by_span.get(t.parent_chat_span_id)
        if parent is None:
            raise GenAISpanTreeInconsistent(
                f"tool span {t.span_id} references unknown parent chat span {t.parent_chat_span_id}."
            )
        if t.tool_call_id not in parent.tool_call_ids_in_output:
            raise GenAISpanTreeInconsistent(
                f"orphan tool span {t.span_id}: tool_call_id={t.tool_call_id} not present in "
                f"parent chat span {parent.span_id}'s output; likely history rewrite / compaction."
            )


def aggregate_tokens(chat_spans: Iterable[ChatSpan], tool_spans: Iterable[ToolSpan]) -> int:
    chats = list(chat_spans)
    tools = list(tool_spans)
    validate_span_tree(chats, tools)  # structural gate before any summation
    return sum((c.input_tokens or 0) + (c.output_tokens or 0) for c in chats)
