# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-token-and-cost-telemetry-loss-across-opentelemetry-genai-agent-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-token-and-cost-telemetry-loss-across-opentelemetry-genai-agent-spans.warrant.json
# Markdown SHA-256:   aa5e0632c8a9a05c5a21e5d4fff5c7051cde33c2be950c406c53644c72a82928
# Code AST SHA-256:   66d564f396eef14fb6d7b138ab7f7dc0af5989c1d3655a05d4f9320624e9a104
# Verified Classes:   GenAIUsagePropagationError, SpanRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAIUsagePropagationError(RuntimeError):
    """Raised when a span reports usage that cannot be reconciled with its descendants."""
    pass


@dataclass
class SpanRecord:
    name: str
    operation: str
    parent_id: Optional[str]
    span_id: str
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    tool_call_id: Optional[str] = None
    referenced_tool_call_id: Optional[str] = None


def validate_usage_invariant(root: SpanRecord, descendants: list[SpanRecord]) -> int:
    """Return authoritative total input tokens; raise if root usage is unreconcilable."""
    usage_bearing = [
        s for s in descendants
        if s.input_tokens is not None or s.output_tokens is not None
    ]
    descendant_input = sum(s.input_tokens or 0 for s in usage_bearing)

    if usage_bearing and root.input_tokens is not None:
        if root.input_tokens < descendant_input:
            raise GenAIUsagePropagationError(
                f"root span {root.span_id} reports {root.input_tokens} input tokens "
                f"but {len(usage_bearing)} descendants account for {descendant_input}; "
                f"root usage was written before children closed (silent under-count)"
            )
        if root.input_tokens > descendant_input:
            raise GenAIUsagePropagationError(
                f"root span {root.span_id} reports {root.input_tokens} input tokens, "
                f"exceeding descendant sum {descendant_input}; uncorrelated usage"
            )
    return descendant_input


def validate_tool_call_joins(descendants: list[SpanRecord]) -> None:
    """Every referenced tool_call_id must resolve to exactly one tool span."""
    tool_ids = {s.tool_call_id for s in descendants if s.operation == "execute_tool"}
    for s in descendants:
        if s.referenced_tool_call_id is not None:
            if s.referenced_tool_call_id not in tool_ids:
                raise GenAIUsagePropagationError(
                    f"chat span {s.span_id} references tool_call_id "
                    f"{s.referenced_tool_call_id!r} with no matching execute_tool span; "
                    f"cost attribution join will silently produce zero rows"
                )
