# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-floor-when-kv-cache-pressure-and-retrieval-fidelity-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-compaction-floor-when-kv-cache-pressure-and-retrieval-fidelity-disagree.warrant.json
# Markdown SHA-256:   3a35b02234b052066b262a2f7c96de07b2b7043b77843c752f77a730b009559b
# Code AST SHA-256:   0ffe9f4f9bfe425b34ef2dbf34246b9604abfe04455dda20684f1ad2e44a05e9
# Verified Classes:   FidelityFloorViolation, SpanClass, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class FidelityFloorViolation(RuntimeError):
    """Raised when compaction would evict an irreproducible span with no durable copy."""
    pass


class SpanClass(Enum):
    RECONSTRUCTIBLE = "reconstructible"
    IRREPRODUCIBLE = "irreproducible"


@dataclass
class Span:
    token_start: int
    token_end: int
    klass: SpanClass
    has_durable_copy: bool
    literal: str | None = None


def enforce_compaction_floor(
    eviction_set: list[Span],
    pressure_floor_tokens: int,
    latency_budget_ms: int,
    estimated_ms_per_retained_k_token: float,
) -> int:
    """
    Returns the token floor to retain. Raises FidelityFloorViolation if the
    fidelity floor and the latency budget are jointly infeasible and no
    durable spill exists for an irreproducible span.
    """
    # Fidelity floor: retain every irreproducible span lacking a durable copy.
    must_retain = [
        s for s in eviction_set
        if s.klass is SpanClass.IRREPRODUCIBLE and not s.has_durable_copy
    ]
    if must_retain:
        fidelity_floor = max(s.token_end for s in must_retain)
    else:
        fidelity_floor = 0

    floor = max(pressure_floor_tokens, fidelity_floor)

    # Joint feasibility check against the latency budget.
    projected_ms = (floor / 1000.0) * estimated_ms_per_retained_k_token
    if projected_ms > latency_budget_ms:
        # Infeasible: must spill, not truncate.
        spillable = [s for s in must_retain if s.literal is not None]
        unspillable = [s for s in must_retain if s.literal is None]
        if unspillable:
            raise FidelityFloorViolation(
                f"fidelity floor {fidelity_floor} tokens projects {projected_ms:.0f}ms "
                f"> latency budget {latency_budget_ms}ms; "
                f"{len(unspillable)} irreproducible span(s) have no durable copy "
                f"and no literal to spill. Halt, do not summarize."
            )
        # Spill path: caller must persist `spillable` and record handles in digest.
        raise FidelityFloorViolation(
            f"fidelity floor infeasible under latency budget; "
            f"spill {len(spillable)} span(s) to durable store before compacting."
        )

    return floor
