# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-span-token-budget-overrun-when-opentelemetry-genai-spans-close-after-the-cost-has-already-been-incurred.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-span-token-budget-overrun-when-opentelemetry-genai-spans-close-after-the-cost-has-already-been-incurred.warrant.json
# Markdown SHA-256:   68a7036ab8ad127c9856a4dffed8fa1fc45230a1572a28767f6ea09bcb374719
# Code AST SHA-256:   b1e773d69e6c952ad442593fb497dff5ccfb7735cde4516dae26bb11f12a7e54
# Verified Classes:   BudgetEnforcementViolation, SpanUsage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class BudgetEnforcementViolation(RuntimeError):
    """Raised when an agent attempts to gate dispatch on post-hoc GenAI usage telemetry."""
    pass


@dataclass
class SpanUsage:
    input_tokens: int | None = None   # None until span closes
    output_tokens: int | None = None
    closed: bool = False


def pre_dispatch_budget_gate(
    serialized_payload: str,
    estimate_tokenizer,
    remaining_budget: int,
    safety_margin: float = 0.15,
) -> int:
    """
    Enforce budget BEFORE dispatch using a payload estimate.
    Returns the estimated input tokens if dispatch is permitted.
    """
    estimated = estimate_tokenizer(serialized_payload)
    ceiling = int(remaining_budget * (1.0 - safety_margin))
    if estimated > ceiling:
        raise BudgetEnforcementViolation(
            f"pre-dispatch estimate {estimated} exceeds margin-adjusted "
            f"ceiling {ceiling} of remaining {remaining_budget}"
        )
    return estimated


def reconcile_post_close(
    estimated: int,
    span: SpanUsage,
    tolerance: float = 0.20,
) -> float:
    """
    After the span closes, compare estimate to ledger and recalibrate.
    Refuses to treat an open span's usage as a gate signal.
    """
    if not span.closed or span.input_tokens is None:
        raise BudgetEnforcementViolation(
            "attempted to read gen_ai.usage.input_tokens from an open span; "
            "value is unset and must not gate dispatch"
        )
    drift = abs(span.input_tokens - estimated) / max(span.input_tokens, 1)
    if drift > tolerance:
        raise BudgetEnforcementViolation(
            f"tokenizer drift {drift:.2%} exceeds tolerance {tolerance:.2%}; "
            f"estimate {estimated} vs billed {span.input_tokens}"
        )
    return drift
