# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-it-must-later-prove-it-never-had-provenance-tombstone-divergence-in-decayed-read-write-forget-memory-ap.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-it-must-later-prove-it-never-had-provenance-tombstone-divergence-in-decayed-read-write-forget-memory-ap.warrant.json
# Markdown SHA-256:   007f01293ad5ee15449ee531f7cea4520ed15f3a75c487f15e4a43ed36c4b825
# Code AST SHA-256:   dd30aebb7d98e93584166a858af9d7a5280262297c00ab0aeeee80dc90bcf2bc
# Verified Classes:   ProvenanceDivergenceError, Record, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceDivergenceError(RuntimeError):
    """Raised when a record's retrieval status and provenance status disagree
    about whether the record was forgotten."""
    pass


@dataclass
class Record:
    record_id: str
    content: str
    warrant: str
    confidence: float
    decay_weight: float
    status: str = "live"  # live | decayed | forgotten | forgotten-by-decay


class MemoryStore:
    def __init__(self, retrieval_floor: float = 0.05):
        self.retrieval_floor = retrieval_floor
        self._records: dict[str, Record] = {}

    def write(self, rec: Record) -> None:
        self._records[rec.record_id] = rec

    def read(self, query: str) -> list[Record]:
        return [
            r for r in self._records.values()
            if r.status == "live" and r.decay_weight >= self.retrieval_floor
        ]

    def read_provenance(self, record_id: str) -> Optional[Record]:
        return self._records.get(record_id)

    def apply_decay(self, record_id: str, factor: float) -> None:
        r = self._records[record_id]
        r.decay_weight *= factor
        if r.decay_weight < self.retrieval_floor and r.status == "live":
            # INVARIANT: crossing the floor is a forgetting event, not a demotion.
            r.status = "forgotten-by-decay"

    def assert_consistent(self, record_id: str) -> None:
        r = self._records[record_id]
        retrievable = r.decay_weight >= self.retrieval_floor and r.status == "live"
        provenance_says_forgotten = r.status in ("forgotten", "forgotten-by-decay")
        if retrievable and provenance_says_forgotten:
            raise ProvenanceDivergenceError(
                f"{record_id}: retrievable but provenance marks forgotten"
            )
        if (not retrievable) and not provenance_says_forgotten:
            raise ProvenanceDivergenceError(
                f"{record_id}: unretrievable but provenance still '{r.status}' "
                f"(decay={r.decay_weight:.4f} < floor={self.retrieval_floor})"
            )


def act_on_absence(store: MemoryStore, known_ids: list[str], candidate: str) -> None:
    """An instance must not infer 'never asserted' from 'not retrievable'."""
    for rid in known_ids:
        prov = store.read_provenance(rid)
        if prov is None:
            continue  # genuinely never written
        if prov.status == "live":
            raise ProvenanceDivergenceError(
                f"{rid} is live and binding; cannot act on absence of {candidate}"
            )
        if prov.status == "decayed":
            # This is the bug state: decayed but not tombstoned.
            raise ProvenanceDivergenceError(
                f"{rid} decayed without tombstone; provenance/retrieval diverge"
            )
        # forgotten or forgotten-by-decay: retired, safe to proceed.
    return
