# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-tool-call-spans-against-its-own-token-budget-and-what-breaks-when-the-span-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-opentelemetry-genai-tool-call-spans-against-its-own-token-budget-and-what-breaks-when-the-span-ledger.warrant.json
# Markdown SHA-256:   7905a8fac5fcc2b71047907474275880f84d49bcda4acde268b9b8bf31b9a900
# Code AST SHA-256:   9afcabf9d6c02dbd02108deb9618f3d18c725150f12e64035d8fe3db146aa335
# Verified Classes:   SpanLedgerDivergence, BudgetDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanLedgerDivergence(RuntimeError):
    """Raised when span-derived token accounting disagrees with the runtime counter."""
    pass


@dataclass
class BudgetDecision:
    allow: bool
    authoritative_spent: int
    span_sum: int
    headroom: int


def reconcile_budget(
    runtime_counter: int,
    span_usage_sum: int,
    ceiling: int,
    reserved_tail: int,
    tolerance: int = 0,
) -> BudgetDecision:
    """
    Enforce the invariant: runtime_counter >= span_usage_sum.
    The span sum is a lower bound; the runtime counter is authoritative.
    """
    if span_usage_sum > runtime_counter + tolerance:
        # Spans claim more than the runtime billed: double-count (nesting bug).
        raise SpanLedgerDivergence(
            f"span sum {span_usage_sum} exceeds runtime counter {runtime_counter}; "
            f"likely nested execute_tool double-count"
        )

    divergence = runtime_counter - span_usage_sum
    if divergence > tolerance:
        # Spans under-report: dropped spans or absent-as-zero streaming usage.
        # We do NOT trust the span sum; we proceed on the runtime counter and
        # record the divergence so it is not silently absorbed.
        spent = runtime_counter
    else:
        spent = runtime_counter

    headroom = ceiling - spent
    allow = headroom >= reserved_tail

    if allow and headroom < 0:
        raise SpanLedgerDivergence(
            f"negative headroom {headroom} with allow=True; guard logic corrupt"
        )

    return BudgetDecision(
        allow=allow,
        authoritative_spent=spent,
        span_sum=span_usage_sum,
        headroom=headroom,
    )


def guarded_continuation(
    runtime_counter: int,
    span_usage_sum: int,
    ceiling: int,
    reserved_tail: int,
) -> None:
    decision = reconcile_budget(
        runtime_counter, span_usage_sum, ceiling, reserved_tail, tolerance=0
    )
    if not decision.allow:
        raise SpanLedgerDivergence(
            f"continuation denied: spent={decision.authoritative_spent} "
            f"ceiling={ceiling} reserved_tail={reserved_tail} "
            f"span_sum={decision.span_sum}"
        )
