# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-double-counted-tool-call-spans-when-opentelemetry-genai-semantic-conventions-merge-retries-into-a-single-logical-operation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-double-counted-tool-call-spans-when-opentelemetry-genai-semantic-conventions-merge-retries-into-a-single-logical-operation.warrant.json
# Markdown SHA-256:   d49197c84d320ae87d1f6fee79e61c9dfc1bb58ba7c01e65d5c33bf9ae33a1f3
# Code AST SHA-256:   fba64e4a8ae5a2aa25668c3a79272e1a2df26a620c1edbc657c7817ed1ee6a0e
# Verified Classes:   TokenAttributionError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class TokenAttributionError(RuntimeError):
    """Raised when a trace violates the exactly-once token attribution invariant."""


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    operation_name: str
    input_tokens: int
    output_tokens: int
    retry_attempt: int | None = None


def _children(spans: dict[str, Span], parent_id: str) -> list[Span]:
    return [s for s in spans.values() if s.parent_id == parent_id]


def validate_token_attribution(spans: Iterable[Span], tolerance: float = 0.02) -> dict[str, int]:
    """
    Enforce exactly-once attribution: for any parent span carrying usage counters,
    its counters must not coexist with usage-bearing children (double counting),
    and input/output counters must be symmetric on aggregate spans.
    Returns the reconciled per-trace totals using the leaf-only predicate.
    """
    by_id = {s.span_id: s for s in spans}

    for span in by_id.values():
        has_usage = span.input_tokens > 0 or span.output_tokens > 0
        if not has_usage:
            continue

        kids = _children(by_id, span.span_id)
        usage_bearing_kids = [k for k in kids if k.input_tokens > 0 or k.output_tokens > 0]

        if usage_bearing_kids:
            child_sum = sum(k.input_tokens for k in usage_bearing_kids)
            if span.input_tokens >= child_sum * (1 - tolerance):
                raise TokenAttributionError(
                    f"span {span.span_id} ({span.operation_name}) carries "
                    f"input_tokens={span.input_tokens} while its "
                    f"{len(usage_bearing_kids)} usage-bearing children sum to "
                    f"{child_sum}; retries are double-counted under mixed "
                    f"physical/logical instrumentation"
                )

        if span.input_tokens > 0 and span.output_tokens == 0:
            raise TokenAttributionError(
                f"span {span.span_id} ({span.operation_name}) reports "
                f"input_tokens={span.input_tokens} but output_tokens=0; "
                f"asymmetric aggregate span indicates partial logical-reading "
                f"instrumentation and under-reported generation cost"
            )

    # Leaf-only predicate: count usage only on spans with no usage-bearing children.
    totals = {"input_tokens": 0, "output_tokens": 0}
    for span in by_id.values():
        kids = _children(by_id, span.span_id)
        if any(k.input_tokens > 0 or k.output_tokens > 0 for k in kids):
            continue
        totals["input_tokens"] += span.input_tokens
        totals["output_tokens"] += span.output_tokens
    return totals


def reconcile(trace_totals: dict[str, int], provider_billed: dict[str, int], tolerance: float = 0.02) -> None:
    for key in ("input_tokens", "output_tokens"):
        expected = provider_billed.get(key, 0)
        actual = trace_totals.get(key, 0)
        if expected and abs(actual - expected) / expected > tolerance:
            raise TokenAttributionError(
                f"{key} reconciliation failed: trace={actual} provider={expected} "
                f"delta={actual - expected}; quarantine trace usage from budget ledger"
            )
