# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quota-allocators-from-starving-the-tool-call-that-resolves-the-task.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quota-allocators-from-starving-the-tool-call-that-resolves-the-task.warrant.json
# Markdown SHA-256:   5da95af41a7d0fd6c5308c677c888763a5482985dc5510494284da40afd4ac9b
# Code AST SHA-256:   91d65c82d005768c3291a8f70136735fdef5d52083d8bf964c2bf2cc182da47f
# Verified Classes:   QuotaStarvationError, BudgetAllocator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class QuotaStarvationError(RuntimeError):
    """Raised when a re-plan after denial would increase planned overhead,
    feeding the allocator loop that starves the resolving call."""
    pass


class BudgetAllocator:
    def __init__(self, agent_quota: int, tool_quotas: dict[str, int]):
        self.agent_quota = agent_quota
        self.tool_quotas = tool_quotas
        self.committed = 0
        self.tool_committed = {t: 0 for t in tool_quotas}
        self._last_planned_overhead = 0

    def reserve(self, tool: str, payload: int, planned_overhead: int) -> str:
        # Invariant: overhead may not grow across a denial-retry cycle.
        if planned_overhead > self._last_planned_overhead and self._last_planned_overhead > 0:
            raise QuotaStarvationError(
                f"retry grew planned_overhead {self._last_planned_overhead}->{planned_overhead}; "
                f"this retry would consume the budget it is trying to free"
            )

        total = self.committed + planned_overhead + payload
        tool_total = self.tool_committed[tool] + payload

        if total > self.agent_quota or tool_total > self.tool_quotas[tool]:
            # Terminal: cannot fit even with declared overhead.
            self._last_planned_overhead = planned_overhead
            return "QuotaExceeded"

        remaining_agent = self.agent_quota - total
        if remaining_agent < 0.15 * self.agent_quota:
            # Non-terminal: fits, but tight. Agent may retry once, smaller, no extra overhead.
            self._last_planned_overhead = planned_overhead
            return "QuotaTight"

        self.committed += planned_overhead + payload
        self.tool_committed[tool] += payload
        self._last_planned_overhead = planned_overhead
        return "Granted"

    def settle(self, tool: str, actual: int) -> None:
        # Reconcile reservation against actual usage; actual may exceed payload.
        self.committed += max(0, actual - self.tool_committed[tool])
        self.tool_committed[tool] = max(self.tool_committed[tool], actual)


def run_retry_cycle(alloc: BudgetAllocator, tool: str, payload: int, overhead: int) -> str:
    decision = alloc.reserve(tool, payload, overhead)
    if decision == "QuotaExceeded":
        # Terminal: summarize with what we have; do not re-plan larger.
        return "summarize_partial"
    if decision == "QuotaTight":
        # One retry, strictly smaller, no added overhead.
        return alloc.reserve(tool, payload // 2, overhead)
    return decision
