# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-under-a-priority-weighted-context-governor-starves-a-low-weight-subagent-s-reserved-floor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-under-a-priority-weighted-context-governor-starves-a-low-weight-subagent-s-reserved-floor.warrant.json
# Markdown SHA-256:   dd4594a7ca512493a4df34e66488ff28bf21ae1b3df015256a4340b63ef1fa44
# Code AST SHA-256:   ee4f4ba2ad7efff7f355f3a78196578a6a89ea804d981dd26b65614cf4a30e73
# Verified Classes:   FloorViolationError, Subagent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class FloorViolationError(RuntimeError):
    """Raised when a priority-weighted allocation cannot honor a subagent's declared minimum-viable floor."""
    pass


@dataclass(frozen=True)
class Subagent:
    name: str
    weight: float
    min_viable: int  # prompt overhead + max input + min terminating output


def allocate(pool: int, agents: list[Subagent]) -> dict[str, int]:
    if not agents:
        return {}

    total_floor = sum(a.min_viable for a in agents)
    if total_floor > pool:
        # Admission control must reject, not admit-and-starve.
        raise FloorViolationError(
            f"pool={pool} cannot cover sum(min_viable)={total_floor}; "
            f"refuse admission of lowest-weight subagents before allocating"
        )

    total_weight = sum(a.weight for a in agents)
    if total_weight <= 0:
        raise FloorViolationError("weights must sum to a positive value")

    # Floor-first: every agent gets its floor, surplus is split by weight.
    surplus = pool - total_floor
    shares = {
        a.name: a.min_viable + int(surplus * (a.weight / total_weight))
        for a in agents
    }

    # Rebalance any rounding remainder without dropping below floors.
    remainder = pool - sum(shares.values())
    if remainder > 0:
        order = sorted(agents, key=lambda a: a.weight, reverse=True)
        for i in range(remainder):
            shares[order[i % len(order)].name] += 1

    # Invariant check: no live subagent below its floor.
    for a in agents:
        if shares[a.name] < a.min_viable:
            raise FloorViolationError(
                f"subagent {a.name!r} allocated {shares[a.name]} < floor {a.min_viable}"
            )
    return shares


def allocate_or_serialize(pool: int, agents: list[Subagent]) -> dict[str, int]:
    try:
        return allocate(pool, agents)
    except FloorViolationError:
        # Caller must decide: serialize, shrink inputs, or drop. Do not retry blindly.
        raise FloorViolationError(
            "weighted allocation infeasible; orchestrator must serialize or shrink inputs, "
            "not re-queue with identical weights"
        )
