# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-agent-cost-telemetry-when-tool-call-spans-straddle-sampling-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-agent-cost-telemetry-when-tool-call-spans-straddle-sampling-boundaries.warrant.json
# Markdown SHA-256:   51034b96495b060c761058f27b3c671190fac4c3776478680aa231a1a100d1ff
# Code AST SHA-256:   b984b9f02ac906f1326856c8c2cf7615b4c3dcabe487a1a595a8daa2d7855a7a
# Verified Classes:   CostTelemetryInvariantError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class CostTelemetryInvariantError(RuntimeError):
    """Raised when a span set violates the GenAI token-accounting invariant."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_id: str | None
    operation_name: str          # gen_ai.operation.name
    agent_name: str | None       # gen_ai.agent.name
    input_tokens: int | None     # gen_ai.usage.input_tokens
    output_tokens: int | None    # gen_ai.usage.output_tokens


def validate_turn(spans: Iterable[Span]) -> int:
    """
    Enforce the cost-telemetry invariants for one logical agent turn.
    Returns the total billed tokens (input+output) attributable to the turn.

    Invariants checked:
      (1) gen_ai.usage.* appears ONLY on gen_ai.operation.name == 'chat' spans.
      (2) every span in the turn carries gen_ai.agent.name (sampling-invariant identity).
      (3) no duplicate span_id (guards against double-export).
    """
    spans = list(spans)
    seen_ids: set[str] = set()
    total = 0

    for s in spans:
        if s.span_id in seen_ids:
            raise CostTelemetryInvariantError(
                f"duplicate span_id {s.span_id} in trace {s.trace_id}: "
                "double-export would double-count tokens"
            )
        seen_ids.add(s.span_id)

        has_usage = s.input_tokens is not None or s.output_tokens is not None

        # Invariant (1): token attributes only on chat spans.
        if has_usage and s.operation_name != "chat":
            raise CostTelemetryInvariantError(
                f"span {s.span_id} op={s.operation_name!r} carries gen_ai.usage.*; "
                "token attributes are only valid on gen_ai.operation.name='chat'"
            )

        # Invariant (2): identity must survive parent-span sampling.
        if s.agent_name is None:
            raise CostTelemetryInvariantError(
                f"span {s.span_id} op={s.operation_name!r} missing gen_ai.agent.name; "
                "cost aggregator cannot attribute tokens if parent span is sampled out"
            )

        if s.operation_name == "chat":
            total += (s.input_tokens or 0) + (s.output_tokens or 0)

    if not any(s.operation_name == "chat" for s in spans):
        raise CostTelemetryInvariantError(
            f"trace {spans[0].trace_id if spans else '<empty>'} has no chat span; "
            "turn cost cannot be established"
        )

    return total
