# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reconciles-a-fixed-kv-cache-budget-against-a-retrieval-injector-that-plans-against-a-stale-token-estimate.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reconciles-a-fixed-kv-cache-budget-against-a-retrieval-injector-that-plans-against-a-stale-token-estimate.warrant.json
# Markdown SHA-256:   b70f856f26ef410b406b4a7e648a41b2aa3f996c7bd77e742a07f1e6071f180a
# Code AST SHA-256:   c57571c491308d8faf072c188646380c6eb41aae764e0b92acaa2e68f23d8296
# Verified Classes:   BudgetInversionError, ContextBudgetScheduler
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class BudgetInversionError(RuntimeError):
    """Raised when an admission is authorized by a stale/estimated count
    rather than a measurement of the live serialized sequence."""


class ContextBudgetScheduler:
    def __init__(self, window: int, reserve_output: int, reserve_safety: int):
        self.window = window
        self.reserve = reserve_output + reserve_safety
        self._serialized = ""          # the exact bytes the runtime will feed
        self._measured_tokens = 0      # authoritative count
        self._dirty = True

    def append(self, serialized_fragment: str) -> None:
        self._serialized += serialized_fragment
        self._dirty = True             # invalidate any cached residual

    def _measure(self, tokenizer) -> int:
        if self._dirty:
            self._measured_tokens = len(tokenizer(self._serialized))
            self._dirty = False
        return self._measured_tokens

    def residual(self, tokenizer) -> int:
        return self.window - self.reserve - self._measure(tokenizer)

    def admit(self, chunk_serialized: str, tokenizer, estimated_tokens: int) -> None:
        # Guard: an estimate may never authorize an admission.
        true_cost = len(tokenizer(self._serialized + chunk_serialized)) - self._measure(tokenizer)
        if estimated_tokens != true_cost:
            raise BudgetInversionError(
                f"estimator ({estimated_tokens}) disagrees with measured envelope "
                f"cost ({true_cost}); admission refused"
            )
        if true_cost > self.residual(tokenizer):
            raise BudgetInversionError(
                f"chunk costs {true_cost} tokens, residual is {self.residual(tokenizer)}; "
                f"refuse and spill to external memory rather than truncate"
            )
        self.append(chunk_serialized)

    def assert_no_silent_eviction(self, tokens_fed: int, tokenizer) -> None:
        # Runtime must report what it actually fed; mismatch == silent drop.
        if tokens_fed != self._measure(tokenizer):
            raise BudgetInversionError(
                f"runtime fed {tokens_fed} tokens but scheduler holds "
                f"{self._measure(tokenizer)}; silent eviction occurred"
            )
