# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reconcile-opentelemetry-genai-span-closure-against-token-budget-exhaustion-before-emitting-cost-telemetry.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reconcile-opentelemetry-genai-span-closure-against-token-budget-exhaustion-before-emitting-cost-telemetry.warrant.json
# Markdown SHA-256:   77b729eb4bb0064952ecbc52e4f72a6f1e5a3dd4c423821c4f6cb26ce4c7a0be
# Code AST SHA-256:   4ae4fcbd1b65ca4a3fec7bd30192ed23115f78ac0dc3a41901e48a8afc4dc2f6
# Verified Classes:   TruncatedUsageTelemetryError, SpanUsage
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TruncatedUsageTelemetryError(RuntimeError):
    """Raised when a span closes with an in-flight model call but carries
    neither complete usage attributes nor an explicit truncation marker."""


@dataclass
class SpanUsage:
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    truncated: bool = False
    in_flight_at_close: bool = False


def finalize_span_usage(usage: SpanUsage, span_name: str) -> SpanUsage:
    """Enforce the invariant: a span that closed with a model call in flight
    must either have complete usage or be explicitly marked truncated."""
    if usage.in_flight_at_close:
        if usage.truncated and usage.input_tokens is not None:
            # Partial usage recorded; downstream must reconcile, not sum.
            return usage
        raise TruncatedUsageTelemetryError(
            f"span {span_name!r} closed with in-flight model call but no "
            f"truncation marker or partial usage; cost telemetry would "
            f"silently under-report this run"
        )
    if usage.input_tokens is None or usage.output_tokens is None:
        raise TruncatedUsageTelemetryError(
            f"span {span_name!r} closed without in-flight call but missing "
            f"usage attributes; cannot distinguish zero-cost from lost usage"
        )
    return usage


def aggregate_trace_cost(spans: list[SpanUsage]) -> tuple[int, int]:
    """Return (measured_tokens, unreconciled_span_count). Truncated spans are
    excluded from measured cost and counted for provider reconciliation."""
    measured = 0
    unreconciled = 0
    for s in spans:
        if s.truncated:
            unreconciled += 1
            continue
        measured += (s.input_tokens or 0) + (s.output_tokens or 0)
    return measured, unreconciled
