# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-token-budget-eviction-against-in-flight-tool-call-reservations-before-admitting-a-new-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-token-budget-eviction-against-in-flight-tool-call-reservations-before-admitting-a-new-turn.warrant.json
# Markdown SHA-256:   29e025705901192b9abf76ca2f021dd7f7a4de4a4f462fbcaf064c4f56a795b3
# Code AST SHA-256:   f0bf5fff9378e073aa6bb86384f390ad250a3814d8dbcaf8fd57265d03a2cb1c
# Verified Classes:   ReservationOrphanError, ContextGovernor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict


class ReservationOrphanError(RuntimeError):
    """Raised when eviction would orphan an in-flight tool-call reservation."""


@dataclass
class ContextGovernor:
    ceiling: int
    resident: int = 0
    # tool_call_id -> upper-bound token estimate for the pending result
    reservations: Dict[str, int] = field(default_factory=dict)
    # tool_call_id -> True if the originating call block is still resident
    call_block_present: Dict[str, bool] = field(default_factory=dict)

    def reserved_tokens(self) -> int:
        return sum(self.reservations.values())

    def admit_turn(self, next_turn_tokens: int, worst_case_result: int) -> bool:
        projected = self.resident + self.reserved_tokens() + next_turn_tokens + worst_case_result
        if projected <= self.ceiling:
            self.resident += next_turn_tokens
            return True
        # Boundary B: do not evict pinned call blocks to make room.
        self.drain()
        projected_after = self.resident + next_turn_tokens + worst_case_result
        if projected_after > self.ceiling:
            return False
        self.resident += next_turn_tokens
        return True

    def evict(self, span_tokens: int, covers_call_ids: list[str]) -> None:
        for cid in covers_call_ids:
            if cid in self.reservations and self.call_block_present.get(cid, False):
                raise ReservationOrphanError(
                    f"eviction span covers in-flight call block {cid!r}; "
                    f"result would arrive orphaned. Drain instead of evict."
                )
        self.resident = max(0, self.resident - span_tokens)

    def drain(self) -> None:
        # Block new admissions until reservations clear; do not touch resident.
        if self.reservations:
            raise ReservationOrphanError(
                f"cannot drain with {len(self.reservations)} outstanding calls; "
                f"stall admission and await results"
            )

    def register_call(self, call_id: str, upper_bound: int) -> None:
        self.reservations[call_id] = upper_bound
        self.call_block_present[call_id] = True

    def admit_result(self, call_id: str, actual_tokens: int) -> None:
        if call_id not in self.reservations:
            raise ReservationOrphanError(f"result for unknown call {call_id!r}")
        del self.reservations[call_id]
        # keep call block pinned for one turn to satisfy adjacency
        self.resident += actual_tokens
        self.call_block_present[call_id] = True
