# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-summarization-trigger-boundary-and-the-loss-budget-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-summarization-trigger-boundary-and-the-loss-budget-invariant.warrant.json
# Markdown SHA-256:   f2a30097fda4ab22f0808f0a501e6501b9ae5c353d0b27266b40c360daf0e145
# Code AST SHA-256:   6eaee82132b9f91911a02bde13a11b6e417686d89f7fe2f240e936b74eed3f8e
# Verified Classes:   SpanClass, LossBudgetExhausted, CompactionGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpanClass(Enum):
    RE_DERIVABLE = "re_derivable"   # tool output, file contents, recomputable
    IRREVERSIBLE = "irreversible"   # constraints, branch decisions, rejection rationales


class LossBudgetExhausted(RuntimeError):
    """Raised when a compaction would spend irreversible-loss budget the agent does not have."""
    pass


@dataclass
class CompactionGate:
    loss_budget: int                      # declared before horizon start, never inferred
    remaining: int = field(init=False)
    spilled_pointers: list = field(default_factory=list)

    def __post_init__(self):
        if self.loss_budget < 0:
            raise LossBudgetExhausted("loss budget must be declared non-negative at horizon start")
        self.remaining = self.loss_budget

    def _irreversible_count(self, span: list[tuple[str, SpanClass]]) -> int:
        return sum(1 for _, cls in span if cls is SpanClass.IRREVERSIBLE)

    def evaluate(self, span: list[tuple[str, SpanClass]], partitionable: bool) -> str:
        """Three-way gate at a watermark crossing. Returns the action taken."""
        irrev = self._irreversible_count(span)

        if irrev <= self.remaining:
            self.remaining -= irrev
            return "compact_full"

        if partitionable:
            # defer, do not spend: spill irreversible partition to cold storage
            self.spilled_pointers.append(
                [tok for tok, cls in span if cls is SpanClass.IRREVERSIBLE]
            )
            return "compact_partition_and_spill"

        # unpartitionable overrun: refuse under pressure, even at 95% utilization
        raise LossBudgetExhausted(
            f"span carries {irrev} irreversible facts but only {self.remaining} "
            f"loss budget remains; refusing to compact. Spill or halt the horizon."
        )


def compact_or_refuse(gate: CompactionGate, span, partitionable: bool) -> str:
    action = gate.evaluate(span, partitionable)
    if action == "compact_partition_and_spill":
        # mandatory retrieval-check on next step touching spilled topic
        assert gate.spilled_pointers, "spill recorded but pointer missing"
    return action
