# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-admission-control-when-concurrent-sub-agents-compete-for-a-shared-context-budget-it-cannot-measure-atomically.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-admission-control-when-concurrent-sub-agents-compete-for-a-shared-context-budget-it-cannot-measure-atomically.warrant.json
# Markdown SHA-256:   6c2d5774ce917b23c6030d4807a238ae314973cfd8d6d034c6a2f46021fc9635
# Code AST SHA-256:   20376a326fed8c611d5f3d5863e1da07a23f6a7bca145ab26fd2f7f40c66b53a
# Verified Classes:   ContextBudgetOvercommitError, BudgetLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ContextBudgetOvercommitError(RuntimeError):
    """Raised when admitting a sub-agent would exceed the shared context budget
    under worst-case post-admission growth, not initial footprint."""
    pass


class BudgetLedger:
    def __init__(self, total_budget: int, orchestrator_reserve: int):
        self.total = total_budget
        self.orchestrator_reserve = orchestrator_reserve
        self.admitted = {}  # agent_id -> reserved ceiling
        self._lock = threading.Lock()

    def _admitted_sum(self) -> int:
        return sum(self.admitted.values())

    def free_for_admission(self) -> int:
        return self.total - self.orchestrator_reserve - self._admitted_sum()

    def admit(self, agent_id: str, growth_ceiling: int) -> None:
        # growth_ceiling must be derived from tool response bounds * retry cap,
        # NOT from the agent's initial prompt footprint.
        with self._lock:
            free = self.free_for_admission()
            if growth_ceiling > free:
                raise ContextBudgetOvercommitError(
                    f"admission of {agent_id} with ceiling {growth_ceiling} "
                    f"exceeds free budget {free} "
                    f"(total={self.total}, reserve={self.orchestrator_reserve}, "
                    f"admitted={self._admitted_sum()})"
                )
            self.admitted[agent_id] = growth_ceiling

    def release(self, agent_id: str) -> None:
        with self._lock:
            self.admitted.pop(agent_id, None)


def derive_growth_ceiling(initial_tokens: int, max_tool_response: int | None,
                          retry_cap: int) -> int:
    if max_tool_response is None:
        # Unbounded tool => unbounded ceiling => must serialize.
        raise ContextBudgetOvercommitError(
            "cannot derive finite ceiling: tool response is unbounded; "
            "serialize this sub-agent or impose a transport-layer cap"
        )
    return initial_tokens + (max_tool_response * retry_cap)
