# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-starves-its-sibling-token-budget-reservation-collapse-under-concurrent-sub-agent-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-starves-its-sibling-token-budget-reservation-collapse-under-concurrent-sub-agent-fan-out.warrant.json
# Markdown SHA-256:   85a3a277dbf19821f2c34dcfd093d2ec32183cb965d83ccda98f731fb3d8576c
# Code AST SHA-256:   c5a76dc85d5f507a0453b792e195ccb8f7bb4c126d0cdc729235662195266f73
# Verified Classes:   BudgetStarvationError, Reservation, SharedPool
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class BudgetStarvationError(RuntimeError):
    """Raised when a sub-agent's effective token ceiling is below its committed plan."""


@dataclass
class Reservation:
    agent_id: str
    floor: int          # hard, physically removed from pool
    borrowed: int = 0   # opt-in only, requires declaration
    consumed: int = 0
    provisional: bool = False


@dataclass
class SharedPool:
    total: int
    reservations: Dict[str, Reservation] = field(default_factory=dict)

    def reserved(self) -> int:
        return sum(r.floor for r in self.reservations.values())

    def residual(self) -> int:
        return self.total - self.reserved() - sum(r.borrowed for r in self.reservations.values())

    def spawn(self, agent_id: str, floor: int) -> Reservation:
        if self.reserved() + floor > self.total:
            raise BudgetStarvationError(
                f"cannot reserve {floor} for {agent_id}: "
                f"{self.reserved()} already reserved of {self.total}"
            )
        r = Reservation(agent_id=agent_id, floor=floor)
        self.reservations[agent_id] = r
        return r

    def declare_borrow(self, borrower: str, lender: str, amount: int) -> None:
        if amount > self.residual():
            raise BudgetStarvationError(
                f"{borrower} requested borrow {amount} exceeding residual {self.residual()}"
            )
        b = self.reservations[borrower]
        b.borrowed += amount
        b.provisional = True  # borrower's output now tainted until re-validated
        # lender is now at risk of starvation; mark it so the parent gates on it
        self.reservations[lender].provisional = True

    def consume(self, agent_id: str, tokens: int) -> None:
        r = self.reservations[agent_id]
        ceiling = r.floor + r.borrowed
        if r.consumed + tokens > ceiling:
            raise BudgetStarvationError(
                f"{agent_id} would exceed ceiling {ceiling} "
                f"(consumed {r.consumed}, requested {tokens}); "
                f"compact or raise, do not truncate silently"
            )
        r.consumed += tokens

    def all_clean(self) -> bool:
        return all(not r.provisional for r in self.reservations.values())


def run_fanout(pool: SharedPool, plan: List[tuple]) -> None:
    """plan: list of (agent_id, floor, planned_tokens)."""
    for agent_id, floor, planned in plan:
        pool.spawn(agent_id, floor)
        if planned > floor:
            # The child committed to a plan larger than its floor.
            # We must refuse rather than let it borrow implicitly.
            raise BudgetStarvationError(
                f"{agent_id} planned {planned} tokens but only {floor} reserved; "
                f"declare an explicit borrow or reduce plan"
            )
    for agent_id, _, planned in plan:
        pool.consume(agent_id, planned)
