# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-otel-genai-agent-spans-when-tool-call-retries-re-enter-the-reasoning-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-otel-genai-agent-spans-when-tool-call-retries-re-enter-the-reasoning-loop.warrant.json
# Markdown SHA-256:   9560a5b2affcf5900effb109081e39da13318f2e891d8a875930f344f107df0c
# Code AST SHA-256:   da66701d1d751a1bfe43f94c47c8e86ef6b710ebe0e65a500ea594fef8882684
# Verified Classes:   GenAiTokenAccountingError, ChatSpan, ToolSpan, AgentTrace
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAiTokenAccountingError(RuntimeError):
    """Raised when a GenAI agent trace violates the retry-dedup invariant."""


@dataclass
class ChatSpan:
    span_id: str
    parent_span_id: Optional[str]
    operation: str                      # gen_ai.operation.name
    input_tokens: int                   # gen_ai.usage.input_tokens
    output_tokens: int                  # gen_ai.usage.output_tokens
    retry_attempt: Optional[int] = None # gen_ai.request.retry_attempt (None == not a retry)
    retry_of_span_id: Optional[str] = None


@dataclass
class ToolSpan:
    span_id: str
    parent_span_id: Optional[str]
    tool_name: str                      # gen_ai.tool.name
    status: str


@dataclass
class AgentTrace:
    root_span_id: str
    chat_spans: list = field(default_factory=list)
    tool_spans: list = field(default_factory=list)


def aggregate_logical_tokens(trace: AgentTrace) -> dict:
    """
    Sum token usage over chat spans, deduplicating retries against their
    original span. Requires every retry span to declare retry_of_span_id.
    """
    by_id = {s.span_id: s for s in trace.chat_spans}
    seen_originals: set = set()
    logical_input = 0
    logical_output = 0
    billed_input = 0
    billed_output = 0

    for span in trace.chat_spans:
        if span.operation != "chat":
            continue
        billed_input += span.input_tokens
        billed_output += span.output_tokens

        if span.retry_attempt is not None and span.retry_attempt > 0:
            # Retry: must back-reference the original to be dedupable.
            if span.retry_of_span_id is None or span.retry_of_span_id not in by_id:
                raise GenAiTokenAccountingError(
                    f"chat span {span.span_id} is a retry (attempt="
                    f"{span.retry_attempt}) but has no valid "
                    f"gen_ai.retry.of_span_id back-reference; token "
                    f"deduplication is impossible and logical input_tokens "
                    f"would be double-counted."
                )
            # Dedup: the original span already contributed to logical totals.
            continue

        # Non-retry span: this is the logical step's authoritative accounting.
        if span.span_id in seen_originals:
            raise GenAiTokenAccountingError(
                f"chat span {span.span_id} counted twice as a logical step."
            )
        seen_originals.add(span.span_id)
        logical_input += span.input_tokens
        logical_output += span.output_tokens

    # Invariant: a retried tool span must be a child of its retry chat span.
    chat_ids = {s.span_id for s in trace.chat_spans}
    for tool in trace.tool_spans:
        if tool.parent_span_id not in chat_ids:
            raise GenAiTokenAccountingError(
                f"tool span {tool.span_id} ({tool.tool_name}) is not a child "
                f"of any chat span; retry provenance cannot be resolved and "
                f"the aggregation tree does not mirror the call graph."
            )

    if logical_input > billed_input:
        raise GenAiTokenAccountingError(
            f"logical input_tokens ({logical_input}) exceeds billed "
            f"({billed_input}); dedup logic is inverted or spans are missing."
        )

    return {
        "gen_ai.usage.input_tokens": billed_input,
        "gen_ai.usage.output_tokens": billed_output,
        "agent.logical_input_tokens": logical_input,
        "agent.logical_output_tokens": logical_output,
    }
