# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-opentelemetry-genai-agent-spans-across-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-accounting-drift-from-silently-corrupting-opentelemetry-genai-agent-spans-across-tool-call-boundaries.warrant.json
# Markdown SHA-256:   45a220ce073742f0c0f5e9c7436f642b9f6b3046fc1128b9488704b2a9813a37
# Code AST SHA-256:   7b3da59a12123a3f4d7282a675219378f68823339ad1f4b5d2a783ea111f600b
# Verified Classes:   UsageReconciliationError, GenAISpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageReconciliationError(RuntimeError):
    """Raised when span-tree usage cannot be proven disjoint from billed usage."""
    pass


@dataclass
class GenAISpan:
    span_id: str
    parent_id: Optional[str]
    kind: str  # "model" | "tool" | "agent"
    input_tokens: int = 0
    output_tokens: int = 0
    billed_tokens: Optional[int] = None  # authoritative, post-stream
    cancelled: bool = False
    finish_reason: Optional[str] = None
    loop_id: Optional[str] = None


def reconcile_usage(spans: list[GenAISpan], ledger_tokens: int) -> int:
    """
    Enforce the tree-global invariant: sum of *billed* leaf usage must equal
    the provider ledger exactly once. Never sum input_tokens across re-entrant
    calls; they are context snapshots, not disjoint cost line items.
    """
    attributable = 0
    for s in spans:
        if s.kind != "model":
            continue
        if s.cancelled and s.billed_tokens is None:
            raise UsageReconciliationError(
                f"span {s.span_id}: cancelled stream closed without billed_tokens; "
                "usage is unattributable and must not be assigned to parent"
            )
        if s.billed_tokens is None:
            raise UsageReconciliationError(
                f"span {s.span_id}: model span missing authoritative billed_tokens; "
                "cannot prove disjointness from re-sent context"
            )
        attributable += s.billed_tokens

    residual = ledger_tokens - attributable
    if residual != 0:
        raise UsageReconciliationError(
            f"usage drift: span-attributable={attributable} ledger={ledger_tokens} "
            f"residual={residual}; likely re-entry double-count or orphaned tool round-trip"
        )
    return attributable
