# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-when-retrieval-and-memory-write-budgets-are-drawn-from-the-same-ceiling.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-when-retrieval-and-memory-write-budgets-are-drawn-from-the-same-ceiling.warrant.json
# Markdown SHA-256:   62b013b603ed79d40a4c3fd1b925b811b240f870022d2b95e390a9e9ae1a93ff
# Code AST SHA-256:   22615cf1db75549e3e901c115f6785b75e68e2596e6c1e2e08e58a2429ee8227
# Verified Classes:   BudgetConflictError, ContextBudgetAllocator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class BudgetConflictError(RuntimeError):
    """Raised when admitting a consumer would starve a higher-priority reserve."""
    pass


class ContextBudgetAllocator:
    def __init__(self, ceiling: int, compaction_threshold: int):
        self.ceiling = ceiling
        self.compaction_threshold = compaction_threshold
        self.used = 0
        self.pending_memory_write_tokens = 0

    def admit_retrieval(self, request_tokens: int, deferrable: bool) -> bool:
        headroom = self.ceiling - self.used - self.pending_memory_write_tokens
        if request_tokens <= headroom:
            self.used += request_tokens
            return True
        if self.pending_memory_write_tokens > 0 and deferrable:
            # Retrieval would consume the memory-write reserve. Refuse and
            # signal that a synchronous flush is required before retry.
            raise BudgetConflictError(
                f"retrieval of {request_tokens} tokens would starve "
                f"{self.pending_memory_write_tokens} pending memory-write tokens; "
                f"flush memory writes before re-admitting retrieval"
            )
        if not deferrable:
            # Non-deferrable retrieval: flush must happen out-of-band first.
            raise BudgetConflictError(
                "non-deferrable retrieval cannot be admitted while memory "
                "writes are pending; flush required"
            )
        return False

    def maybe_compact(self) -> bool:
        if self.pending_memory_write_tokens > 0:
            raise BudgetConflictError(
                "compaction refused: pending memory writes would be evicted"
            )
        if self.used >= self.compaction_threshold:
            self.used = 0
            return True
        return False
