# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-promotes-a-memory-page-it-cannot-demote-model-controlled-tier-churn-and-the-eviction-inversion-deadlock-in-memgpt-style.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-promotes-a-memory-page-it-cannot-demote-model-controlled-tier-churn-and-the-eviction-inversion-deadlock-in-memgpt-style.warrant.json
# Markdown SHA-256:   2c7bdf0328c56d019462035e1232e08694db8ed2a4ebe0619d0eb24a8dedca3a
# Code AST SHA-256:   6297a66379d73fd856b5dc3ce4c1dcd13bd298744a4b8317e757d0e3800e5bbf
# Verified Classes:   EvictionInversionError, PagingTier
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class EvictionInversionError(RuntimeError):
    """Raised when a promotion demand cannot be satisfied because the
    demotable supply is empty due to model-authored pins."""
    pass


class PagingTier:
    def __init__(self, budget_tokens: int, pin_fraction_cap: float = 0.5):
        self.budget = budget_tokens
        self.pin_cap = int(budget_tokens * pin_fraction_cap)
        self.pages = {}          # id -> {"tokens": int, "pinned": bool}
        self.used = 0

    def pin_manifest(self):
        return {pid: p["tokens"] for pid, p in self.pages.items() if p["pinned"]}

    def demotable(self):
        return {pid: p["tokens"] for pid, p in self.pages.items() if not p["pinned"]}

    def pin(self, pid: str):
        page = self.pages[pid]
        pinned_tokens = sum(self.pin_manifest().values()) + page["tokens"]
        if pinned_tokens > self.pin_cap:
            raise EvictionInversionError(
                f"pin of {pid} would leave demotable supply below safety floor; "
                f"pinned={pinned_tokens} cap={self.pin_cap}"
            )
        page["pinned"] = True

    def page_out(self, pid: str):
        page = self.pages.get(pid)
        if page is None:
            raise EvictionInversionError(f"page_out on unknown page {pid}")
        if page["pinned"]:
            # self-healing rejection: surface manifest + a concrete victim
            victims = self.demotable()
            hint = next(iter(victims), None)
            raise EvictionInversionError(
                f"cannot demote pinned page {pid}; "
                f"demotable={list(victims)}; suggested_victim={hint}; "
                f"pin_manifest={self.pin_manifest()}"
            )
        self.used -= page["tokens"]
        del self.pages[pid]

    def page_in(self, pid: str, tokens: int):
        if not self.demotable():
            raise EvictionInversionError(
                f"promotion of {pid} impossible: demotable set empty "
                f"(eviction inversion); pinned={self.pin_manifest()}"
            )
        if self.used + tokens > self.budget:
            raise EvictionInversionError(
                f"promotion of {pid} exceeds budget; demote first. "
                f"demotable={list(self.demotable())}"
            )
        self.pages[pid] = {"tokens": tokens, "pinned": False}
        self.used += tokens


def guarded_promote(tier: PagingTier, pid: str, tokens: int) -> None:
    """Refuse promotion at request time if inversion is already latent,
    rather than after the model has committed reasoning to the load."""
    if not tier.demotable():
        raise EvictionInversionError(
            f"refusing page_in({pid}) before reasoning commit: "
            f"no demotable pages remain; model must unpin or runtime must evict"
        )
    tier.page_in(pid, tokens)
