# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-account-for-the-retrieval-budget-it-already-spent-before-the-planner-loop-began.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-account-for-the-retrieval-budget-it-already-spent-before-the-planner-loop-began.warrant.json
# Markdown SHA-256:   5172bd6e925f3a0f6207126d1ee90d51f36d76b7dd36358ce180f9958c5cf99f
# Code AST SHA-256:   63b091ce14563a8a9bd5edbb1d4a913d6e5a78b3ca03aa130f3c6ad48f2ec1dd
# Verified Classes:   RetrievalBudgetInvariantError, BudgetAllocator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RetrievalBudgetInvariantError(RuntimeError):
    """Raised when the retrieval sub-budget accounting excludes the seed retrieval,
    causing partition-starvation while the context window still has headroom."""
    pass


class BudgetAllocator:
    def __init__(self, window_budget: int, retrieve_budget: int,
                 reason_min: int, seed_tokens: int):
        self.window_budget = window_budget
        self.retrieve_budget = retrieve_budget
        self.reason_min = reason_min
        self.seed_tokens = seed_tokens
        self.window_used = 0
        self.retrieve_used = 0
        # Invariant: the seed retrieval is part of the retrieval footprint.
        # If it is not charged, the sub-budget is a phantom ceiling.
        if seed_tokens > retrieve_budget:
            raise RetrievalBudgetInvariantError(
                f"seed_tokens={seed_tokens} exceeds retrieve_budget={retrieve_budget}; "
                "partition was sized without the seed and will starve the planner"
            )
        self.retrieve_used += seed_tokens
        self.window_used += seed_tokens

    def request_retrieval(self, requested: int, reason_tokens_in_use: int) -> bool:
        # Window-level invariant is checked FIRST and is binding.
        window_headroom = self.window_budget - self.window_used
        if requested > window_headroom:
            return False  # genuine window pressure

        # Sub-budget is soft: may borrow from reserve, but must not
        # push reason below its minimum.
        soft_cap = self.retrieve_budget + (self.window_budget - self.window_used
                                           - reason_tokens_in_use - self.reason_min)
        if self.retrieve_used + requested > soft_cap:
            # Distinguish partition-starvation from window-starvation in the trace.
            if window_headroom >= requested:
                raise RetrievalBudgetInvariantError(
                    f"partition-starvation: requested={requested} rejected while "
                    f"window_headroom={window_headroom}; retrieve_used={self.retrieve_used} "
                    f"soft_cap={soft_cap}. Sub-budget is binding below the window."
                )
            return False

        self.retrieve_used += requested
        self.window_used += requested
        return True
