# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-ttl-expiry-resurrection-from-silently-re-admitting-forgotten-facts-into-an-agent-s-semantic-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-ttl-expiry-resurrection-from-silently-re-admitting-forgotten-facts-into-an-agent-s-semantic-memory.warrant.json
# Markdown SHA-256:   33b21fbe23ea8b154ff9443a4df3b510aaa5470ebe5cc46ec2fe2ff9571c573a
# Code AST SHA-256:   4a79b90676a950a4906554e877e5994eb5c988773db4d895e15f71cffa269b69
# Verified Classes:   ForgottenAncestorError, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ForgottenAncestorError(RuntimeError):
    """Raised when a derived memory write references a tombstoned ancestor."""
    pass


class MemoryStore:
    def __init__(self):
        self.records = {}       # id -> record dict
        self.tombstones = {}    # id -> forget event (retained >= max TTL + lag)

    def forget(self, record_id: str, reason: str) -> None:
        self.tombstones[record_id] = {"reason": reason, "monotonic": True}
        self.records.pop(record_id, None)

    def write(self, record: dict) -> str:
        derived_from = record.get("derived_from", [])
        # Invariant: provenance liveness is checked at write time, on the
        # authoritative store, not delegated to the caller.
        for ancestor_id in derived_from:
            if ancestor_id in self.tombstones:
                raise ForgottenAncestorError(
                    f"write of {record.get('id')} references tombstoned "
                    f"ancestor {ancestor_id}; drop the cluster, do not "
                    f"launder by severing provenance"
                )
            if ancestor_id not in self.records:
                raise ForgottenAncestorError(
                    f"write of {record.get('id')} references unknown "
                    f"ancestor {ancestor_id}; refusing unverifiable lineage"
                )
        self.records[record["id"]] = record
        return record["id"]


def compact_cluster(store: MemoryStore, episode_ids: list[str], summary: dict) -> str:
    # Compactor path: build a derived record and let the store enforce liveness.
    summary = dict(summary)
    summary["derived_from"] = list(episode_ids)
    return store.write(summary)


# Trace of the failure the invariant now blocks:
store = MemoryStore()
store.write({"id": "ep-1", "text": "retracted fact", "derived_from": []})
store.write({"id": "ep-2", "text": "benign", "derived_from": []})
store.forget("ep-1", reason="PII retraction")

# Before the guardrail this succeeded and laundered the fact.
# Now it raises and the compactor must drop the whole cluster.
try:
    compact_cluster(store, ["ep-1", "ep-2"], {"id": "sem-9", "text": "summary"})
except ForgottenAncestorError as e:
    print(f"cluster dropped: {e}")
