# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-span-attribute-collapse-when-an-agent-s-tool-call-tree-is-re-emitted-across-retries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-span-attribute-collapse-when-an-agent-s-tool-call-tree-is-re-emitted-across-retries.warrant.json
# Markdown SHA-256:   4d4008d31565b29d6e8c570b2c71bc054b76343311a64672dbe88943016c5418
# Code AST SHA-256:   e361687dfc59a15c1626a53bc55e3ee87af08af844e5142b89c0cb21865fa4aa
# Verified Classes:   UnauthoritativeUsageError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnauthoritativeUsageError(RuntimeError):
    """Raised when token aggregation encounters a span whose usage authority is ambiguous."""


@dataclass
class GenAISpan:
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str          # gen_ai.operation.name
    step_id: Optional[str]       # gen_ai.step.id  (custom; required for retry-capable agents)
    attempt_index: Optional[int] # gen_ai.attempt.index
    input_tokens: int            # gen_ai.usage.input_tokens
    output_tokens: int           # gen_ai.usage.output_tokens
    authoritative: Optional[bool]  # gen_ai.usage.authoritative
    status: str = "OK"


def aggregate_authoritative_input_tokens(spans: list[GenAISpan], retry_capable: bool) -> int:
    """
    Sum input tokens across a span tree, enforcing the token-authority invariant.

    Invariant: for each logical step, exactly one span is authoritative; only
    authoritative spans contribute to the sum. In retry-capable agents, a span
    missing step_id / attempt_index / authoritative is an accounting hazard and
    must not be silently summed.
    """
    seen_steps: dict[str, GenAISpan] = {}
    total = 0

    for span in spans:
        if retry_capable:
            if span.step_id is None or span.attempt_index is None or span.authoritative is None:
                raise UnauthoritativeUsageError(
                    f"Span {span.span_id} ({span.operation_name}) in a retry-capable agent "
                    f"is missing step_id/attempt_index/authoritative; token accounting is unverifiable."
                )
            # Keep the highest successful attempt per logical step.
            prior = seen_steps.get(span.step_id)
            if prior is None or span.attempt_index > prior.attempt_index:
                seen_steps[span.step_id] = span

        if span.authoritative is True:
            total += span.input_tokens

    if retry_capable:
        for step_id, chosen in seen_steps.items():
            if chosen.authoritative is not True:
                raise UnauthoritativeUsageError(
                    f"Logical step {step_id} has no authoritative usage span after "
                    f"attempt resolution (best attempt {chosen.attempt_index}, status {chosen.status})."
                )

    return total


def verify_trace(spans: list[GenAISpan], retry_capable: bool) -> int:
    try:
        return aggregate_authoritative_input_tokens(spans, retry_capable)
    except UnauthoritativeUsageError:
        raise
    except Exception as exc:  # defensive: never let a malformed trace pass as valid
        raise UnauthoritativeUsageError(f"Trace verification failed: {exc}") from exc
