# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-forgotten-memory-that-is-still-live-via-a-stale-scope-handle-after-right-to-forget-enforcement.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-forgotten-memory-that-is-still-live-via-a-stale-scope-handle-after-right-to-forget-enforcement.warrant.json
# Markdown SHA-256:   662277306e4bf7620bd3223ee709623fe0b535d2e03ff136140f0688dbf4e9fc
# Code AST SHA-256:   62059a88c10382896affea70c0758a421314ea436a2487065dc8fba3190162bf
# Verified Classes:   StaleScopeHandle, TombstoneVisibilityViolation, ScopeHandle, ScopeRecord, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleScopeHandle(RuntimeError):
    """Raised when a scope handle's retention_epoch does not match the canonical scope record,
    or when a read would surface a tombstone created after the handle was minted."""


class TombstoneVisibilityViolation(RuntimeError):
    """Raised when a read returns records whose tombstone_epoch exceeds the reader's epoch."""


@dataclass(frozen=True)
class ScopeHandle:
    scope_id: str
    retention_epoch: int


@dataclass(frozen=True)
class ScopeRecord:
    scope_id: str
    retention_epoch: int


@dataclass(frozen=True)
class MemoryRecord:
    content: str
    tombstone_epoch: int | None  # None = live


def read_memory(handle: ScopeHandle, canonical: ScopeRecord,
                records: list[MemoryRecord], query: str) -> list[MemoryRecord]:
    # Invariant: handle epoch must equal canonical epoch at read time.
    if handle.scope_id != canonical.scope_id:
        raise StaleScopeHandle(
            f"handle scope {handle.scope_id} != canonical {canonical.scope_id}"
        )
    if handle.retention_epoch != canonical.retention_epoch:
        raise StaleScopeHandle(
            f"handle epoch {handle.retention_epoch} != canonical epoch "
            f"{canonical.retention_epoch} for scope {handle.scope_id}; "
            f"re-resolve scope and purge context derived from stale handle"
        )

    visible: list[MemoryRecord] = []
    for r in records:
        if r.tombstone_epoch is not None and r.tombstone_epoch > handle.retention_epoch:
            # Tombstone was written by a policy this handle has not observed.
            raise TombstoneVisibilityViolation(
                f"record tombstoned at epoch {r.tombstone_epoch} but reader is at "
                f"epoch {handle.retention_epoch}; fail closed"
            )
        if r.tombstone_epoch is None:
            visible.append(r)
    return visible


def enforce_right_to_forget(canonical: ScopeRecord, records: list[MemoryRecord],
                            distilled: list[tuple[str, int]]) -> tuple[ScopeRecord, list[MemoryRecord], list[str]]:
    new_epoch = canonical.retention_epoch + 1
    tombstoned = [
        MemoryRecord(content=r.content, tombstone_epoch=new_epoch)
        if r.tombstone_epoch is None else r
        for r in records
    ]
    # Cascade to distilled semantic memories whose provenance epoch is <= erasure epoch.
    purged_distilled = [claim for claim, src_epoch in distilled if src_epoch <= canonical.retention_epoch]
    surviving_distilled = [claim for claim, src_epoch in distilled if src_epoch > canonical.retention_epoch]
    if purged_distilled and not surviving_distilled:
        pass  # all distilled claims cited forgotten data; context must be invalidated
    return ScopeRecord(canonical.scope_id, new_epoch), tombstoned, surviving_distilled
