# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-boundaries-as-a-correctness-constraint-rather-than-a-logging-convenience.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-opentelemetry-genai-span-boundaries-as-a-correctness-constraint-rather-than-a-logging-convenience.warrant.json
# Markdown SHA-256:   1cc6a9a038f87497e5e6478c35df31065c475b8eacdadb5b2ec90d6f6d726341
# Code AST SHA-256:   b8eabb8c3f80f49e45f93d1555fcc929ebe371267843bdca9c5d8cfe1c2f51cf
# Verified Classes:   SpanAccountingDivergence, GenAISpan, TurnCheckpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class SpanAccountingDivergence(RuntimeError):
    """Raised when a span-derived token aggregate cannot be reconciled against
    the committed checkpoint log, i.e. observability has led durability."""


@dataclass
class GenAISpan:
    trace_id: str
    turn_index: int
    operation: str            # "chat" | "execute_tool"
    tool_call_id: str | None
    output_tokens: int
    input_tokens: int
    attempt_disposition: str  # "committed" | "discarded" | "orphaned"
    status_ok: bool


@dataclass
class TurnCheckpoint:
    trace_id: str
    turn_index: int
    committed_output_tokens: int
    committed_input_tokens: int
    committed_tool_call_ids: set[str] = field(default_factory=set)


def reconcile_turn_usage(
    spans: Iterable[GenAISpan],
    checkpoint: TurnCheckpoint,
) -> dict[str, int]:
    """Reconstruct authoritative usage for one turn from spans, then verify it
    against the committed checkpoint. Raises if the aggregate the budget
    enforcer would read disagrees with durable state."""
    committed_chat = [
        s for s in spans
        if s.operation == "chat"
        and s.attempt_disposition == "committed"
        and s.turn_index == checkpoint.turn_index
    ]
    if len(committed_chat) != 1:
        raise SpanAccountingDivergence(
            f"turn {checkpoint.turn_index} has {len(committed_chat)} committed "
            f"chat spans; expected exactly 1 (attempt disposition not set at emission?)"
        )

    span = committed_chat[0]
    if span.output_tokens != checkpoint.committed_output_tokens:
        raise SpanAccountingDivergence(
            f"turn {checkpoint.turn_index}: span output_tokens={span.output_tokens} "
            f"!= checkpoint committed={checkpoint.committed_output_tokens}; "
            f"observability led durability (cache-aware usage block likely ignored)"
        )

    tool_ids = {
        s.tool_call_id for s in spans
        if s.operation == "execute_tool"
        and s.turn_index == checkpoint.turn_index
        and s.attempt_disposition == "committed"
    }
    if tool_ids != checkpoint.committed_tool_call_ids:
        raise SpanAccountingDivergence(
            f"turn {checkpoint.turn_index}: committed tool_call_ids {tool_ids} "
            f"!= checkpoint {checkpoint.committed_tool_call_ids}; "
            f"resume minted duplicate call IDs"
        )

    return {
        "input_tokens": span.input_tokens,
        "output_tokens": span.output_tokens,
        "tool_calls": len(tool_ids),
    }
