# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-token-budget-schedulers-from-silently-starving-the-compaction-reservation-under-latency-slo-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-token-budget-schedulers-from-silently-starving-the-compaction-reservation-under-latency-slo-pressure.warrant.json
# Markdown SHA-256:   e23f325f59a62025e49a6539a536da2b2251293e361abceb71acf6389479f699
# Code AST SHA-256:   f049fab19b07f8f14bbc15167806c5f26596e7ba929751bd1b6af3819c1b7de4
# Verified Classes:   CompactionStarvationError, Budget
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CompactionStarvationError(RuntimeError):
    """Raised when the scheduler would defer a mandatory compaction.

    This is the guardrail for the headroom-and-debt invariant: once the
    un-compacted working set plus carry-forward debt plus one reservation
    exceeds hard headroom, deferral is illegal and must escalate.
    """


@dataclass(frozen=True)
class Budget:
    window: int          # W
    sys: int             # B_sys
    ret_min: int         # minimum viable retrieval slice
    mem_min: int         # minimum viable recall slice
    cmp_reservation: int # C_t

    @property
    def hard_headroom(self) -> int:
        # H = W - B_sys - B_ret_min - B_mem_min
        return self.window - self.sys - self.ret_min - self.mem_min


def decide_compaction(
    budget: Budget,
    working_set_tokens: int,   # U_t
    carry_forward_debt: int,   # D_t
    latency_slo_pressure: bool,  # governor wants to skip
) -> str:
    """Return 'fill' or 'defer'. Raise if a skip would be illegal."""
    h = budget.hard_headroom
    u = working_set_tokens
    d = carry_forward_debt
    c = budget.cmp_reservation

    # Invariant: a legal skip requires U + D + C <= H. None of these
    # terms depend on latency_slo_pressure, so the SLO cannot buy a skip.
    legal_to_skip = (u + d + c) <= h

    if latency_slo_pressure and legal_to_skip:
        return "defer"

    if not legal_to_skip:
        # Mandatory fill. The governor may not override this.
        if latency_slo_pressure:
            # It is legal for the SLO to compress ret/mem fill, but the
            # mandatory compaction itself must still be attempted.
            return "fill"
        return "fill"

    # No SLO pressure and within headroom: fill opportunistically.
    return "fill"


def apply_turn(
    budget: Budget,
    working_set_tokens: int,
    carry_forward_debt: int,
    latency_slo_pressure: bool,
    compaction_reduced_working_set: bool | None = None,
) -> tuple[int, int]:
    """Advance one turn. Returns (new_working_set, new_debt)."""
    decision = decide_compaction(
        budget, working_set_tokens, carry_forward_debt, latency_slo_pressure
    )

    if decision == "defer":
        # Debt accrues by the skipped reservation; working set unchanged.
        return working_set_tokens, carry_forward_debt + budget.cmp_reservation

    # decision == "fill": mandatory or opportunistic compaction runs.
    if compaction_reduced_working_set is False:
        # A mandatory compaction that failed to reduce U cannot be
        # recovered by waiting; escalate rather than loop.
        raise CompactionStarvationError(
            f"mandatory compaction did not reduce working set "
            f"(U={working_set_tokens}, D={carry_forward_debt}, "
            f"H={budget.hard_headroom}); invariant unrestorable by deferral"
        )

    # Successful fill clears debt and shrinks the working set.
    new_working_set = max(0, working_set_tokens - budget.cmp_reservation)
    return new_working_set, 0
