# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-self-rewrite-commit-barrier-and-the-lossy-summarization-trap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-self-rewrite-commit-barrier-and-the-lossy-summarization-trap.warrant.json
# Markdown SHA-256:   95d3c220678d00c4f22be5426deecd0946f03c7bc9bde99e204843bb6c52ec0b
# Code AST SHA-256:   5d4d8317f068bf594e19be382067dc7a25ccbc44d56812bd66f1195e5a6fbf13
# Verified Classes:   CompactionRefused, FactClass, WorkingFact, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionRefused(RuntimeError):
    """Raised when a lossy self-rewrite would drop a non-recoverable fact
    that a pending step depends on, and re-derivation has side effects."""
    pass


class FactClass(Enum):
    RECOVERABLE = "recoverable"          # re-readable from external store
    NEGATIVE_RESULT = "negative_result"  # "X already exists" — high risk
    DERIVED = "derived"                  # synthesized by agent reasoning
    EXCEPTION = "exception"              # discovered special case


@dataclass
class WorkingFact:
    key: str
    content: str
    cls: FactClass
    pending_step_depends: bool
    rederivation_has_side_effects: bool


@dataclass
class CompactionPlan:
    facts_to_evict: list[WorkingFact] = field(default_factory=list)
    obligations: list[str] = field(default_factory=list)
    spill: list[WorkingFact] = field(default_factory=list)


def evaluate_compaction(facts: list[WorkingFact], saturation: float,
                        spill_watermark: float = 0.60) -> CompactionPlan:
    plan = CompactionPlan()

    # Trigger discipline: refuse to even decide under last-minute pressure
    # unless every evicted fact is recoverable.
    late = saturation > spill_watermark

    for f in facts:
        recoverable = f.cls is FactClass.RECOVERABLE

        if recoverable:
            plan.facts_to_evict.append(f)
            continue

        if not f.pending_step_depends:
            plan.facts_to_evict.append(f)
            continue

        # Non-recoverable AND a pending step needs it.
        if not f.rederivation_has_side_effects:
            plan.facts_to_evict.append(f)
            plan.obligations.append(
                f"re-derive '{f.key}' before dependent step"
            )
            continue

        # The bottom row: non-recoverable, pending-dependent, side-effecting.
        # Must NOT commit lossily. Spill to external store instead.
        if late:
            raise CompactionRefused(
                f"refusing lossy commit of '{f.key}' ({f.cls.value}): "
                f"pending step depends on it, re-derivation has side "
                f"effects, and saturation {saturation:.0%} leaves no "
                f"budget to spill safely. Spill earlier or halt."
            )
        plan.spill.append(f)

    return plan


def commit(plan: CompactionPlan) -> None:
    # Spill is mandatory before eviction; an unspilled non-recoverable
    # fact that survives to eviction is a protocol violation.
    for f in plan.spill:
        persist_to_external_store(f)  # noqa: F821 — external sink
    for f in plan.facts_to_evict:
        if f.cls is not FactClass.RECOVERABLE and f not in plan.spill:
            # defensive: should have been caught in evaluate_compaction
            raise CompactionRefused(
                f"evicting non-recoverable '{f.key}' without spill"
            )
    apply_summary(plan)  # noqa: F821 — external sink
