# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-retention-policy-tombstone-gap-when-an-agent-s-forget-tool-acknowledges-deletion-but-the-underlying-episodic-store.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-retention-policy-tombstone-gap-when-an-agent-s-forget-tool-acknowledges-deletion-but-the-underlying-episodic-store.warrant.json
# Markdown SHA-256:   a8c0748ab6e43b786d4ed6b67af16efb4a67f96de480741d4c9933bd421efb24
# Code AST SHA-256:   4f2b3df1fb3c36f76e1390cb362b54d5872be9ff1ae6a0a39b606657a1baff0f
# Verified Classes:   ResurrectionBoundaryError, Tombstone, DeletionLedger, SemanticCandidate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ResurrectionBoundaryError(RuntimeError):
    """Raised when a distillation pass would re-derive a tombstoned fact."""
    pass


@dataclass
class Tombstone:
    key: str
    deleted_at: int
    source_episode_ids: frozenset[int]


@dataclass
class DeletionLedger:
    entries: list[Tombstone] = field(default_factory=list)

    def add(self, key: str, deleted_at: int, source_episode_ids: Iterable[int]) -> None:
        self.entries.append(
            Tombstone(key, deleted_at, frozenset(source_episode_ids))
        )

    def suppressed_episode_ids(self) -> frozenset[int]:
        out: set[int] = set()
        for e in self.entries:
            out |= e.source_episode_ids
        return frozenset(out)


@dataclass
class SemanticCandidate:
    text: str
    source_episode_ids: frozenset[int]


def distill(
    candidates: Iterable[SemanticCandidate],
    ledger: DeletionLedger,
    strict: bool = True,
) -> list[SemanticCandidate]:
    """Emit only candidates whose provenance does not intersect the tombstone set."""
    suppressed = ledger.suppressed_episode_ids()
    emitted: list[SemanticCandidate] = []
    for c in candidates:
        overlap = c.source_episode_ids & suppressed
        if overlap:
            if strict:
                raise ResurrectionBoundaryError(
                    f"candidate {c.text!r} derives from tombstoned episodes "
                    f"{sorted(overlap)}; refusing to emit (tier-local deletion "
                    f"would resurrect a forgotten fact)"
                )
            continue
        emitted.append(c)
    return emitted


def forget_and_verify(
    key: str,
    deleted_at: int,
    source_episode_ids: Iterable[int],
    ledger: DeletionLedger,
    pending_candidates: Iterable[SemanticCandidate],
) -> None:
    ledger.add(key, deleted_at, source_episode_ids)
    # Enforce immediately: the deletion is only valid if no in-flight
    # distillation can re-derive it.
    try:
        distill(pending_candidates, ledger, strict=True)
    except ResurrectionBoundaryError:
        # Deletion is tier-local and unenforceable; surface it rather than
        # returning a misleading success receipt.
        raise ResurrectionBoundaryError(
            f"forget({key!r}) cannot be guaranteed: re-derivation path "
            f"would resurrect the fact. Quarantine source episodes or "
            f"suppress the distiller before reporting success."
        )
