# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-hierarchies-from-silently-double-counting-tokens-across-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-hierarchies-from-silently-double-counting-tokens-across-agent-handoffs.warrant.json
# Markdown SHA-256:   bdc69894f661fb50ac1c4242a9e5d05849477d0897ce2992cd9d3d38cbf27bd7
# Code AST SHA-256:   0dce78354bd83fbfcb3c6fff49a65560597f80bb4b0bfa99fd3b10c280a492f3
# Verified Classes:   TokenAggregationViolation, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TokenAggregationViolation(RuntimeError):
    """Raised when a span tree cannot be summed under the partition invariant."""


@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    operation: str                      # "chat", "tool", "agent", ...
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    status: str = "ok"                  # "ok" | "error"
    inherited_tokens: Optional[int] = None
    children: list["GenAISpan"] = field(default_factory=list)

    @property
    def carries_usage(self) -> bool:
        return self.input_tokens is not None or self.output_tokens is not None


def _assert_partition(span: GenAISpan, seen_ids: set[str]) -> None:
    if span.span_id in seen_ids:
        raise TokenAggregationViolation(
            f"duplicate span_id {span.span_id!r}: double instrumentation of one call"
        )
    seen_ids.add(span.span_id)

    usage_children = [c for c in span.children if c.carries_usage]
    if span.carries_usage and usage_children:
        raise TokenAggregationViolation(
            f"span {span.span_id!r} ({span.operation}) carries usage AND has "
            f"usage-bearing descendants {[c.span_id for c in usage_children]}: "
            f"tree is not a partition; strip derived usage or nest correctly"
        )

    # Retry attempt pairs: same parent, same op, one errored -> count terminal only.
    by_parent: dict[Optional[str], list[GenAISpan]] = {}
    for c in span.children:
        if c.operation == "chat" and c.carries_usage:
            by_parent.setdefault(c.parent_id, []).append(c)
    for parent_id, group in by_parent.items():
        if len(group) > 1 and all(g.status == "error" for g in group):
            raise TokenAggregationViolation(
                f"all attempts under parent {parent_id!r} errored but carry usage"
            )

    for c in span.children:
        _assert_partition(c, seen_ids)


def aggregate_tokens(root: GenAISpan) -> tuple[int, int]:
    """Sum leaf usage under the partition invariant; reject non-partitions."""
    _assert_partition(root, set())

    total_in = total_out = 0

    def walk(s: GenAISpan) -> None:
        nonlocal total_in, total_out
        if s.carries_usage:
            # Handoff guard: a receiver must declare inherited context.
            if s.inherited_tokens is None and s.operation == "chat" and s.parent_id:
                parent = _find(root, s.parent_id)
                if parent is not None and parent.carries_usage:
                    raise TokenAggregationViolation(
                        f"handoff span {s.span_id!r} lacks inherited_tokens "
                        f"but parent {parent.span_id!r} carries usage: "
                        f"input would be double-counted"
                    )
            total_in += s.input_tokens or 0
            total_out += s.output_tokens or 0
        for c in s.children:
            walk(c)

    walk(root)
    return total_in, total_out


def _find(root: GenAISpan, span_id: str) -> Optional[GenAISpan]:
    if root.span_id == span_id:
        return root
    for c in root.children:
        hit = _find(c, span_id)
        if hit is not None:
            return hit
    return None
