# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-forget-tool-compliance-failure-against-right-to-erasure-in-agentic-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-forget-tool-compliance-failure-against-right-to-erasure-in-agentic-pipelines.warrant.json
# Markdown SHA-256:   6bcdbc46cad0e89ba7350f5eee68e9579667ff28b8ffb1b38db68ba61f4ae198
# Code AST SHA-256:   55a5a072413ad287e004569c52e1771c2e521163b0a42f14f882cfc1463b2145
# Verified Classes:   ErasureComplianceError, ErasureRequest, ForgetReceipt
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ErasureComplianceError(RuntimeError):
    """Raised when a forget-tool success signal does not constitute physical erasure."""
    pass


@dataclass
class ErasureRequest:
    subject_id: str
    record_key: str
    epoch: int


@dataclass
class ForgetReceipt:
    logical_ok: bool
    physical_ok: bool
    epoch: int
    probe_reconstruction_distance: Optional[float] = None
    surviving_artifacts: list = field(default_factory=list)


# Reconstruction distance below this threshold means the probe recovered
# content traceable to the erased record; physical erasure has failed.
RECONSTRUCTION_THRESHOLD = 0.15


def verify_physical_erasure(req: ErasureRequest, receipt: ForgetReceipt) -> None:
    """Gate right-to-erasure reporting on physical, not logical, erasure.

    A forget tool returning success on a DB write acknowledgement attests
    only to logical erasure. Refuse to certify completion unless the receipt
    carries an independent probe and an epoch visible to every derivation layer.
    """
    if not receipt.logical_ok:
        raise ErasureComplianceError(
            f"logical erasure failed for {req.record_key}; nothing to verify"
        )

    if receipt.epoch <= req.epoch:
        raise ErasureComplianceError(
            f"erasure epoch not advanced for {req.record_key}: "
            f"receipt epoch {receipt.epoch} <= request epoch {req.epoch}; "
            f"caches and summaries may still replay the record"
        )

    if receipt.probe_reconstruction_distance is None:
        raise ErasureComplianceError(
            f"no post-erasure probe for {req.record_key}; "
            f"self-attested success is not a data-residency signal"
        )

    if receipt.probe_reconstruction_distance < RECONSTRUCTION_THRESHOLD:
        raise ErasureComplianceError(
            f"probe reconstructed erased content for {req.record_key} "
            f"(distance={receipt.probe_reconstruction_distance:.3f} < "
            f"{RECONSTRUCTION_THRESHOLD}); residual embedding neighborhood "
            f"or derived summary survives"
        )

    if receipt.surviving_artifacts:
        raise ErasureComplianceError(
            f"derived artifacts survived erasure for {req.record_key}: "
            f"{receipt.surviving_artifacts}"
        )

    if not receipt.physical_ok:
        raise ErasureComplianceError(
            f"physical erasure unverified for {req.record_key}"
        )


def report_erasure(req: ErasureRequest, receipt: ForgetReceipt) -> dict:
    """Return a compliance report; raises rather than over-reporting."""
    verify_physical_erasure(req, receipt)
    digest = hashlib.sha256(
        f"{req.subject_id}:{req.record_key}:{receipt.epoch}".encode()
    ).hexdigest()
    return {
        "status": "erased",
        "subject_id": req.subject_id,
        "record_key": req.record_key,
        "epoch": receipt.epoch,
        "receipt_digest": digest,
    }
