# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-fidelity-budget-exhaustion-boundary-in-hierarchical-summarization.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-fidelity-budget-exhaustion-boundary-in-hierarchical-summarization.warrant.json
# Markdown SHA-256:   2674895568ae9a250d70ed463b4840ed131241ed6442191727e23ef5c4c895be
# Code AST SHA-256:   68ca41d8f488c3e2578ad98d0c7b76459dd5a7aa8b2d27963466f3eb7d948144
# Verified Classes:   FidelityBudgetExhausted, BudgetState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class FidelityBudgetExhausted(RuntimeError):
    """Raised when another compaction pass cannot be performed within the
    remaining cumulative fidelity budget at an achievable local loss rate."""


@dataclass
class BudgetState:
    remaining_cumulative: float   # e.g. 0.90 means >=90% of gen-0 facts must survive
    passes_left: int              # floored estimate, never the agent's optimistic guess
    min_achievable_local_retention: float  # measured summarizer capability, e.g. 0.93


def required_local_retention(remaining_cumulative: float, passes_left: int) -> float:
    if passes_left <= 0:
        return 1.0
    return remaining_cumulative ** (1.0 / passes_left)


def authorize_compaction(state: BudgetState) -> float:
    """
    Return the local retention the next pass must achieve, or refuse.
    Refusal is the correct outcome when the summarizer cannot hit the bar.
    """
    if state.remaining_cumulative <= 0.0:
        raise FidelityBudgetExhausted(
            f"cumulative budget exhausted (remaining={state.remaining_cumulative:.3f})"
        )

    required = required_local_retention(
        state.remaining_cumulative, state.passes_left
    )

    if state.min_achievable_local_retention < required:
        raise FidelityBudgetExhausted(
            "cannot compact within cumulative budget: "
            f"required_local_retention={required:.4f} "
            f"achievable={state.min_achievable_local_retention:.4f} "
            f"passes_left={state.passes_left} "
            f"remaining_cumulative={state.remaining_cumulative:.3f}; "
            "escalate to external spill / larger window / checkpoint"
        )

    return required


def apply_pass(state: BudgetState, measured_local_retention: float) -> BudgetState:
    required = authorize_compaction(state)
    if measured_local_retention < required:
        # Post-hoc violation: the pass already ran and lost too much.
        raise FidelityBudgetExhausted(
            f"pass violated budget: measured={measured_local_retention:.4f} "
            f"required={required:.4f}; roll back from ledger and re-summarize"
        )
    return BudgetState(
        remaining_cumulative=state.remaining_cumulative
        / measured_local_retention,
        passes_left=max(state.passes_left - 1, 0),
        min_achievable_local_retention=state.min_achievable_local_retention,
    )


# Example: 0.90 cumulative budget, 5 passes left, summarizer only hits 0.93.
# required = 0.90 ** (1/5) = 0.9791 > 0.93  -> refuse, do not compact.
if __name__ == "__main__":
    state = BudgetState(
        remaining_cumulative=0.90,
        passes_left=5,
        min_achievable_local_retention=0.93,
    )
    try:
        authorize_compaction(state)
    except FidelityBudgetExhausted as exc:
        print(f"REFUSED: {exc}")
