# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-retention-scope-leakage-when-a-forget-tool-call-succeeds-but-a-derived-summary-still-carries-the-deleted-fact.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-retention-scope-leakage-when-a-forget-tool-call-succeeds-but-a-derived-summary-still-carries-the-deleted-fact.warrant.json
# Markdown SHA-256:   89a90f522248ebe966cdde6d4a60e3e75f093c63ce4269fba05a5d922610a655
# Code AST SHA-256:   8d465f62291ae7d3225c1f6fd2b4e12574ced0088ed88d7be6fc047ed161056e
# Verified Classes:   UnverifiedDeletionError, ForgetResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnverifiedDeletionError(RuntimeError):
    """Raised when a forget call reports success but a derivative may survive."""
    pass


@dataclass
class ForgetResult:
    handle: str
    deleted: bool
    cascaded: int
    source_was_distilled: bool


def assert_deletion_complete(result: ForgetResult, reachability_hits: int) -> None:
    """
    Enforce the invariant: a forget is only 'complete' when cascade closure
    covers every attributed derivative AND a post-tombstone reachability probe
    finds no surviving near-neighbor in any longer-lived scope.
    """
    if not result.deleted:
        raise UnverifiedDeletionError(
            f"forget({result.handle}) did not tombstone the record"
        )

    if result.source_was_distilled and result.cascaded == 0:
        # The signature of retention-scope leakage: the source fed a
        # distillation job, but no derivative was cascaded. The tool's
        # success is locally true and globally false.
        raise UnverifiedDeletionError(
            f"forget({result.handle}) returned success with cascaded=0, but the "
            f"source participated in distillation; derivatives in longer-lived "
            f"scopes are unattributed and may still carry the fact"
        )

    if reachability_hits > 0:
        raise UnverifiedDeletionError(
            f"post-tombstone reachability probe found {reachability_hits} "
            f"surviving near-neighbor(s) of the deleted fact in a longer-lived "
            f"scope; deletion is not complete"
        )
