# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-genai-tool-call-span-whose-token-accounting-cannot-be-reconciled-across-the-parent-agent-span-and-the-child-tool-span.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-genai-tool-call-span-whose-token-accounting-cannot-be-reconciled-across-the-parent-agent-span-and-the-child-tool-span.warrant.json
# Markdown SHA-256:   6d35c4f1b25953bb55cad0b49693ed73b3a6195af66c3416bd5ca0eaf1de379d
# Code AST SHA-256:   f3654b627c92b746794cd40c06b8789507121ddc2a321168bcc167c6dd41b169
# Verified Classes:   TokenAccountingReconciliationError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable

MODEL_OPS = {"chat", "invoke_agent", "text_completion"}
TOOL_OPS = {"execute_tool"}
USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")
AGGREGATE_MARKER = "gen_ai.usage.aggregate"


class TokenAccountingReconciliationError(RuntimeError):
    """Raised when a GenAI span's usage attributes cannot be placed in exactly one accounting frame."""


@dataclass
class Span:
    span_id: str
    op: str
    attrs: dict[str, object] = field(default_factory=dict)
    children: list["Span"] = field(default_factory=list)

    def has_usage(self) -> bool:
        return any(k in self.attrs for k in USAGE_KEYS)

    def is_aggregate(self) -> bool:
        return bool(self.attrs.get(AGGREGATE_MARKER, False))


def _walk(root: Span) -> Iterable[Span]:
    yield root
    for child in root.children:
        yield from _walk(child)


def validate_span_usage(root: Span) -> None:
    """Enforce: each model turn's usage appears on exactly one span; tool spans carry no model usage.

    Rejects (a) tool spans carrying gen_ai.usage.*, (b) agent/chat spans whose usage overlaps a
    descendant model-call span without an explicit aggregate marker.
    """
    for span in _walk(root):
        if span.op in TOOL_OPS and span.has_usage():
            raise TokenAccountingReconciliationError(
                f"tool span {span.span_id} carries model usage attributes; "
                f"execute_tool spans must not emit {USAGE_KEYS}"
            )

    for span in _walk(root):
        if span.op not in MODEL_OPS or not span.has_usage():
            continue
        model_descendants = [
            d for d in _walk(span)
            if d is not span and d.op in MODEL_OPS and d.has_usage()
        ]
        if model_descendants and not span.is_aggregate():
            ids = [d.span_id for d in model_descendants]
            raise TokenAccountingReconciliationError(
                f"span {span.span_id} ({span.op}) carries usage overlapping model-call "
                f"descendants {ids} without {AGGREGATE_MARKER}=true; "
                f"summing this tree will double-count tokens"
            )
