# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-a-provenance-forgotten-memory-through-a-read-modify-write-cycle-on-a-keyed-memory-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-a-provenance-forgotten-memory-through-a-read-modify-write-cycle-on-a-keyed-memory-tool.warrant.json
# Markdown SHA-256:   fa34a22ea678e1769c6b42af6c26dcd09eb13efb07e6e96c63ea80401e4ada76
# Code AST SHA-256:   d2865cc9d1dc0b6d1bb5777d5f9f858f042e52494bc65bf27af09f6d1c9d0bc6
# Verified Classes:   MemoryResurrectionError, Tombstone, LiveRecord, ProvenanceStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class MemoryResurrectionError(RuntimeError):
    """Raised when a write would re-materialize provenance-forgotten content."""


@dataclass
class Tombstone:
    key: str
    forgotten_at: float
    lineage_root: str
    value_fingerprints: frozenset  # hashes of forgotten values


@dataclass
class LiveRecord:
    key: str
    value: dict
    provenance: dict
    written_at: float
    supersedes_tombstone: Optional[float] = None


@dataclass
class ProvenanceStore:
    live: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)  # key -> Tombstone

    def forget(self, key: str, reason: str, now: float, fingerprint: str) -> None:
        rec = self.live.pop(key, None)
        if rec is None:
            return
        self.tombstones[key] = Tombstone(
            key=key,
            forgotten_at=now,
            lineage_root=rec.provenance["source"],
            value_fingerprints=frozenset({fingerprint}),
        )

    def write(self, key: str, value: dict, provenance: dict,
              now: float, fingerprint: str) -> LiveRecord:
        tomb = self.tombstones.get(key)
        if tomb is not None:
            lineage_clash = provenance["source"] == tomb.lineage_root
            value_clash = fingerprint in tomb.value_fingerprints
            if lineage_clash or value_clash:
                raise MemoryResurrectionError(
                    f"write to {key!r} would resurrect content forgotten at "
                    f"{tomb.forgotten_at} (lineage_root={tomb.lineage_root!r}); "
                    f"supply a fresh key or an explicit reauthorize warrant"
                )
            rec = LiveRecord(key, value, provenance, now,
                             supersedes_tombstone=tomb.forgotten_at)
            self.live[key] = rec
            return rec
        rec = LiveRecord(key, value, provenance, now)
        self.live[key] = rec
        return rec
