# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-budget-reallocation-from-evicting-the-instruction-that-authorizes-the-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-budget-reallocation-from-evicting-the-instruction-that-authorizes-the-eviction.warrant.json
# Markdown SHA-256:   ad8545c613c990cb18aff564bb3030e107c4a8aed8b9b05437bd4c4051b1de4b
# Code AST SHA-256:   00b0b0a56612739dac908d640bb6797a350ccd6a92a3a1981dbe368dc14fb99f
# Verified Classes:   Partition, AllocatorSelfEvictionError, Anchor, BudgetState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class Partition(Enum):
    INSTRUCTIONS = "I"
    MEMORY = "M"
    TOOL_SCHEMAS = "S"


class AllocatorSelfEvictionError(RuntimeError):
    """Raised when a reclamation step would leave a partition anchor-incomplete
    or evict a schema the current plan depends on."""


@dataclass
class Anchor:
    anchor_id: str
    partition: Partition
    tokens: int
    indivisible: bool = True


@dataclass
class BudgetState:
    window: int
    anchors: list[Anchor] = field(default_factory=list)
    plan_tools: set[str] = field(default_factory=set)

    def used(self) -> int:
        return sum(a.tokens for a in self.anchors)

    def pressure(self) -> float:
        return self.used() / self.window

    def anchors_in(self, p: Partition) -> list[Anchor]:
        return [a for a in self.anchors if a.partition is p]


def reclaim(state: BudgetState, target_tokens: int, order: list[Partition]) -> BudgetState:
    """Reclaim tokens by dropping anchors in the given partition order.

    Invariant: a reclamation step is legal only if, after it, every partition
    that still has any anchor retains its full anchor set for the active plan,
    and no schema referenced by the plan is evicted. Aggregate token floors are
    insufficient; floors are checked per-partition against anchor completeness.
    """
    freed = 0
    surviving = list(state.anchors)
    for part in order:
        for anchor in state.anchors_in(part):
            if freed >= target_tokens:
                break
            if anchor.indivisible and anchor.anchor_id in state.plan_tools:
                raise AllocatorSelfEvictionError(
                    f"refusing to evict plan-critical anchor {anchor.anchor_id!r} "
                    f"in partition {part.value}; escalate instead of reclaiming"
                )
            surviving.remove(anchor)
            freed += anchor.tokens
            remaining = [a for a in surviving if a.partition is part]
            if not remaining:
                raise AllocatorSelfEvictionError(
                    f"reclamation emptied partition {part.value}; "
                    f"anchor-complete floor violated, escalate to BudgetExhausted"
                )
        if freed >= target_tokens:
            break
    if freed < target_tokens:
        raise AllocatorSelfEvictionError(
            f"cannot free {target_tokens} tokens without violating an invariant; "
            f"freed {freed}; abort task with BudgetExhausted"
        )
    return BudgetState(window=state.window, anchors=surviving, plan_tools=state.plan_tools)


def allocate_under_pressure(state: BudgetState, target_tokens: int) -> BudgetState:
    # Memory first, then schemas, instructions last — but every step is guarded.
    return reclaim(state, target_tokens, [Partition.MEMORY, Partition.TOOL_SCHEMAS, Partition.INSTRUCTIONS])
