# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-token-accounting-divergence-between-genai-span-attributes-and-the-model-s-own-usage-envelope-at-turn-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-token-accounting-divergence-between-genai-span-attributes-and-the-model-s-own-usage-envelope-at-turn-boundaries.warrant.json
# Markdown SHA-256:   4b9a72ac878a605641e1f82ac929a0ebcd8a92564cd66ab78368a9882388b6ec
# Code AST SHA-256:   5046d206c275d6fa9c03031e2ad1b5f58f8580fe0209fc7ce688d02cb6540829
# Verified Classes:   UsageAccountingDivergence, TurnUsage
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UsageAccountingDivergence(RuntimeError):
    """Raised when span-emitted token usage cannot be reconciled with the provider envelope."""
    pass


@dataclass
class TurnUsage:
    provider_input: Optional[int]      # from response.usage; None if provider omitted it
    provider_output: Optional[int]
    span_input_sum: int                # sum of gen_ai.usage.input_tokens over turn span tree
    span_output_sum: int
    history_tokens: int                # tokens the runtime re-sent on resume
    accounting_mode: str               # "cumulative" | "incremental"
    epsilon: int = 8


def reconcile_turn_usage(u: TurnUsage) -> str:
    if u.provider_input is None:
        # Estimated source: governor may warn, must not act.
        return "estimated_no_hard_decision"

    if u.accounting_mode not in ("cumulative", "incremental"):
        raise UsageAccountingDivergence(
            f"unknown tool accounting_mode={u.accounting_mode!r}; cannot reconcile span tree"
        )

    delta = u.span_input_sum - u.provider_input

    # Negative beyond epsilon: tool-result tokens dropped from the tree.
    if delta < -u.epsilon:
        return "undercount_clamp_to_provider"

    # Positive beyond the re-sent-history bound: shared prefix double-counted.
    if delta > u.history_tokens + u.epsilon:
        raise UsageAccountingDivergence(
            "span input sum exceeds provider cumulative beyond re-sent-history bound: "
            f"span_sum={u.span_input_sum} provider={u.provider_input} "
            f"history={u.history_tokens} mode={u.accounting_mode}"
        )

    return "trust_span_tree"


def govern_turn(u: TurnUsage, window: int) -> int:
    verdict = reconcile_turn_usage(u)
    if verdict == "estimated_no_hard_decision":
        return window - (u.span_input_sum + u.span_output_sum)  # advisory only
    if verdict == "undercount_clamp_to_provider":
        return window - (u.provider_input + u.provider_output)
    # trust_span_tree
    return window - (u.provider_input + u.provider_output)
