# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-semantic-convention-token-counter-diverges-from-the-model-s-actual-billing-meter-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-semantic-convention-token-counter-diverges-from-the-model-s-actual-billing-meter-mid-run.warrant.json
# Markdown SHA-256:   e9bf00a7af2a979160d54ce92299c90d905fca08c92f71dfa58053fcee3b6edd
# Code AST SHA-256:   6516f8cf861f62a6610a272eb37c3a635d918f2ef516b107b5223b766c6ed368
# Verified Classes:   SemanticCounterDivergence
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SemanticCounterDivergence(RuntimeError):
    """Raised when a reconstructed token accumulator is used to gate a hard decision."""


# Conservative headroom as a fraction of the ceiling, sized to observed p99 drift.
DRIFT_HEADROOM = 0.15


def enforce_hard_context_gate(
    accumulated_semconv_tokens: int,
    authoritative_last_response_tokens: int | None,
    ceiling: int,
) -> None:
    """
    Hard gate: may only fire on an authoritative number.
    Falls open (logs + allows) when authority is missing, because a late
    compaction costs a retry while an early abort costs the whole task.
    """
    if authoritative_last_response_tokens is None:
        # No authority this turn: do NOT abort on the reconstructed counter.
        return

    effective = authoritative_last_response_tokens + int(ceiling * DRIFT_HEADROOM)
    if effective >= ceiling:
        raise SemanticCounterDivergence(
            f"authoritative={authoritative_last_response_tokens} "
            f"accumulated_semconv={accumulated_semconv_tokens} "
            f"ceiling={ceiling}: hard context gate tripped on reported usage"
        )


def reconcile_accumulator(
    accumulated_semconv_tokens: int,
    authoritative_last_response_tokens: int,
) -> int:
    """Overwrite, never add. Returns drift for the token_counter_drift metric."""
    drift = authoritative_last_response_tokens - accumulated_semconv_tokens
    return drift
