# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-genai-span-trees-under-retry-and-streaming.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-genai-span-trees-under-retry-and-streaming.warrant.json
# Markdown SHA-256:   1d307718fc345872e0085629f3ca63d05f321cb87bf8791005e2d6f8246b6d36
# Code AST SHA-256:   e8429756db5252e11db1ee3656c647446d484f99debe29c69a8cfe8251bbe700
# Verified Classes:   NonAuthoritativeUsageError, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class NonAuthoritativeUsageError(RuntimeError):
    """Raised when a span claims authoritative usage without satisfying the invariant."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    operation_id: str
    operation_name: str
    status: str  # "OK" | "ERROR"
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    finish_reasons: Optional[list] = None
    aborted: bool = False
    authoritative: bool = False


def close_attempt_span(
    span: GenAISpan,
    *,
    response_consumed: bool,
    terminal_finish_reason: bool,
) -> GenAISpan:
    """Apply the authority invariant at span-close time.

    Authority requires: response was consumed by the agent AND a terminal
    finish reason was observed. Anything else is diagnostic-only.
    """
    if response_consumed and terminal_finish_reason:
        span.authoritative = True
        return span

    # Non-authoritative path: input tokens are real spend, output tokens
    # are only real if the stream produced them before abort.
    if span.output_tokens is not None and not span.aborted:
        raise NonAuthoritativeUsageError(
            f"span {span.span_id} has output_tokens={span.output_tokens} "
            f"but was not consumed and not marked aborted; cannot classify"
        )

    span.authoritative = False
    return span


def aggregate_authoritative_usage(spans: list[GenAISpan]) -> dict:
    """Sum usage across a trace, counting only authoritative spans for
    output accounting, all spans for input accounting."""
    by_op: dict[str, dict] = {}
    for s in spans:
        bucket = by_op.setdefault(
            s.operation_id, {"input": 0, "output": 0, "authoritative_found": False}
        )
        if s.input_tokens:
            bucket["input"] += s.input_tokens
        if s.authoritative:
            if bucket["authoritative_found"]:
                raise NonAuthoritativeUsageError(
                    f"operation {s.operation_id} has multiple authoritative spans"
                )
            bucket["authoritative_found"] = True
            if s.output_tokens:
                bucket["output"] += s.output_tokens
    return by_op
