# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-context-budget-arbiters-from-starving-a-re-entrant-agent-during-shared-memory-contention.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-context-budget-arbiters-from-starving-a-re-entrant-agent-during-shared-memory-contention.warrant.json
# Markdown SHA-256:   5c8049a13d398e1f39f73fcc64aba4d027c770f5a0d66082d5d5e5c2238521e5
# Code AST SHA-256:   d474c19c2fc1cca57041becb1cce945b9d9fe4bf13e335fcf7e16239fe70dc2f
# Verified Classes:   LeaseViolation, Block, BudgetArbiter
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class LeaseViolation(RuntimeError):
    """Raised when a reclamation or read violates write-lease durability."""
    pass


class Block:
    def __init__(self, owner, tokens, lease_open, epoch):
        self.owner = owner
        self.tokens = tokens
        self.lease_open = lease_open
        self.epoch = epoch


class BudgetArbiter:
    def __init__(self, reentrant_agents):
        # agents declared re-entrant at registration
        self.reentrant = set(reentrant_agents)

    def reclaimable(self, block, requester, now_lease_expired):
        """A block is peer-reclaimable only if no live open lease protects it."""
        if block.lease_open and not now_lease_expired:
            if block.owner in self.reentrant and block.owner != requester:
                return False  # durability invariant: peer cannot reclaim
            if block.owner == requester:
                return True   # owner-scoped eviction always allowed
        return True

    def reclaim(self, blocks, requester, budget_needed, now_lease_expired):
        freed = 0
        for b in sorted(blocks, key=lambda x: x.epoch):
            if freed >= budget_needed:
                break
            if self.reclaimable(b, requester, now_lease_expired):
                freed += b.tokens
                b.lease_open = False
        if freed < budget_needed:
            # cannot satisfy peer demand without breaking durability
            raise LeaseViolation(
                f"requester={requester} needs {budget_needed} tokens but only "
                f"{freed} peer-reclaimable; durable leases reserve the rest"
            )
        return freed

    def read(self, block, requester, presented_epoch):
        if block.owner != requester:
            raise LeaseViolation(
                f"{requester} attempted to read block owned by {block.owner}"
            )
        if presented_epoch != block.epoch:
            raise LeaseViolation(
                f"stale epoch: {requester} holds epoch {presented_epoch}, "
                f"block is at {block.epoch}; checkpoint was reclaimed"
            )
        return block
