# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-context-window-and-the-eviction-metric-reports-high-fidelity-on-a-summary-that-has-silently-dropped-the-bin.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-context-window-and-the-eviction-metric-reports-high-fidelity-on-a-summary-that-has-silently-dropped-the-bin.warrant.json
# Markdown SHA-256:   95ac9520fb6051fddbc7f581f3ced036f91b11cd994fc3c04f1d6d88f98325f0
# Code AST SHA-256:   0bf67b48dbf1328c1c7242c1dd7791d43985cf8b398aa86cbcbef60490238785
# Verified Classes:   CompactionFidelityError, Constraint, CompactionResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction summary is authorized for eviction on a
    reconstruction-fidelity score while failing constraint preservation on an
    irrecoverable (non-inline-retrievable) eviction."""


@dataclass(frozen=True)
class Constraint:
    key: str          # e.g. "dump_size_cap"
    entity: str       # e.g. "staging_db"
    value: str        # e.g. "2GB"
    source_turn: int


@dataclass
class CompactionResult:
    summary_text: str
    reconstruction_fidelity: float          # cosine / judge score, 0..1
    constraints_in_summary: dict[str, str]  # key -> value as found in summary
    raw_turns_inline_retrievable: bool


def gate_eviction(
    raw_turns: Iterable[str],
    enumerated_constraints: list[Constraint],
    result: CompactionResult,
    reconstruction_threshold: float = 0.85,
) -> None:
    # Constraint enumeration MUST come from raw turns, never the summary.
    if not enumerated_constraints:
        raise CompactionFidelityError(
            "no constraints enumerated from raw turns; "
            "reconstruction fidelity is not a valid eviction gate"
        )

    dropped: list[Constraint] = []
    misbound: list[Constraint] = []
    for c in enumerated_constraints:
        found = result.constraints_in_summary.get(c.key)
        if found is None:
            dropped.append(c)
        elif found.strip() != c.value.strip():
            misbound.append(c)

    # If raw turns remain inline-retrievable, a missed constraint is recoverable.
    if result.raw_turns_inline_retrievable:
        return

    # Irrecoverable eviction: reconstruction score is irrelevant to safety.
    if dropped or misbound:
        detail = []
        if dropped:
            detail.append(
                "dropped=" + ",".join(f"{c.key}@{c.source_turn}" for c in dropped)
            )
        if misbound:
            detail.append(
                "misbound="
                + ",".join(f"{c.key}({c.value}!={result.constraints_in_summary[c.key]})"
                           for c in misbound)
            )
        raise CompactionFidelityError(
            "blocking irreversible eviction: constraint preservation failed "
            f"[{'; '.join(detail)}] despite reconstruction_fidelity="
            f"{result.reconstruction_fidelity:.2f} (threshold "
            f"{reconstruction_threshold:.2f}); summary is not a safe sole "
            "representation of evicted turns"
        )

    # Only now may the reconstruction threshold be consulted as a secondary check.
    if result.reconstruction_fidelity < reconstruction_threshold:
        raise CompactionFidelityError(
            f"reconstruction_fidelity {result.reconstruction_fidelity:.2f} "
            f"below {reconstruction_threshold:.2f} and eviction is irreversible"
        )
