# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reserve-retrieval-budget-before-committing-to-an-slo-bearing-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reserve-retrieval-budget-before-committing-to-an-slo-bearing-tool-call.warrant.json
# Markdown SHA-256:   48b60de91c2cb3c011d72f524129efec35ea2ffecc23b8a79e1e7d6bc698c2b8
# Code AST SHA-256:   e300caf8039e483a9e18483de5a512dea7f039dbbd7c6a0a009f258a50f904bc
# Verified Classes:   RetrievalBudgetViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RetrievalBudgetViolation(RuntimeError):
    """Raised when a retrieval payload or reservation breaks the pre-commitment invariant."""
    pass


def reserve_and_dispatch(
    tokens_used: int,
    window: int,
    k: int,
    max_chunk_tokens: int,
    w_reasoning: int,
    w_emit: int,
    w_margin: int = 512,
) -> int:
    """
    Compute the pre-dispatch reservation. Returns the per-chunk cap to pass
    into the retriever. Fails closed if no valid cap exists.
    """
    w_retrieval_max = k * max_chunk_tokens
    reservation = w_retrieval_max + w_reasoning + w_emit + w_margin

    if tokens_used + reservation <= window:
        return max_chunk_tokens  # full cap is affordable

    # Shrink the per-chunk cap so the reservation fits, never truncate after return.
    available_for_retrieval = window - tokens_used - w_reasoning - w_emit - w_margin
    if available_for_retrieval <= 0:
        raise RetrievalBudgetViolation(
            f"no headroom for retrieval: used={tokens_used} window={window} "
            f"reasoning={w_reasoning} emit={w_emit} margin={w_margin}"
        )

    per_chunk_cap = available_for_retrieval // k
    if per_chunk_cap < 1:
        raise RetrievalBudgetViolation(
            f"per-chunk cap collapsed to {per_chunk_cap} with k={k}; reduce k"
        )
    return per_chunk_cap


def verify_returned_payload(payload_tokens: int, reserved_max: int) -> None:
    """Guardrail: a cap-violating retriever must surface, not silently degrade."""
    if payload_tokens > reserved_max:
        raise RetrievalBudgetViolation(
            f"retriever returned {payload_tokens} tokens, reservation was {reserved_max}; "
            "cap was ignored — do not truncate, re-dispatch with enforced cap"
        )
