# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-salience-based-eviction-is-about-to-silently-destroy-a-live-dependency-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-salience-based-eviction-is-about-to-silently-destroy-a-live-dependency-chain.warrant.json
# Markdown SHA-256:   3e1909c49a4217221da801946c71f11dee9bb85954250bdce88509c07b0d5417
# Code AST SHA-256:   f354573279deba91f4f2a663f5bfc9d10741acd3e252cf8d1ccdcf07e3f0bc46
# Verified Classes:   EvictionInvariantViolation, ReDerivationCost, MemoryRecord, EvictionNotice, SalienceStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EvictionInvariantViolation(RuntimeError):
    """Raised when a forward-dependency record is evicted without an agent-visible notice."""


class ReDerivationCost(Enum):
    DETERMINISTIC = "deterministic"   # safe to recompute from in-context inputs
    NON_DETERMINISTIC = "non_deterministic"  # remote fetch, user input, sampled model output


@dataclass
class MemoryRecord:
    record_id: str
    content: str
    salience: float
    last_read_step: int
    forward_dependency: bool = False
    pinned_until_step: Optional[int] = None
    rederivation_cost: ReDerivationCost = ReDerivationCost.DETERMINISTIC


@dataclass
class EvictionNotice:
    record_id: str
    evicted_at_step: int
    reason: str


class SalienceStore:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.records: dict[str, MemoryRecord] = {}
        self.tombstones: list[EvictionNotice] = []

    def write(self, rec: MemoryRecord, step: int) -> list[EvictionNotice]:
        notices: list[EvictionNotice] = []
        if len(self.records) >= self.capacity:
            victim = min(
                (r for r in self.records.values() if r.pinned_until_step is None
                 or r.pinned_until_step < step),
                key=lambda r: r.salience,
            )
            del self.records[victim.record_id]
            notice = EvictionNotice(victim.record_id, step, "salience_floor")
            notices.append(notice)
            self.tombstones.append(notice)
            # INVARIANT: a forward-dependency record may not be evicted silently.
            # The eviction must reach the agent as a notice before the next write.
            if victim.forward_dependency and not self._notice_delivered(notice):
                raise EvictionInvariantViolation(
                    f"forward-dependency record {victim.record_id} evicted at step {step} "
                    f"with no agent-visible notice; downstream steps will re-derive "
                    f"against a wrong premise"
                )
        self.records[rec.record_id] = rec
        return notices

    def _notice_delivered(self, notice: EvictionNotice) -> bool:
        # In production this checks the agent's acknowledged-notice ledger.
        # Here: notice is delivered iff it was appended to the tombstone log
        # the agent polls. A real implementation must confirm the poll happened.
        return notice in self.tombstones

    def handle_eviction(self, notice: EvictionNotice, step: int) -> None:
        rec_tombstone = next(
            (t for t in self.tombstones if t.record_id == notice.record_id), None
        )
        if rec_tombstone is None:
            raise EvictionInvariantViolation(
                f"eviction notice for unknown record {notice.record_id}"
            )
        # Agent decision boundary: pin vs re-derive, by cost not reflex.
        if rec_tombstone.reason == "salience_floor":
            # We no longer hold the record body; we hold only the notice.
            # If the lost record was non-deterministically sourced, we must
            # re-fetch or re-ask, and we must flag that the re-fetch is a guess.
            raise EvictionInvariantViolation(
                f"record {notice.record_id} lost to salience eviction at step {step}; "
                f"re-derivation cost unknown after body loss — pin at write time instead"
            )
