# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-salience-weight-decay-has-inverted-the-eviction-ordering-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-salience-weight-decay-has-inverted-the-eviction-ordering-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   272889110bec6b0fe1e884662485d0ce06334107be0ddc6443159d8a018adc08
# Code AST SHA-256:   71bf36138e1e187795992b90980f8f595f0b12b4dedd7eb46891ce010b942e44
# Verified Classes:   SalienceInversionError, MemoryRecord, EvictionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SalienceInversionError(RuntimeError):
    """Raised when eviction selects a structurally load-bearing record."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    weight: float
    accesses: int = 0
    pinned: bool = False
    content: str = ""


@dataclass
class EvictionResult:
    evicted: Optional[str]
    occupancy: int


PIN_THRESHOLD = 0.7
ACCESS_FLOOR = 2
MAX_RECORDS = 32


def eviction_comparator(rec: MemoryRecord, now_salience: float) -> tuple:
    # Lexicographic: pinned records sort last (never evicted first).
    return (0 if rec.pinned else 1, rec.weight, now_salience)


def write_record(store: list[MemoryRecord], rec: MemoryRecord, now_salience_fn) -> EvictionResult:
    store.append(rec)
    if len(store) <= MAX_RECORDS:
        return EvictionResult(evicted=None, occupancy=len(store))

    candidates = sorted(store, key=lambda r: eviction_comparator(r, now_salience_fn(r)))
    victim = candidates[0]
    if victim.pinned:
        # All records pinned: capacity invariant violated, cannot evict safely.
        raise SalienceInversionError(
            f"store full ({len(store)}) and all records pinned; cannot evict {victim.record_id}"
        )

    # Detect ordering inversion: load-bearing, rarely-accessed record is the victim.
    if victim.weight >= PIN_THRESHOLD and victim.accesses <= ACCESS_FLOOR:
        raise SalienceInversionError(
            f"eviction-ordering inversion: victim {victim.record_id} "
            f"weight={victim.weight} accesses={victim.accesses}; "
            f"re-write as pinned before proceeding"
        )

    store.remove(victim)
    return EvictionResult(evicted=victim.record_id, occupancy=len(store))
