# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-attribution-from-silently-double-counting-tokens-across-nested-genai-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-attribution-from-silently-double-counting-tokens-across-nested-genai-spans.warrant.json
# Markdown SHA-256:   a878b9ee582347f770616876e27721f2544236a44dff114dfc7fc0441158e673
# Code AST SHA-256:   ef7f668883d203d9a8603191b0976c880d98d22d7bef177396f6236008a8c5d2
# Verified Classes:   UsageAttributionError, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageAttributionError(RuntimeError):
    """Raised when gen_ai.usage.* attributes violate the leaf-only invariant."""


@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    operation_name: Optional[str]  # gen_ai.operation.name, None for coordination spans
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    attempt: int = 0
    children: list = field(default_factory=list)


def validate_usage_attribution(spans: dict[str, GenAISpan]) -> int:
    """Return authoritative input-token total; raise on invariant violation.

    Invariants enforced:
      1. A span with gen_ai.operation.name set must not carry usage if any
         descendant also carries usage (no ancestor/descendant double-count).
      2. Usage on a retried attempt (attempt > 0) must not be summed with
         attempt 0 unless explicitly requested; we reject ambiguous siblings.
      3. Absent usage is None, never 0, so averages exclude unknown spans.
    """
    by_id = {s.span_id: s for s in spans.values()}

    def descendants(span: GenAISpan):
        for child_id in span.children:
            child = by_id[child_id]
            yield child
            yield from descendants(child)

    authoritative = 0
    for span in by_id.values():
        carries_usage = span.input_tokens is not None or span.output_tokens is not None
        if not carries_usage:
            continue

        if span.operation_name is None:
            raise UsageAttributionError(
                f"coordination span {span.span_id} carries gen_ai.usage.*; "
                f"usage must live on the leaf operation span only"
            )

        for desc in descendants(span):
            if desc.input_tokens is not None or desc.output_tokens is not None:
                raise UsageAttributionError(
                    f"span {span.span_id} and descendant {desc.span_id} both carry "
                    f"gen_ai.usage.*; aggregation would double-count tokens"
                )

        if span.attempt > 0:
            raise UsageAttributionError(
                f"retried attempt span {span.span_id} carries usage as a sibling; "
                f"re-parent under the original operation span or filter by attempt"
            )

        authoritative += span.input_tokens or 0

    return authoritative
