# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-read-as-an-implicit-write-under-temporal-decay-provenance-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-read-as-an-implicit-write-under-temporal-decay-provenance-tracking.warrant.json
# Markdown SHA-256:   bb7372386060f6061dbc97be3aa43bb638bc1215e917a2cba1a0a6d719ced4bc
# Code AST SHA-256:   1856fdc53435ff7276741df566870c492232c93226914b2846de23189f57f97e
# Verified Classes:   ReadPurpose, DecayMutationOnInspection, MemoryRecord, DecayMemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ReadPurpose(Enum):
    CONSUMPTION = "consumption"   # content enters context; refresh is legitimate
    INSPECTION = "inspection"     # evaluating for forget/dedup/migrate; must be neutral


class DecayMutationOnInspection(RuntimeError):
    """Raised when an inspection read would refresh decay state or add a recall edge."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    created_at: float
    last_accessed: float
    provenance: list = field(default_factory=list)


class DecayMemoryStore:
    def __init__(self, clock, half_life: float):
        self._clock = clock
        self._half_life = half_life
        self._records: dict[str, MemoryRecord] = {}

    def _effective_score(self, rec: MemoryRecord) -> float:
        anchor = max(rec.created_at, rec.last_accessed)
        age = self._clock() - anchor
        return 0.5 ** (age / self._half_life)

    def read(self, record_id: str, purpose: ReadPurpose,
             instance_id: str) -> MemoryRecord:
        rec = self._records[record_id]
        if purpose is ReadPurpose.INSPECTION:
            # Invariant: inspection must not mutate the state under evaluation.
            # If the store's read path would refresh, refuse rather than corrupt.
            if self._would_refresh(rec):
                raise DecayMutationOnInspection(
                    f"inspection read of {record_id} by {instance_id} would "
                    f"reset decay (last_accessed={rec.last_accessed}); "
                    f"use peek() or a snapshot instead"
                )
            rec.provenance.append(("inspected_by", instance_id, self._clock()))
            return rec
        # CONSUMPTION: refresh decay and record a genuine recall edge.
        rec.last_accessed = self._clock()
        rec.provenance.append(("recall_by", instance_id, self._clock()))
        return rec

    def _would_refresh(self, rec: MemoryRecord) -> bool:
        # A store that anchors decay on last_accessed will refresh on any read
        # that bumps it. Detect that condition before allowing the read.
        return rec.last_accessed < self._clock()

    def peek(self, record_id: str) -> tuple[float, list]:
        """Decay-neutral projection: score and provenance without mutation."""
        rec = self._records[record_id]
        return self._effective_score(rec), list(rec.provenance)

    def forget(self, record_id: str, snapshot_score: float,
               threshold: float, instance_id: str) -> bool:
        # Forget decisions must be issued against a pre-read snapshot score,
        # never a score recomputed through a refreshing read.
        rec = self._records[record_id]
        if snapshot_score >= threshold:
            return False
        del self._records[record_id]
        return True


def consolidation_sweep(store: DecayMemoryStore, threshold: float,
                        instance_id: str) -> int:
    # Snapshot every candidate's decay state BEFORE any read that could refresh.
    snapshot = {rid: store.peek(rid)[0] for rid in list(store._records)}
    evicted = 0
    for rid, score in snapshot.items():
        try:
            # Inspection read is allowed only because peek() already snapshotted;
            # if the store tries to refresh here, the guard fires.
            store.read(rid, ReadPurpose.INSPECTION, instance_id)
        except DecayMutationOnInspection:
            # Fall back to snapshot-only decision; never read to decide.
            pass
        if store.forget(rid, score, threshold, instance_id):
            evicted += 1
    return evicted
