# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-evict-a-live-memory-to-satisfy-a-forget-by-sla-the-eviction-vs-distillation-budget-race.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-evict-a-live-memory-to-satisfy-a-forget-by-sla-the-eviction-vs-distillation-budget-race.warrant.json
# Markdown SHA-256:   612a747f63f2883f55ba808be92e3f646ac1b582f5938400d81c86124c2d7705
# Code AST SHA-256:   2a4937418ce836e495c98a2c5097f2d2f52e3dc70197fa269f86ed3030703234
# Verified Classes:   ForgetSLAViolation, MemoryItem
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ForgetSLAViolation(RuntimeError):
    """Raised when compaction would spend budget on an item whose residual
    lifetime is shorter than the distillation cost — i.e. distill-then-delete."""


@dataclass
class MemoryItem:
    id: str
    tokens: int
    forget_by: float  # wall-clock epoch seconds
    access_recency: float


def distillation_cost_estimate(item: MemoryItem) -> int:
    # Empirical: ~0.37 tokens of write budget per source token, plus fixed overhead.
    return int(0.37 * item.tokens) + 40


def partition_for_compaction(
    items: list[MemoryItem],
    now: float,
    write_budget: int,
    reaper_jitter_margin: float,
) -> tuple[list[MemoryItem], list[MemoryItem]]:
    """Return (to_evict, to_distill). Eviction is free; distillation is budgeted.

    Invariant: no item with slack <= cost + jitter may enter the distill queue.
    """
    to_evict: list[MemoryItem] = []
    survivors: list[MemoryItem] = []

    for item in items:
        slack = item.forget_by - now
        cost = distillation_cost_estimate(item)
        if slack <= cost + reaper_jitter_margin:
            to_evict.append(item)
        else:
            survivors.append(item)

    # Earliest-deadline-first among survivors; drop largest-slack on budget overflow.
    survivors.sort(key=lambda i: i.forget_by - now)
    reserved = 0
    to_distill: list[MemoryItem] = []
    for item in survivors:
        cost = distillation_cost_estimate(item)
        if reserved + cost <= write_budget:
            to_distill.append(item)
            reserved += cost
        # else: dropped from this tick; it has the most slack, so it can wait.

    return to_evict, to_distill


def distill(item: MemoryItem, now: float, reaper_jitter_margin: float) -> str:
    """Last-line guard: re-check deadline at distillation start, not enqueue time."""
    slack = item.forget_by - now
    cost = distillation_cost_estimate(item)
    if slack <= cost + reaper_jitter_margin:
        raise ForgetSLAViolation(
            f"item {item.id}: slack={slack:.1f}s <= cost={cost} + "
            f"jitter={reaper_jitter_margin:.1f}s; must evict, not distill"
        )
    return f"<summary of {item.id}>"
