# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-opentelemetry-genai-token-accounting-when-a-retried-tool-call-double-counts-usage-across-agent-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-opentelemetry-genai-token-accounting-when-a-retried-tool-call-double-counts-usage-across-agent-spans.warrant.json
# Markdown SHA-256:   10d4fbbbb08bfd3925c71e2735d1e88c4908837cc699b1bb8e47d675a950c917
# Code AST SHA-256:   f774ad6917558e535c95fcacc8c019e4be9299f3ff6c890065861f51b96f3999
# Verified Classes:   AmbiguousUsageAccountingError, ModelSpan, StepUsage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AmbiguousUsageAccountingError(RuntimeError):
    """Raised when an agent step's spans cannot be split into physical vs logical token cost."""


@dataclass
class ModelSpan:
    span_id: str
    logical_action_id: str          # identifies the logical tool/reasoning action
    attempt: Optional[int]          # agent.retry.attempt; None if unmarked
    status: str                     # "OK" | "ERROR"
    input_tokens: int
    output_tokens: int


@dataclass
class StepUsage:
    physical_input: int = 0
    physical_output: int = 0
    logical_input: int = 0
    logical_output: int = 0


def account_step(spans: list[ModelSpan], logical_ceiling: int) -> StepUsage:
    by_action: dict[str, list[ModelSpan]] = {}
    for s in spans:
        by_action.setdefault(s.logical_action_id, []).append(s)

    usage = StepUsage()
    for action_id, group in by_action.items():
        # Physical cost: every attempt was billed, count all of them.
        usage.physical_input += sum(s.input_tokens for s in group)
        usage.physical_output += sum(s.output_tokens for s in group)

        # Logical cost: exactly one attempt per action must be selected.
        if len(group) == 1:
            chosen = group[0]
        else:
            if any(s.attempt is None for s in group):
                raise AmbiguousUsageAccountingError(
                    f"action {action_id!r} has {len(group)} spans but at least one "
                    f"lacks agent.retry.attempt; cannot distinguish retry from "
                    f"distinct step. Emit the attribute or split the action id."
                )
            terminal = [s for s in group if s.status == "OK"]
            if len(terminal) != 1:
                raise AmbiguousUsageAccountingError(
                    f"action {action_id!r} has {len(terminal)} OK attempts; "
                    f"expected exactly one terminal attempt to bill logically."
                )
            chosen = terminal[0]

        usage.logical_input += chosen.input_tokens
        usage.logical_output += chosen.output_tokens

    if usage.logical_input > logical_ceiling:
        raise AmbiguousUsageAccountingError(
            f"logical input {usage.logical_input} exceeds ceiling {logical_ceiling} "
            f"(physical was {usage.physical_input}); abort is legitimate."
        )
    return usage
