# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-deletion-when-forgetting-is-probabilistic-the-tombstone-replay-gap-in-gdpr-aligned-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-deletion-when-forgetting-is-probabilistic-the-tombstone-replay-gap-in-gdpr-aligned-agent-memory.warrant.json
# Markdown SHA-256:   5117160e8e1502a1e64862ae3c47b9386a53fd2182c13551fa3f61c46096e7d3
# Code AST SHA-256:   9aa57e3e3a868c3fc6697b6dbcfb8914e7b8b4f70c818f6a9042e705974be833
# Verified Classes:   ErasureBarrierViolation, DerivedFact, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class ErasureBarrierViolation(RuntimeError):
    """Raised when a derivation attempts to admit a fact whose provenance
    predates the subject's erasure epoch (i.e. would resurrect erased data)."""


@dataclass
class DerivedFact:
    subject: str
    predicate: str
    obj: str
    source_epoch: int


@dataclass
class MemoryStore:
    # subject -> erasure epoch (monotonic; higher = later erasure)
    erasure_epoch: dict[str, int] = field(default_factory=dict)
    admitted: list[DerivedFact] = field(default_factory=list)

    def erase(self, subject: str, current_epoch: int) -> None:
        # Row delete + vector purge happen elsewhere; this records the barrier.
        self.erasure_epoch[subject] = max(
            self.erasure_epoch.get(subject, 0), current_epoch
        )

    def admit(self, fact: DerivedFact) -> None:
        """Admission gate for the distillation pipeline. Must be the ONLY
        writer into the retrievable semantic namespace."""
        barrier = self.erasure_epoch.get(fact.subject)
        if barrier is not None and fact.source_epoch < barrier:
            raise ErasureBarrierViolation(
                f"refusing to admit ({fact.subject}, {fact.predicate}) "
                f"derived from epoch {fact.source_epoch} < erasure epoch {barrier}"
            )
        self.admitted.append(fact)


def nightly_distill(
    store: MemoryStore, candidates: Iterable[DerivedFact]
) -> list[DerivedFact]:
    """Simulates the async re-derivation job. Returns admitted facts; any
    resurrection attempt raises and is surfaced to the audit trail."""
    admitted: list[DerivedFact] = []
    for fact in candidates:
        store.admit(fact)  # raises ErasureBarrierViolation on violation
        admitted.append(fact)
    return admitted


def audit_no_resurrection(store: MemoryStore, subject: str) -> None:
    """Deterministic post-erasure check: no admitted fact over `subject`
    may carry provenance older than its erasure epoch."""
    barrier = store.erasure_epoch.get(subject)
    if barrier is None:
        return
    for fact in store.admitted:
        if fact.subject == subject and fact.source_epoch < barrier:
            raise ErasureBarrierViolation(
                f"audit found resurrected fact for {subject} "
                f"from epoch {fact.source_epoch}"
            )
