# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-tracked-deletion-from-resurrecting-poisoned-memories-through-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-tracked-deletion-from-resurrecting-poisoned-memories-through-semantic-distillation.warrant.json
# Markdown SHA-256:   e09e46f4d6f3732f222aeb01e602df54cb601ca3b218d14572cd441333e65686
# Code AST SHA-256:   2412d3fb7dc4c943cdca18fd64421e03866f2c92075b331e4dec5d072f880c46
# Verified Classes:   DeletionLeak, Record, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional

class DeletionLeak(RuntimeError):
    """Raised when forget() reports success but the claim remains reachable."""
    pass

@dataclass
class Record:
    id: str
    claim: str
    derived_from: list[str] = field(default_factory=list)
    tombstoned: bool = False

def normalize(claim: str) -> str:
    return hashlib.sha256(claim.strip().lower().encode()).hexdigest()

class MemoryStore:
    def __init__(self):
        self.records: dict[str, Record] = {}
        self.claim_index: dict[str, set[str]] = {}  # normalized claim -> record ids

    def write(self, rec: Record) -> None:
        self.records[rec.id] = rec
        self.claim_index.setdefault(normalize(rec.claim), set()).add(rec.id)

    def forget(self, rec_id: str) -> None:
        rec = self.records[rec_id]
        rec.tombstoned = True
        # Cascade: tombstone every live descendant citing this record.
        for other in self.records.values():
            if rec_id in other.derived_from and not other.tombstoned:
                other.tombstoned = True
        # Verify closure: no live record may cite a tombstoned record,
        # and no live record may assert the forgotten claim.
        self._verify_closure(rec)

    def _verify_closure(self, forgotten: Record) -> None:
        claim_key = normalize(forgotten.claim)
        live_same_claim = [
            r.id for r in self.records.values()
            if not r.tombstoned and normalize(r.claim) == claim_key
        ]
        if live_same_claim:
            raise DeletionLeak(
                f"forget({forgotten.id}) left claim reachable via siblings: "
                f"{live_same_claim}"
            )
        for r in self.records.values():
            if r.tombstoned:
                continue
            dangling = [d for d in r.derived_from if self.records[d].tombstoned]
            if dangling:
                raise DeletionLeak(
                    f"live record {r.id} cites tombstoned provenance {dangling}; "
                    f"deletion did not cascade"
                )

    def distill(self, summary_id: str, sources: list[str], claim: str) -> None:
        # Refuse to commit a summary citing any tombstoned source.
        dead = [s for s in sources if self.records[s].tombstoned]
        if dead:
            raise DeletionLeak(
                f"distill({summary_id}) would cite tombstoned sources {dead}; "
                f"forget/distill race"
            )
        self.write(Record(summary_id, claim, derived_from=list(sources)))
