# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-allocate-context-budget-across-a-delegated-sub-agent-boundary-the-attention-floor-starvation-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-allocate-context-budget-across-a-delegated-sub-agent-boundary-the-attention-floor-starvation-invariant.warrant.json
# Markdown SHA-256:   ec4de1ee3d4989b6dcdebb16182597456411d4e9e91842ee2135fd9fa3ccd7e2
# Code AST SHA-256:   c39864424f1cff8bb157f40ce86ea2d22aa6423347c7860580216c8db0f87821
# Verified Classes:   AttentionFloorStarvationError, DispatchContract
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AttentionFloorStarvationError(RuntimeError):
    """Raised when a child is dispatched below its contract's attention floor."""
    pass


@dataclass(frozen=True)
class DispatchContract:
    agent_id: str
    scratch_tokens: int
    tool_headroom_tokens: int
    synthesis_tokens: int

    @property
    def floor(self) -> int:
        return self.scratch_tokens + self.tool_headroom_tokens + self.synthesis_tokens


def allocate_budget(
    parent_window: int,
    overhead: int,
    contracts: list[DispatchContract],
    weights: list[float],
) -> dict[str, int]:
    """Proportional allocation with a hard per-child floor gate.

    Sum feasibility is checked first; then every slice is checked against the
    floor implied by the contract actually being dispatched. A slice that is
    positive but below floor is the starvation bug and must not ship.
    """
    if len(contracts) != len(weights):
        raise AttentionFloorStarvationError("contracts/weights length mismatch")

    available = parent_window - overhead
    total_weight = sum(weights)
    if total_weight <= 0:
        raise AttentionFloorStarvationError("non-positive total weight")

    slices = {c.agent_id: int(available * w / total_weight) for c, w in zip(contracts, weights)}

    if sum(slices.values()) > available:
        raise AttentionFloorStarvationError(
            f"sum infeasible: {sum(slices.values())} > {available}"
        )

    # The non-obvious invariant: positivity is not feasibility.
    starved = [
        c.agent_id for c in contracts if slices[c.agent_id] < c.floor
    ]
    if starved:
        raise AttentionFloorStarvationError(
            f"attention-floor starvation for {starved}: "
            f"slices below per-contract floor; rebalance or downgrade contracts"
        )

    return slices


def plan_fanout(parent_window: int, contracts: list[DispatchContract]) -> dict[str, int]:
    """Try proportional; on starvation, reduce fanout rather than truncate."""
    weights = [float(c.floor) for c in contracts]  # floor-proportional
    try:
        return allocate_budget(parent_window, overhead=parent_window // 20, contracts=contracts, weights=weights)
    except AttentionFloorStarvationError:
        # Degrade: drop the largest-floor contract and retry, logging the drop.
        if len(contracts) <= 1:
            raise AttentionFloorStarvationError(
                "cannot satisfy even a single contract within parent window"
            )
        trimmed = sorted(contracts, key=lambda c: c.floor)[:-1]
        return plan_fanout(parent_window, trimmed)
