# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reserve-headroom-against-a-retrieval-flood-before-committing-scratchpad-state-and-why-the-naive-allocator-fails-at-the-exact-bo.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reserve-headroom-against-a-retrieval-flood-before-committing-scratchpad-state-and-why-the-naive-allocator-fails-at-the-exact-bo.warrant.json
# Markdown SHA-256:   fdf1a76a9994db423e467fedf49736fd067af064f12cee004d0f839425e7e019
# Code AST SHA-256:   9681cee19bbdace6ca7e6c26c4ac70e79f7da194bbe0fddf912d60d578589f98
# Verified Classes:   ScratchpadEvictionWithoutCheckpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScratchpadEvictionWithoutCheckpoint(RuntimeError):
    """Raised when an allocator would evict scratchpad state that has no durable checkpoint."""
    pass


def admit_retrieval(payload_tokens: int,
                    ceiling: int,
                    scratchpad_used: int,
                    scratchpad_floor: int,
                    persistent_reserve: int,
                    checkpoint_confirmed: bool) -> int:
    """
    Returns the number of payload tokens that may be admitted.
    Raises if admission would require evicting uncheckpointed scratchpad.
    """
    residual = ceiling - scratchpad_floor - persistent_reserve
    if payload_tokens <= residual:
        return payload_tokens

    # Overrun: we must reclaim from somewhere. Scratchpad is only reclaimable
    # down to its floor, and only if the excess above floor is checkpointed.
    reclaimable = max(0, scratchpad_used - scratchpad_floor)
    if reclaimable > 0 and not checkpoint_confirmed:
        raise ScratchpadEvictionWithoutCheckpoint(
            f"retrieval payload {payload_tokens} exceeds residual {residual}; "
            f"would evict {reclaimable} uncheckpointed scratchpad tokens"
        )

    # Safe path: truncate retrieval to the residual instead of touching scratchpad.
    admitted = residual
    if admitted <= 0:
        raise ScratchpadEvictionWithoutCheckpoint(
            "no residual capacity; retrieval must be deferred to a sub-call"
        )
    return admitted
