# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-divergence-between-opentelemetry-genai-token-metrics-and-the-model-s-own-usage-ledger-at-span-close.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-divergence-between-opentelemetry-genai-token-metrics-and-the-model-s-own-usage-ledger-at-span-close.warrant.json
# Markdown SHA-256:   5aba50b2df04d971846f328218989f05f2233f07e8cb1d11a49cefe5a6e6fbd9
# Code AST SHA-256:   3e98b973f92e9f2227144c003d517eb20e3916c9b5092fe239871bfe6568b720
# Verified Classes:   SpanUsageDivergence, ChatSpanUsage, ParentSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class SpanUsageDivergence(RuntimeError):
    """Raised when a parent GenAI span's projected token usage cannot be
    reconciled against the retained provider usage ledger."""
    pass


@dataclass
class ChatSpanUsage:
    span_id: str
    input_tokens: int
    output_tokens: int
    billed: bool = True
    retry_of: str | None = None


@dataclass
class ParentSpan:
    span_id: str
    children: list[ChatSpanUsage] = field(default_factory=list)
    turn_shape: Literal["single", "tool_loop", "unknown"] = "unknown"
    reconciled: bool = False


def reconcile_parent_usage(
    parent: ParentSpan,
    context_window: int,
    ledger_available: bool,
) -> dict[str, int]:
    if not ledger_available:
        # Cannot verify the sum against the provider ledger. Do not emit a
        # confident sum; surface as unreconciled so downstream cost and
        # saturation guards treat it as a known-unknown.
        parent.reconciled = False
        raise SpanUsageDivergence(
            f"parent {parent.span_id}: provider usage ledger evicted; "
            "cannot reconcile projected gen_ai.usage against billed tokens"
        )

    billed = [c for c in parent.children if c.billed]
    if not billed:
        raise SpanUsageDivergence(
            f"parent {parent.span_id}: no billed chat spans; "
            "parent usage would be zero but turn executed"
        )

    # Detect retry inflation: a billed span whose retry_of points at a
    # non-billed sibling means the failed attempt leaked into the sum.
    retried = {c.retry_of for c in parent.children if c.retry_of}
    leaked = [c for c in billed if c.span_id in retried]
    if leaked:
        raise SpanUsageDivergence(
            f"parent {parent.span_id}: retried span {leaked[0].span_id} "
            "counted in cost sum; failed attempt must be billed=false"
        )

    total_input = sum(c.input_tokens for c in billed)
    max_input = max(c.input_tokens for c in billed)

    if parent.turn_shape == "unknown":
        # Cannot classify; a sum would be ambiguous between cost and
        # saturation semantics. Refuse to emit.
        raise SpanUsageDivergence(
            f"parent {parent.span_id}: turn_shape unclassified; "
            "sum is valid as throughput but not as cost or saturation"
        )

    if parent.turn_shape == "tool_loop" and len(billed) > 1:
        # Cost = final context sent; saturation = high-water mark.
        # Parent gen_ai.usage.input_tokens must carry max, not sum.
        if total_input > context_window:
            # Sum exceeded the window: the naive guard would have
            # saturated permanently and triggered a compaction storm.
            pass
        parent.reconciled = True
        return {
            "gen_ai.usage.input_tokens": max_input,
            "gen_ai.usage.total_input_tokens": total_input,
            "gen_ai.usage.output_tokens": sum(c.output_tokens for c in billed),
        }

    # Single inference: sum == max == cost == saturation.
    parent.reconciled = True
    return {
        "gen_ai.usage.input_tokens": total_input,
        "gen_ai.usage.output_tokens": sum(c.output_tokens for c in billed),
    }
