# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-horizon-before-hierarchical-summarization-silently-evicts-the-load-bearing-constraint.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-horizon-before-hierarchical-summarization-silently-evicts-the-load-bearing-constraint.warrant.json
# Markdown SHA-256:   6d64a310fb087ef0b30e4d73b7584cbce6535b60dd4a9fec11237298b7954ba9
# Code AST SHA-256:   c35f55f8014085f5384a8b17c7a236f9ea2107d99a9c74531ef8f7bdde7bb2e5
# Verified Classes:   CompactionHorizonError, Span, ProtectedSlot
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class CompactionHorizonError(RuntimeError):
    """Raised when a span would be lossily compacted while carrying an unpromoted constraint."""
    pass


@dataclass
class Span:
    step_range: tuple[int, int]
    tokens: int
    text: str
    constraints: list[str] = field(default_factory=list)


@dataclass
class ProtectedSlot:
    budget_tokens: int = 3000
    entries: list[tuple[int, str]] = field(default_factory=list)

    def used(self) -> int:
        return sum(len(c.split()) for _, c in self.entries)

    def promote(self, step: int, constraint: str) -> None:
        if self.used() + len(constraint.split()) > self.budget_tokens:
            raise CompactionHorizonError(
                f"protected slot full ({self.used()}/{self.budget_tokens} tokens); "
                f"cannot promote constraint from step {step} — escalate, do not summarize"
            )
        self.entries.append((step, constraint))


def compact(span: Span, slot: ProtectedSlot, mode: Literal["lossless", "lossy"]) -> str:
    if mode == "lossy":
        unpromoted = [c for c in span.constraints if (span.step_range[0], c) not in slot.entries]
        if unpromoted:
            raise CompactionHorizonError(
                f"refusing lossy compaction of steps {span.step_range}: "
                f"{len(unpromoted)} constraint(s) not yet in protected slot: {unpromoted!r}"
            )
        return f"[SUMMARY steps {span.step_range}] topic-level compression"
    return span.text  # lossless eviction: verbatim, re-fetchable


def schedule(spans: list[Span], slot: ProtectedSlot, watermark_tokens: int) -> list[str]:
    total = sum(s.tokens for s in spans)
    out: list[str] = []
    for s in spans:
        if total <= watermark_tokens:
            out.append(s.text)
            continue
        # promote constraints first, then decide mode
        for c in s.constraints:
            if (s.step_range[0], c) not in slot.entries:
                slot.promote(s.step_range[0], c)
        out.append(compact(s, slot, mode="lossy" if not s.constraints else "lossless"))
        total -= s.tokens
    return out
