# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-context-window-allocation-as-a-per-subtask-reservation-system-rather-than-a-single-global-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-context-window-allocation-as-a-per-subtask-reservation-system-rather-than-a-single-global-budget.warrant.json
# Markdown SHA-256:   379ca3b0d74babb63b1885806571466fe91d03c3714a716d5bc21a9b4f33a542
# Code AST SHA-256:   c7161dcbfd93254ec3ed266f3b7fd7e645af4d4f66f93d15bb298719c1ee3360
# Verified Classes:   ReservationTheftError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ReservationTheftError(RuntimeError):
    """Raised when a subtask's materialized input would consume tokens
    reserved for a later, not-yet-executed subtask, or when generation
    would evict already-materialized reserved content."""
    pass


def allocate_subtask(
    subtask_id: str,
    requested_tokens: int,
    window_size: int,
    forward_reservations: dict[str, int],
    safety_margin: int,
) -> int:
    """Return the token allotment a subtask may materialize.

    forward_reservations maps every *pending* downstream subtask id to the
    tokens it has reserved. Those tokens are unavailable to the caller.
    """
    if subtask_id in forward_reservations:
        raise ReservationTheftError(
            f"subtask {subtask_id!r} is consuming its own reservation; "
            "reservations are held by pending subtasks, not the running one"
        )

    reserved_total = sum(forward_reservations.values())
    available = window_size - reserved_total - safety_margin

    if available < 0:
        raise ReservationTheftError(
            f"forward reservations ({reserved_total}) plus margin "
            f"({safety_margin}) exceed window ({window_size}); "
            "decomposition is infeasible and must be restructured, "
            "not shrunk proportionally"
        )

    if requested_tokens > available:
        raise ReservationTheftError(
            f"subtask {subtask_id!r} requested {requested_tokens} tokens "
            f"but only {available} are unreserved; it must externalize "
            "its intermediate product instead of borrowing from "
            f"downstream reservations {list(forward_reservations)}"
        )

    return requested_tokens


def assert_no_eviction(
    materialized: dict[str, int],
    reserved_ids: set[str],
    eviction_candidates: list[str],
) -> None:
    """Before any truncation, verify no reserved subtask's content is evicted."""
    for victim in eviction_candidates:
        if victim in reserved_ids:
            raise ReservationTheftError(
                f"truncation would evict reserved content for {victim!r}; "
                "silent positional eviction of reserved input is the "
                "omission defect this invariant exists to prevent"
            )
