# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-arbitrate-a-shared-context-budget-when-concurrent-subagents-reservations-are-individually-satisfiable-but-jointly-infeasible.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-arbitrate-a-shared-context-budget-when-concurrent-subagents-reservations-are-individually-satisfiable-but-jointly-infeasible.warrant.json
# Markdown SHA-256:   34a77b578c05361701ea703bfb3a6a85632feb8f683fee2f710c50cffd1c3d4e
# Code AST SHA-256:   6b2ad980509679e967cf17e6f964df91489eb916e7a897629a41d40824b7260c
# Verified Classes:   JointContextInfeasible, SubagentReservation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class JointContextInfeasible(RuntimeError):
    """Raised when a concurrent subagent batch is individually admissible
    but jointly exceeds the shared parent context ceiling."""
    pass


@dataclass
class SubagentReservation:
    name: str
    reserved_tokens: int          # declared point estimate
    shared_prefix_tokens: int     # per-agent cost of re-materialized parent context
    estimate_error_margin: int    # bounded upper margin, NOT zero
    hard_cap_tokens: int          # wall the subagent cannot exceed

    def upper_bound(self) -> int:
        return (
            self.reserved_tokens
            + self.shared_prefix_tokens
            + self.estimate_error_margin
        )


def arbitrate_batch(
    batch: list[SubagentReservation],
    free_tokens: int,
    parent_reserve: int,
    concurrent: bool,
) -> None:
    # Serial fan-out: per-request greedy admission is sound.
    if not concurrent:
        for r in batch:
            if r.upper_bound() > free_tokens:
                raise JointContextInfeasible(
                    f"{r.name} upper bound {r.upper_bound()} exceeds free {free_tokens}"
                )
            free_tokens -= r.upper_bound()
        return

    # Concurrent fan-out: set-level arbitration. A subset admission is NOT
    # safe because admitting fewer agents changes shared-prefix accounting
    # for the rest. Reject the whole batch or none.
    joint = sum(r.upper_bound() for r in batch)
    available = free_tokens - parent_reserve

    if joint > available:
        raise JointContextInfeasible(
            f"batch of {len(batch)} jointly needs {joint} tokens "
            f"(upper bounds incl. shared prefix + error margin) but only "
            f"{available} available after parent reserve {parent_reserve}. "
            f"Per-request checks would each pass; joint check fails. "
            f"Defer or serialize the batch — do not admit a subset."
        )

    # Enforce hard caps: a reservation the reasoning loop can overrun is
    # not a guarantee. The context manager must wall at hard_cap_tokens.
    for r in batch:
        if r.hard_cap_tokens < r.reserved_tokens:
            raise JointContextInfeasible(
                f"{r.name} hard cap {r.hard_cap_tokens} below its own "
                f"reservation {r.reserved_tokens}; scratchpad can silently "
                f"overrun the reservation and re-invalidate the joint check."
            )
