# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-provenance-rooted-tombstone-invariants-when-a-forget-call-races-a-write-that-re-derives-the-same-memory-key.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-provenance-rooted-tombstone-invariants-when-a-forget-call-races-a-write-that-re-derives-the-same-memory-key.warrant.json
# Markdown SHA-256:   8eb9bdf86feb1ef5c1c0e5635d69c8da7231bff14ca545b2ab6b472e3856baa4
# Code AST SHA-256:   c7999d1ebc78e9ea442fae3576eb6e369ebd330cf4af4abf977ef61ff4145a7b
# Verified Classes:   TombstoneViolation, MemoryGuard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class TombstoneViolation(RuntimeError):
    """Raised when a write's provenance intersects a tombstoned root set,
    or when a read returns a record whose roots are tombstoned."""
    pass


class MemoryGuard:
    def __init__(self):
        self.tombstoned_roots: set[str] = set()
        self.live: dict[str, dict] = {}

    def forget(self, record_id: str, reason: str) -> str:
        rec = self.live.get(record_id)
        if rec is None:
            raise TombstoneViolation(f"forget on unknown record {record_id}")
        roots = set(rec["root_ids"])
        if not roots:
            raise TombstoneViolation(
                f"record {record_id} has no provenance roots; "
                "cannot audit deletion"
            )
        self.tombstoned_roots |= roots
        # Cascade: any live record sharing a root is now invalid.
        for rid, r in list(self.live.items()):
            if set(r["root_ids"]) & self.tombstoned_roots:
                del self.live[rid]
        return f"tombstone:{sorted(roots)}"

    def write(self, content: str, provenance: list[str]) -> str:
        roots: set[str] = set()
        for p in provenance:
            if p == "ROOT":
                roots.add(f"root:{id(content)}")
            elif p in self.live:
                roots |= set(self.live[p]["root_ids"])
            else:
                raise TombstoneViolation(
                    f"provenance parent {p} is not live (forgotten or missing)"
                )
        if roots & self.tombstoned_roots:
            raise TombstoneViolation(
                f"write provenance intersects tombstoned roots "
                f"{roots & self.tombstoned_roots}; refusing resurrection"
            )
        rid = f"r{len(self.live)}_{abs(hash(content)) % 10**6}"
        self.live[rid] = {"content": content, "root_ids": roots}
        return rid

    def read(self, rid: str) -> dict:
        rec = self.live.get(rid)
        if rec is None:
            raise TombstoneViolation(f"read of non-live record {rid}")
        if set(rec["root_ids"]) & self.tombstoned_roots:
            raise TombstoneViolation(
                f"read of {rid} touches tombstoned roots; discard"
            )
        return rec
