# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-invalidate-a-memory-write-whose-provenance-chain-was-truncated-by-a-forgotten-parent.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-invalidate-a-memory-write-whose-provenance-chain-was-truncated-by-a-forgotten-parent.warrant.json
# Markdown SHA-256:   be9dc7037395cb21427598fd090620e8693d8b6e7d804bd6b100aa68ee4b2fd4
# Code AST SHA-256:   bff4cf1afe1fecc59f2df764ce9e223c74e03987f708b6feb15e37f16d15a302
# Verified Classes:   ProvenanceTruncationError, MemoryRecord, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ProvenanceTruncationError(RuntimeError):
    """Raised when decay recomputation encounters a chain whose interior
    links were removed by forget(), making the true derivation age unknowable."""


@dataclass
class MemoryRecord:
    id: str
    created_at: float
    sources: list[str] = field(default_factory=list)
    stale: bool = False


class MemoryStore:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}
        # Sidecar: descendant_id -> {forgotten_ancestor_id: created_at}
        # Retained ONLY under the retain-and-freeze policy.
        self._frozen_ancestors: dict[str, dict[str, float]] = {}
        self._policy: str = "invalidate"  # or "retain"

    def remember(self, rec: MemoryRecord) -> None:
        self._records[rec.id] = rec

    def forget(self, rec_id: str) -> list[str]:
        """Remove a record. Returns the ids of all descendants whose decay
        is now affected. Caller MUST acknowledge this set."""
        if rec_id not in self._records:
            return []
        victim = self._records.pop(rec_id)
        affected: list[str] = []
        for other in self._records.values():
            if rec_id in other.sources:
                affected.append(other.id)
                if self._policy == "retain":
                    self._frozen_ancestors.setdefault(other.id, {})[rec_id] = (
                        victim.created_at
                    )
                else:
                    other.stale = True
        return affected

    def _true_root_age(self, rec: MemoryRecord, now: float, seen: set[str]) -> float:
        if rec.id in seen:
            raise ProvenanceTruncationError(f"cycle detected at {rec.id}")
        seen.add(rec.id)
        if not rec.sources:
            return now - rec.created_at
        ages: list[float] = []
        for src_id in rec.sources:
            if src_id in self._records:
                ages.append(self._true_root_age(self._records[src_id], now, seen))
            elif src_id in self._frozen_ancestors.get(rec.id, {}):
                # retain-and-freeze: timestamp survived the forget
                ages.append(now - self._frozen_ancestors[rec.id][src_id])
            else:
                # interior link gone with no retained timestamp: the true
                # derivation age is unknowable. Refuse to guess.
                raise ProvenanceTruncationError(
                    f"record {rec.id} sources forgotten ancestor {src_id} "
                    f"with no retained timestamp; decay is not recomputable"
                )
        return max(ages)

    def decay(self, rec_id: str, now: float | None = None) -> float:
        now = now if now is not None else time.time()
        rec = self._records[rec_id]
        if rec.stale:
            raise ProvenanceTruncationError(
                f"record {rec_id} is stale pending re-derivation"
            )
        age_days = self._true_root_age(rec, now, set()) / 86400.0
        return 1.0 / (age_days + 1.0)
