# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-in-opentelemetry-genai-agent-spans-when-tool-call-subtrees-are-re-emitted-after-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-in-opentelemetry-genai-agent-spans-when-tool-call-subtrees-are-re-emitted-after-retry.warrant.json
# Markdown SHA-256:   cc1e82b358e4c86a939432b600244f6e04c2e57a9e67653a0d673d4ed4453599
# Code AST SHA-256:   30f7e9ece9e6dd1b84762368cb7feefeaa76272e761f8d9e329e1e5a0ba263c4
# Verified Classes:   TokenAccountingInvariantError, GenAISpanEmission, EmissionLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TokenAccountingInvariantError(RuntimeError):
    """Raised when a span emission would make token usage ambiguous under naive aggregation."""
    pass


@dataclass
class GenAISpanEmission:
    trace_id: str
    span_id: str
    operation_name: str          # gen_ai.operation.name
    tool_name: Optional[str]     # gen_ai.tool.name
    step_id: Optional[str]       # gen_ai.agent.step_id  (custom, required for retries)
    attempt: Optional[int]       # gen_ai.agent.attempt  (custom, required for retries)
    status_code: str             # "OK" | "ERROR"
    input_tokens: Optional[int]  # gen_ai.usage.input_tokens
    output_tokens: Optional[int] # gen_ai.usage.output_tokens


@dataclass
class EmissionLedger:
    # (trace_id, step_id) -> list of attempts already emitted
    seen: dict = field(default_factory=dict)

    def record(self, e: GenAISpanEmission, aggregator_is_attempt_aware: bool) -> None:
        carries_usage = e.input_tokens is not None or e.output_tokens is not None
        if not carries_usage:
            # A usage-free span is always safe to emit (e.g. stripped superseded attempt).
            return

        key = (e.trace_id, e.step_id)
        prior_attempts = self.seen.get(key, [])

        if prior_attempts and not aggregator_is_attempt_aware:
            # Re-execution of a logical step, but downstream cannot distinguish attempts
            # from distinct steps. Emitting usage here guarantees drift.
            raise TokenAccountingInvariantError(
                f"refusing usage-bearing span for step_id={e.step_id!r} "
                f"attempt={e.attempt!r}: prior attempts {prior_attempts} already "
                f"emitted usage and aggregator is not attempt-aware; "
                f"either strip gen_ai.usage.* on superseded attempts or set "
                f"aggregator_is_attempt_aware=True and emit gen_ai.agent.attempt."
            )

        if e.attempt is None or e.step_id is None:
            # First emission without identity is tolerated only if no retry can follow.
            # If a retry does follow, this span becomes the un-keyed duplicate.
            if prior_attempts:
                raise TokenAccountingInvariantError(
                    f"usage-bearing retry for step_id={e.step_id!r} lacks "
                    f"gen_ai.agent.attempt; cannot order attempts for argmax dedup."
                )

        if e.attempt is not None and e.attempt in prior_attempts:
            raise TokenAccountingInvariantError(
                f"duplicate attempt {e.attempt!r} for step_id={e.step_id!r} in "
                f"trace {e.trace_id!r}; attempt counter must be monotonic."
            )

        self.seen.setdefault(key, []).append(e.attempt if e.attempt is not None else 0)


def aggregate_input_tokens(emissions: list[GenAISpanEmission]) -> int:
    """Attempt-aware aggregation: sum usage of the terminal attempt per (trace_id, step_id)."""
    by_step: dict = {}
    for e in emissions:
        if e.input_tokens is None:
            continue
        key = (e.trace_id, e.step_id)
        prev = by_step.get(key)
        rank = (e.status_code != "ERROR", e.attempt or 0)
        if prev is None or rank > (prev.status_code != "ERROR", prev.attempt or 0):
            by_step[key] = e
    total = sum(e.input_tokens or 0 for e in by_step.values())
    return total
