# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-parent-child-span-chain-in-opentelemetry-genai-agent-handoffs-and-how-token-attribution-silently-double-coun.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-broken-parent-child-span-chain-in-opentelemetry-genai-agent-handoffs-and-how-token-attribution-silently-double-coun.warrant.json
# Markdown SHA-256:   83385081a7e97ddf5473e6e3cf32c216b647705eb530d52ee0222278f841eabf
# Code AST SHA-256:   268901fcfea2e2063fa0cbf5c0ac3d33ecbb69e0173f3f7a41ffb7b2f2565bd7
# Verified Classes:   UsageAttributionError, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageAttributionError(RuntimeError):
    """Raised when a span's GenAI usage attributes violate the attribution invariant."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: Optional[str]
    name: str
    input_tokens: int = 0
    output_tokens: int = 0
    attribution: Optional[str] = None  # "direct" | "rollup" | None
    response_id: Optional[str] = None  # dedup key for retried inferences


def validate_usage_attribution(spans: list[GenAISpan]) -> dict[str, int]:
    """
    Enforce: every usage-bearing span is tagged 'direct' or 'rollup';
    no span is both; rollup == sum of direct descendants; retried
    inferences (same response_id) counted once.
    Returns authoritative token totals keyed by span_id (direct only).
    """
    by_id = {s.span_id: s for s in spans}
    children: dict[str, list[GenAISpan]] = {}
    for s in spans:
        if s.parent_span_id:
            children.setdefault(s.parent_span_id, []).append(s)

    seen_response_ids: set[str] = set()
    authoritative: dict[str, int] = {}

    for s in spans:
        has_usage = s.input_tokens or s.output_tokens
        if not has_usage:
            continue
        if s.attribution not in ("direct", "rollup"):
            raise UsageAttributionError(
                f"span {s.span_id} ({s.name}) carries gen_ai.usage.* but no "
                f"attribution tag; token accounting is ambiguous at the "
                f"delegation boundary"
            )

        if s.attribution == "rollup":
            direct_desc = _collect_direct_descendants(s, children)
            expected = sum(d.input_tokens + d.output_tokens for d in direct_desc)
            actual = s.input_tokens + s.output_tokens
            if actual != expected:
                raise UsageAttributionError(
                    f"rollup span {s.span_id} ({s.name}) reports {actual} tokens "
                    f"but direct descendants sum to {expected}; likely partial "
                    f"child read or overwrite-not-add on retry"
                )
        else:  # direct
            if s.response_id:
                if s.response_id in seen_response_ids:
                    continue  # retried inference; count once
                seen_response_ids.add(s.response_id)
            authoritative[s.span_id] = s.input_tokens + s.output_tokens

    return authoritative


def _collect_direct_descendants(
    root: GenAISpan, children: dict[str, list[GenAISpan]]
) -> list[GenAISpan]:
    out: list[GenAISpan] = []
    stack = list(children.get(root.span_id, []))
    while stack:
        node = stack.pop()
        if node.attribution == "direct":
            out.append(node)
        stack.extend(children.get(node.span_id, []))
    return out
