# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-when-otel-genai-token-accounting-silently-double-counts-retried-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-convention-drift-when-otel-genai-token-accounting-silently-double-counts-retried-tool-calls.warrant.json
# Markdown SHA-256:   71ccb27d59c3f330fc10dd70dfbcce31c8b50e8c95722df3d32e4a334a05563d
# Code AST SHA-256:   32d140f3038578ab30b68735713ba8d5e0958f69d7eaa52d27c1bf5c90f7bf6f
# Verified Classes:   UsageAggregationDrift, ChatSpan, OperationSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UsageAggregationDrift(RuntimeError):
    """Raised when a span tree's token accounting cannot be soundly aggregated."""


@dataclass
class ChatSpan:
    attempt: int | None          # gen_ai.request.attempt, None if not emitted
    input_tokens: int
    finish_reason: str


@dataclass
class OperationSpan:
    span_id: str
    declared_input_tokens: int   # gen_ai.usage.input_tokens on the operation span
    children: list[ChatSpan]


def verify_operation_usage(op: OperationSpan) -> int:
    """Return billable input tokens, or raise if the trace is ambiguous/inflated."""
    if not op.children:
        # Leaf operation: the declared value is the only source of truth.
        return op.declared_input_tokens

    attempts = [c.attempt for c in op.children]
    if any(a is None for a in attempts):
        # Retry and fan-out are indistinguishable without an attempt discriminator.
        raise UsageAggregationDrift(
            f"span {op.span_id}: {len(op.children)} children with missing "
            f"gen_ai.request.attempt; cannot distinguish retry from fan-out"
        )

    if len(set(attempts)) != len(attempts):
        raise UsageAggregationDrift(
            f"span {op.span_id}: duplicate attempt indices {attempts}; "
            f"trace was re-emitted or merged"
        )

    terminal = max(op.children, key=lambda c: c.attempt)
    billable = terminal.input_tokens
    wasted = sum(c.input_tokens for c in op.children if c is not terminal)

    if op.declared_input_tokens != billable:
        raise UsageAggregationDrift(
            f"span {op.span_id}: declared {op.declared_input_tokens} != "
            f"terminal-attempt {billable} (wasted={wasted}); "
            f"operation span double-counts retries"
        )
    return billable
