# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-call-has-silently-orphaned-a-derived-memory-it-must-also-erase.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-forget-call-has-silently-orphaned-a-derived-memory-it-must-also-erase.warrant.json
# Markdown SHA-256:   1e0059b7bf18c75828208420cf44dfa615225d5b6df1e89fa15c28a364c2664c
# Code AST SHA-256:   84313341d0ffad0604a6d401e0164e90e3105d702f05fa2a42378a1846d672e0
# Verified Classes:   UnverifiedErasureError, OrphanedDerivativeError, ForgetResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnverifiedErasureError(RuntimeError):
    """Raised when a forget call reports completion without a verified closure."""
    pass


class OrphanedDerivativeError(RuntimeError):
    """Raised when erasure leaves derived records whose provenance reaches the subject."""
    pass


@dataclass
class ForgetResult:
    status: str                      # "complete" | "partial" | "blocked"
    deleted: int
    closure_verified: bool
    orphans: list = field(default_factory=list)   # derived_from chains still live
    unprovable: list = field(default_factory=list)  # derived_from == empty, body matches subject


def enforce_erasure(subject_id: str, result: ForgetResult) -> None:
    """
    Gate that an orchestrator MUST run on every forget() response before
    closing an erasure ticket. Fails closed on any unverified closure.
    """
    # A "complete" that was not closure-verified is a contradiction: the tool
    # deleted the tagged set but did not prove the derivation closure is empty.
    if result.status == "complete" and not result.closure_verified:
        raise UnverifiedErasureError(
            f"forget({subject_id}) returned status=complete but "
            f"closure_verified=False; {len(result.orphans)} orphan(s) may "
            f"still carry derived personal data. Refusing to close ticket."
        )

    # Un-provable records (derived_from empty, body matches subject) are the
    # worst case: the tool cannot prove erasure. Quarantine, do not proceed.
    if result.unprovable:
        raise OrphanedDerivativeError(
            f"forget({subject_id}) left {len(result.unprovable)} record(s) with "
            f"no derivation edge but subject-matching content; these are "
            f"un-erasable by construction. Move to quarantine retention class "
            f"and exclude from retrieval before resuming."
        )

    # Partial with a resolvable orphan set is resumable: re-issue forget on
    # the orphan IDs. It is NOT terminal and must not be reported as complete.
    if result.status == "partial" and result.orphans:
        raise OrphanedDerivativeError(
            f"forget({subject_id}) is partial: {len(result.orphans)} derived "
            f"record(s) still reachable via derived_from. Re-issue forget with "
            f"orphan IDs as explicit targets; do not close ticket."
        )

    if result.status == "complete" and result.closure_verified and not result.orphans:
        return  # the only path on which the ticket may close
