# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-memory-when-a-retention-sweep-races-an-in-flight-write-back.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-memory-when-a-retention-sweep-races-an-in-flight-write-back.warrant.json
# Markdown SHA-256:   bcb2849f1692e025dd925c904e1b317d712ed973e8d7f52ac904f4b95ceea28b
# Code AST SHA-256:   f443370f80cc43509d41a391e018caefc6752f4974ab787ccedc2ab443fb98ef
# Verified Classes:   ResurrectionRaceError, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResurrectionRaceError(RuntimeError):
    """Raised when a write-back would re-materialize content whose provenance is tombstoned."""
    pass


class MemoryStore:
    def __init__(self):
        self.records = {}        # id -> value
        self.tombstones = {}     # id -> content_fingerprint
        self.epoch = 0

    def forget(self, record_id, fingerprint):
        self.records.pop(record_id, None)
        self.tombstones[record_id] = fingerprint
        self.epoch += 1

    def write(self, key, value, derived_from, read_epoch, fingerprint):
        # 1. Epoch fencing: reject writes derived under a stale retention epoch.
        if read_epoch != self.epoch:
            raise ResurrectionRaceError(
                f"write to {key!r} derived under epoch {read_epoch}, "
                f"current epoch {self.epoch}; re-read required"
            )
        # 2. Fail-closed provenance: never reclassify a dangling reference.
        for src in derived_from:
            if src in self.tombstones:
                raise ResurrectionRaceError(
                    f"write to {key!r} references tombstoned record {src!r}; "
                    f"content must not be re-materialized"
                )
        # 3. Content-keyed tombstone check: catch paraphrase resurrection.
        for tid, fp in self.tombstones.items():
            if fp == fingerprint:
                raise ResurrectionRaceError(
                    f"write to {key!r} matches tombstone content of {tid!r}"
                )
        self.records[key] = value
        return key


def distill_and_write(store, src_id, summary, read_epoch, fingerprint):
    # read_epoch captured at read time; write enforces it.
    return store.write(
        key=f"sem_{src_id}",
        value=summary,
        derived_from=[src_id],
        read_epoch=read_epoch,
        fingerprint=fingerprint,
    )
