# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-divergence-between-its-local-budget-ledger-and-the-otel-genai-span-tree-during-a-multi-hop-tool-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-divergence-between-its-local-budget-ledger-and-the-otel-genai-span-tree-during-a-multi-hop-tool-loop.warrant.json
# Markdown SHA-256:   aaed341c56f1692aaefadb8685b5c9d9cd860bc90c175a31f7e7e3c38b9a434b
# Code AST SHA-256:   0fc74a51062c2e301d6fcbf06bdc009b06a201adf126fd90bea3002f74c98774
# Verified Classes:   TokenAccountingDivergence, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

RECONCILE_TOLERANCE = 1.02
SESSION_HALT_RATIO = 1.05


class TokenAccountingDivergence(RuntimeError):
    """Raised when the OTel GenAI span tree disagrees with the local ledger."""


@dataclass
class GenAISpan:
    span_id: str
    turn_id: str
    operation: str  # e.g. "chat"
    input_tokens: int | None
    output_tokens: int | None
    finish_reason: str | None = None


def span_token_sum(spans: Iterable[GenAISpan], turn_id: str) -> int:
    total = 0
    for s in spans:
        if s.turn_id != turn_id or s.operation != "chat":
            continue
        # Missing usage attributes are NOT zero — they are unknown, and a naive
        # sum would under-count. Treat as divergence-triggering.
        if s.input_tokens is None or s.output_tokens is None:
            raise TokenAccountingDivergence(
                f"span {s.span_id} on turn {turn_id} lacks gen_ai.usage.* "
                f"attributes; cannot reconcile"
            )
        total += s.input_tokens + s.output_tokens
    return total


def reconcile_turn(
    spans: list[GenAISpan],
    turn_id: str,
    ledger_debit: int,
    session_cumulative_ratio: float,
) -> tuple[int, float]:
    """Returns (conservative_debit, new_cumulative_ratio).

    On divergence above tolerance, raises; the caller must re-debit the ledger
    by the span-tree sum before proceeding.
    """
    if ledger_debit <= 0:
        raise TokenAccountingDivergence(
            f"turn {turn_id}: ledger debit {ledger_debit} is non-positive; "
            f"ledger state is corrupt"
        )
    observed = span_token_sum(spans, turn_id)
    ratio = observed / ledger_debit

    if ratio > RECONCILE_TOLERANCE:
        raise TokenAccountingDivergence(
            f"turn {turn_id}: span tree {observed} > ledger {ledger_debit} "
            f"(ratio {ratio:.3f}); likely retry/truncation under-debit. "
            f"Re-debit by {observed} before next admission."
        )

    new_cumulative = (session_cumulative_ratio + ratio) / 2.0
    if new_cumulative > SESSION_HALT_RATIO:
        raise TokenAccountingDivergence(
            f"session cumulative ratio {new_cumulative:.3f} exceeds halt "
            f"threshold {SESSION_HALT_RATIO}; ledger no longer a safe bound"
        )

    # Conservative: debit the higher of the two figures.
    return max(observed, ledger_debit), new_cumulative
