# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-facts-through-semantic-cache-rehydration-after-a-scoped-ttl-erasure.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-forgotten-facts-through-semantic-cache-rehydration-after-a-scoped-ttl-erasure.warrant.json
# Markdown SHA-256:   8c93686f5eb255038cde123d81b106087c7210fc9b9acd834fcecdea8af39802
# Code AST SHA-256:   738dd51e4e0eedaf27f4837ff63629dff0b4e270a767a989e7aaac8c506fa493
# Verified Classes:   ErasureInvariantViolation, DerivedArtifact, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class ErasureInvariantViolation(RuntimeError):
    """Raised when a forgotten fact remains recoverable through a derived store."""


@dataclass
class DerivedArtifact:
    artifact_id: str
    text: str
    sources: frozenset[str]  # record_ids this artifact was computed from


@dataclass
class MemoryStore:
    rows: dict[str, str] = field(default_factory=dict)
    tombstoned: set[str] = field(default_factory=set)
    derived: dict[str, DerivedArtifact] = field(default_factory=dict)

    def write(self, record_id: str, text: str, derived_from: Iterable[str] = ()) -> None:
        self.rows[record_id] = text
        # Derived artifacts MUST declare their provenance at write time.
        self.derived[record_id] = DerivedArtifact(
            artifact_id=record_id, text=text, sources=frozenset(derived_from) | {record_id}
        )

    def forget(self, record_id: str) -> None:
        self.rows.pop(record_id, None)
        self.tombstoned.add(record_id)
        # Transitive invalidation: drop every artifact whose provenance intersects.
        for aid in [a for a, art in self.derived.items() if record_id in art.sources]:
            del self.derived[aid]

    def read(self, record_id: str) -> str | None:
        # Serve-time erasure check, not just index-build-time.
        if record_id in self.tombstoned:
            return None
        return self.rows.get(record_id)

    def probe_forgotten(self, record_id: str) -> None:
        """Assert the fact is unrecoverable through any read path."""
        if self.read(record_id) is not None:
            raise ErasureInvariantViolation(
                f"row {record_id} still readable after forget"
            )
        for art in self.derived.values():
            if record_id in art.sources:
                raise ErasureInvariantViolation(
                    f"derived artifact {art.artifact_id} still carries forgotten "
                    f"record {record_id} via sources={sorted(art.sources)}"
                )


def demonstrate() -> None:
    store = MemoryStore()
    # A summarizer that forgets to record provenance — the failure trigger.
    store.write("rec_1", "employer=Northwind; badge expires 2025-07-01")
    store.derived["digest_7"] = DerivedArtifact(
        artifact_id="digest_7",
        text="u_8812 works at Northwind; access dates cluster mid-year",
        sources=frozenset(),  # provenance gap: empty sources
    )
    store.forget("rec_1")
    store.probe_forgotten("rec_1")  # passes: digest has no sources, but also no link
    # Now the realistic failure: digest DID consume rec_1 but declared nothing,
    # so the probe cannot see the leak. Assert the stronger contract:
    for art in store.derived.values():
        if "Northwind" in art.text and "rec_1" not in art.sources:
            raise ErasureInvariantViolation(
                f"artifact {art.artifact_id} contains forgotten content but "
                f"declares no provenance to rec_1 — erasure unverifiable"
            )


if __name__ == "__main__":
    demonstrate()
