# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-context-budget-exhaustion-as-a-retrieval-arbitration-failure-rather-than-a-truncation-event.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-context-budget-exhaustion-as-a-retrieval-arbitration-failure-rather-than-a-truncation-event.warrant.json
# Markdown SHA-256:   71c5d4f2b4df18dacd2b39e0b2dd57b47877f8a1e148c16ee0c3b3eb29993fb2
# Code AST SHA-256:   9412c5a6cff7285079caf344574a325596ce921add2bfd89da0ba1537ff3b0b6
# Verified Classes:   ContextArbitrationError, Allocation, BudgetPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ContextArbitrationError(RuntimeError):
    """Raised when context-budget arbitration violates a producer floor."""
    pass


@dataclass
class Allocation:
    retrieval_k: int
    memory_chunks: int
    tool_tokens: int
    total_tokens: int
    budget: int


@dataclass
class BudgetPolicy:
    budget: int
    k_min: int = 2                 # minimum viable retrieval chunks
    memory_floor_tokens: int = 1024
    starvation_utilization: float = 0.85


def arbitrate(
    policy: BudgetPolicy,
    retrieval_candidates: int,
    memory_tokens: int,
    tool_result_tokens: int,
    chunk_tokens: int = 750,
) -> Allocation:
    # Reserve floors BEFORE greedy fill. Live tool results are the only
    # producer we do not control, so they absorb the residual, not the floor.
    retrieval_floor = policy.k_min * chunk_tokens
    reserved = retrieval_floor + policy.memory_floor_tokens

    if reserved >= policy.budget:
        raise ContextArbitrationError(
            f"reserved floors ({reserved}) exceed budget ({policy.budget}); "
            "policy is unsatisfiable and must not silently degrade to k=0"
        )

    residual = policy.budget - reserved

    # Tool results take from residual only; overflow is spilled, never
    # allowed to eat the floors.
    tool_admitted = min(tool_result_tokens, residual)
    residual -= tool_admitted

    # Retrieval may grow above its floor using leftover residual.
    extra_k = min(retrieval_candidates - policy.k_min, residual // chunk_tokens)
    retrieval_k = policy.k_min + max(0, extra_k)
    residual -= max(0, extra_k) * chunk_tokens

    memory_admitted = min(memory_tokens, policy.memory_floor_tokens + residual)

    total = retrieval_k * chunk_tokens + memory_admitted + tool_admitted
    return Allocation(retrieval_k, memory_admitted, tool_admitted, total, policy.budget)


def classify_miss(alloc: Allocation, policy: BudgetPolicy) -> str:
    utilization = alloc.total_tokens / alloc.budget
    if alloc.retrieval_k < policy.k_min:
        if utilization > policy.starvation_utilization:
            return "ARBITRATION_STARVATION"   # allocator starved retriever
        raise ContextArbitrationError(
            "retrieval below k_min without budget pressure: "
            "allocator failed to invoke retriever (indistinguishable from "
            "poisoned no-results state)"
        )
    if utilization > policy.starvation_utilization:
        return "BUDGET_SATURATED_BUT_RETRIEVED"
    return "GENUINE_MISS"                     # retriever ran, corpus lacked it
