# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-arbitrate-context-budget-across-concurrent-subagents-and-where-must-it-refuse.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-arbitrate-context-budget-across-concurrent-subagents-and-where-must-it-refuse.warrant.json
# Markdown SHA-256:   f10a7cf696f920ae30877116a53aff8b1c9f91e584dac2c223ab42658e68aa75
# Code AST SHA-256:   4a66f73bd7bc861e1dd1f625b367220b1589be2c94624f25e0b9183b1e6007d1
# Verified Classes:   ContextBudgetInvariantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ContextBudgetInvariantError(RuntimeError):
    """Raised when concurrent subagent admission would violate a completion contract."""
    pass


def admit_subagent(
    child_id: str,
    minimum_viable_budget: int,
    admitted: dict[str, int],
    window_tokens: int,
    parent_reserved_headroom: int,
) -> dict[str, int]:
    """Admit a child only if the joint MVB of all children plus parent headroom fits.

    Returns the updated admission map. Raises rather than admitting a child that
    cannot be granted its minimum viable budget, because a sub-MVB child emits
    confidently wrong output instead of failing loudly.
    """
    if minimum_viable_budget <= 0:
        raise ContextBudgetInvariantError(
            f"child {child_id!r} has non-positive MVB {minimum_viable_budget}; "
            "completion threshold must be computed before admission"
        )

    prospective = dict(admitted)
    prospective[child_id] = minimum_viable_budget

    committed = sum(prospective.values()) + parent_reserved_headroom
    if committed > window_tokens:
        raise ContextBudgetInvariantError(
            f"cannot admit {child_id!r}: joint MVB {committed} exceeds window "
            f"{window_tokens} (parent headroom {parent_reserved_headroom}). "
            "Serialize the child or narrow its scope; do not run it degraded."
        )

    return prospective


def allocate_residual(
    admitted: dict[str, int],
    window_tokens: int,
    parent_reserved_headroom: int,
    priority: dict[str, int],
) -> dict[str, int]:
    """Grant each child its MVB floor, then distribute residual by priority weight."""
    residual = window_tokens - parent_reserved_headroom - sum(admitted.values())
    if residual < 0:
        raise ContextBudgetInvariantError(
            f"residual budget {residual} is negative; admission invariant was bypassed"
        )
    total_weight = sum(priority.get(c, 1) for c in admitted) or 1
    grants = {}
    for child, floor in admitted.items():
        share = residual * priority.get(child, 1) // total_weight
        grants[child] = floor + share
    return grants
