# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-opentelemetry-genai-span-attributes-as-evidence-rather-than-truth.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-opentelemetry-genai-span-attributes-as-evidence-rather-than-truth.warrant.json
# Markdown SHA-256:   121bdfb660628accb6643c509085876f788fb9686022c6c62ddc9539b50e04cf
# Code AST SHA-256:   1ea3ab964ed159c5fdf5a1cc68bb4381e5248f203f54cb72fad135e48c696f95
# Verified Classes:   SpanAccountingInvariantError, LogicalCallSpan, AttemptSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpanAccountingInvariantError(RuntimeError):
    """Raised when span-derived token usage is promoted to a truth source
    without reconciliation against an attempt-level record."""
    pass


@dataclass
class LogicalCallSpan:
    operation_name: str
    input_tokens: Optional[int]      # gen_ai.usage.input_tokens
    output_tokens: Optional[int]     # gen_ai.usage.output_tokens
    finish_reasons: list[str]        # gen_ai.response.finish_reasons
    request_model: str               # gen_ai.request.model


@dataclass
class AttemptSpan:
    attempt_index: int
    billed_tokens_estimate: int      # from provider billing or wrapper-side count
    outcome: str                     # "ok" | "rate_limited" | "transport_error" | "truncated"


def reconcile_usage(
    logical: LogicalCallSpan,
    attempts: list[AttemptSpan],
    *,
    purpose: str,  # "observability" | "cost_attribution" | "budget_gate" | "audit"
) -> int:
    """Return a token count safe for the given purpose.

    Span usage is promoted to truth only when the attempt record confirms it.
    Otherwise the conservative upper bound (sum of attempt estimates) is used.
    """
    if logical.input_tokens is None or logical.output_tokens is None:
        # Absent usage: never promote. Fall back to attempt sum.
        span_usage = None
    else:
        span_usage = logical.input_tokens + logical.output_tokens

    attempt_sum = sum(a.billed_tokens_estimate for a in attempts)
    retried = len(attempts) > 1
    truncated = "length" in logical.finish_reasons
    fallback = any(a.outcome == "transport_error" for a in attempts)

    # The four validity conditions from the record.
    valid_as_truth = (
        not retried
        and not truncated
        and not fallback
        and span_usage is not None
        and span_usage == attempt_sum
    )

    if purpose in ("observability",):
        return span_usage if span_usage is not None else attempt_sum

    if purpose in ("cost_attribution", "budget_gate", "audit"):
        if not valid_as_truth:
            # Irreversible decisions must not consume unreconciled span usage.
            if purpose == "budget_gate" and span_usage is not None and attempt_sum < span_usage:
                raise SpanAccountingInvariantError(
                    f"attempt sum {attempt_sum} < span usage {span_usage} "
                    f"for {logical.operation_name}/{logical.request_model}; "
                    f"retried={retried} truncated={truncated} fallback={fallback}"
                )
            return attempt_sum
        return span_usage

    raise SpanAccountingInvariantError(f"unknown purpose: {purpose}")
