# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-decay-weighted-memory-reads-against-concurrent-writes-that-reset-the-decay-clock.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-decay-weighted-memory-reads-against-concurrent-writes-that-reset-the-decay-clock.warrant.json
# Markdown SHA-256:   2f260c9f37fa144d82e20bfb52278547e5574b4b2319added06faa5fc7dbe94d
# Code AST SHA-256:   aecb65948d463c829d1a9399c36a4eb82c7253c01b07b2e7acb515a3c4ba85e6
# Verified Classes:   DecayClockRaceError, MemoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DecayClockRaceError(RuntimeError):
    """Raised when a destructive memory op is gated on a stale decay projection."""


@dataclass(frozen=True)
class MemoryRecord:
    id: str
    base_weight: float
    half_life_s: float
    last_touched_at: float
    version: int


def confidence(rec: MemoryRecord, now: float) -> float:
    age = max(0.0, now - rec.last_touched_at)
    return rec.base_weight * (0.5 ** (age / rec.half_life_s))


def safe_forget(
    store: dict[str, MemoryRecord],
    record_id: str,
    observed_version: int,
    observed_confidence: float,
    threshold: float,
    now: float,
) -> None:
    rec = store.get(record_id)
    if rec is None:
        raise DecayClockRaceError(f"{record_id}: vanished before forget")
    if rec.version != observed_version:
        # A concurrent touch/write moved the decay clock; the score we
        # decided on no longer describes this record.
        raise DecayClockRaceError(
            f"{record_id}: version {observed_version} -> {rec.version}; "
            f"re-read required (observed_conf={observed_confidence:.3f})"
        )
    live_conf = confidence(rec, now)
    if abs(live_conf - observed_confidence) > 1e-6:
        raise DecayClockRaceError(
            f"{record_id}: confidence drifted {observed_confidence:.3f} -> "
            f"{live_conf:.3f} at same version; clock not monotonic"
        )
    if live_conf >= threshold:
        raise DecayClockRaceError(
            f"{record_id}: confidence {live_conf:.3f} >= threshold {threshold}; "
            f"refusing destructive prune"
        )
    del store[record_id]
