# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-context-budget-arbiters-from-double-spending-reclaimed-tokens-during-concurrent-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-context-budget-arbiters-from-double-spending-reclaimed-tokens-during-concurrent-compaction.warrant.json
# Markdown SHA-256:   96e87123e3b9cbe7cf13124e99e9adb63a09a70a5b82a042c8ed6048ca2a3382
# Code AST SHA-256:   70f0533d107a5dc351bf3c7ae1547a9bf9f2fef941afd937f18966bb3f95ba14
# Verified Classes:   BudgetDoubleSpendError, ContextBudgetArbiter
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class BudgetDoubleSpendError(RuntimeError):
    """Raised when an allocation would draw against unrealized reclaim."""
    pass


class ContextBudgetArbiter:
    def __init__(self, ceiling: int, orchestrator_reserve: int):
        self.ceiling = ceiling
        self.reserve = orchestrator_reserve
        self.realized = {}          # agent_id -> physical tokens committed
        self.pending = {}           # compaction_id -> projected reclaim (lower bound)
        self.shortfall = 0          # accumulated under-realization, charged forward

    def _spendable(self) -> int:
        used = sum(self.realized.values()) + self.reserve
        # PENDING is deliberately excluded: it is a reservation, not capacity.
        return max(0, self.ceiling - used - self.shortfall)

    def request(self, agent_id: str, amount: int) -> bool:
        if amount < 0:
            raise BudgetDoubleSpendError(f"negative request from {agent_id}")
        if amount > self._spendable():
            # Queue, do not grant against projection.
            return False
        self.realized[agent_id] = self.realized.get(agent_id, 0) + amount
        return True

    def begin_compaction(self, agent_id: str, compaction_id: str,
                         estimate: int, summarizer_cap: int) -> int:
        # Projection must be a hard lower bound.
        projected = min(estimate, summarizer_cap)
        if projected <= 0:
            raise BudgetDoubleSpendError(
                f"compaction {compaction_id} has non-positive bound")
        self.pending[compaction_id] = projected
        return projected

    def commit_compaction(self, compaction_id: str, realized_reclaim: int,
                          new_footprint: int, agent_id: str) -> None:
        projected = self.pending.pop(compaction_id, None)
        if projected is None:
            raise BudgetDoubleSpendError(
                f"commit for unknown compaction {compaction_id}")
        if realized_reclaim < projected:
            # Under-realization: charge the shortfall forward, never revoke.
            self.shortfall += (projected - realized_reclaim)
        self.realized[agent_id] = new_footprint

    def reconcile(self) -> None:
        # Shortfall decays only as genuine surplus is realized.
        if self._spendable() > self.shortfall:
            self.shortfall = 0


def grant_or_checkpoint(arbiter: ContextBudgetArbiter, agent_id: str,
                        amount: int) -> str:
    if not arbiter.request(agent_id, amount):
        raise BudgetDoubleSpendError(
            f"agent {agent_id} requested {amount} tokens with no realized "
            f"headroom; checkpoint state and re-request after compaction "
            f"commit (shortfall={arbiter.shortfall})")
    return "granted"
