# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-erased-memory-when-ttl-expiry-and-right-to-be-forgotten-erasure-share-a-namespace.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-erased-memory-when-ttl-expiry-and-right-to-be-forgotten-erasure-share-a-namespace.warrant.json
# Markdown SHA-256:   754a5e4c0e3f8b03c3ad24b4bc7df0361ec474e2fc56007dc64fc8358165e209
# Code AST SHA-256:   e3a18aaf7d16f3236f5f6bbd076558f094c0c139c137baa3fe863fe9c4fdbbce
# Verified Classes:   ErasureContractViolation, Record, TombstoneSet
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterable


class ErasureContractViolation(RuntimeError):
    """Raised when a retrieval path would serve a record whose erasure
    obligation is active but whose tombstone gate was not consulted or
    was consulted against a stale view."""


@dataclass(frozen=True)
class Record:
    record_id: str
    subject_id: str
    content: str
    expires_at: float
    derived_from: tuple[str, ...] = ()


@dataclass
class TombstoneSet:
    """Authoritative erasure state. Written BEFORE primary delete.
    Read on every retrieval path. Fails closed."""
    records: set[str] = field(default_factory=set)
    subjects: set[str] = field(default_factory=set)
    derived: set[str] = field(default_factory=set)  # ids reachable via derived_from

    def is_erased(self, rec: Record) -> bool:
        if rec.record_id in self.records:
            return True
        if rec.subject_id in self.subjects:
            return True
        if any(p in self.derived for p in rec.derived_from):
            return True
        return False


def recall_gated(
    query_neighbors: Iterable[Record],
    now: float,
    tombstones: TombstoneSet | None,
    max_staleness_s: float,
    tombstone_age_s: float,
) -> list[Record]:
    if tombstones is None:
        # Fail closed: no tombstone view means no recall.
        return []
    if tombstone_age_s > max_staleness_s:
        raise ErasureContractViolation(
            f"tombstone view stale by {tombstone_age_s:.3f}s "
            f"(bound {max_staleness_s:.3f}s); refusing to serve recall"
        )
    served: list[Record] = []
    for rec in query_neighbors:
        if rec.expires_at <= now:
            continue  # TTL expiry: soft, read-path predicate
        if tombstones.is_erased(rec):
            raise ErasureContractViolation(
                f"recall would serve erased record {rec.record_id} "
                f"(subject={rec.subject_id}); cache TTL had not expired"
            )
        served.append(rec)
    return served


def forget(
    subject_id: str,
    record_ids: Iterable[str],
    tombstones: TombstoneSet,
    primary_delete,
    cache_invalidate,
) -> None:
    """Write-ahead erasure. Tombstone first, then primary, then cache.
    Any crash between steps leaves the gate closed, never open."""
    ids = list(record_ids)
    tombstones.subjects.add(subject_id)
    for rid in ids:
        tombstones.records.add(rid)
    # Only after the gate is durable do we mutate the store.
    primary_delete(subject_id, ids)
    cache_invalidate(subject_id, ids)
