# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-exhaust-its-context-budget-after-the-governor-reports-allocation-satisfied.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-exhaust-its-context-budget-after-the-governor-reports-allocation-satisfied.warrant.json
# Markdown SHA-256:   db879135574cf8e023fcf81254974148b25d47cf4b20acf89d5381c7f0013d66
# Code AST SHA-256:   d4f27e25a24a519152fdca0bfda56862972b160175940d9cb33fc568a1168215
# Verified Classes:   ContextBudgetInvariantError, BudgetGovernor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ContextBudgetInvariantError(RuntimeError):
    """Raised when a reservation check passes but measured serialization overruns the window."""
    pass


class BudgetGovernor:
    def __init__(self, window: int, generation_reserve: int, tokenizer):
        self.window = window
        self.generation_reserve = generation_reserve
        self.tokenizer = tokenizer  # must be the serving tokenizer, not an approximation

    def reserve(self, segments: dict[str, str]) -> dict[str, int]:
        # Advisory reservations only. Never authoritative.
        return {name: len(self.tokenizer.encode(payload)) for name, payload in segments.items()}

    def serialize_frame(self, segments: dict[str, str]) -> str:
        # Must include role delimiters, tool schemas, structural tokens — the full frame.
        return self._render_chat_template(segments)

    def _render_chat_template(self, segments: dict[str, str]) -> str:
        parts = []
        for role, payload in segments.items():
            parts.append(f"<|{role}|>\n{payload}\n<|end|>")
        return "\n".join(parts)

    def dispatch(self, segments: dict[str, str]) -> str:
        reservations = self.reserve(segments)
        reserved_total = sum(reservations.values())
        ceiling = self.window - self.generation_reserve

        frame = self.serialize_frame(segments)
        measured_total = len(self.tokenizer.encode(frame))

        # The authoritative gate. Reservation passing does NOT license dispatch.
        if measured_total > ceiling:
            raise ContextBudgetInvariantError(
                f"reservation={reserved_total} passed ceiling={ceiling} "
                f"but measured={measured_total} overruns window={self.window} "
                f"(delta={measured_total - reserved_total}); refusing dispatch"
            )
        return self._call_model(frame)

    def _call_model(self, frame: str) -> str:
        raise NotImplementedError("bound to serving transport in production")
