# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-prove-a-memory-is-forgotten-before-acknowledging-a-deletion-request.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-prove-a-memory-is-forgotten-before-acknowledging-a-deletion-request.warrant.json
# Markdown SHA-256:   8aadd442edc9d8cc5d37ff33dd6ae0218fa0fe8d605250cf596fc27cf03035a6
# Code AST SHA-256:   f438ab33f430bba65c66402c2e263c5c37a884170257469513fe591356d7d217
# Verified Classes:   PrematureErasureAcknowledgment, ErasureObligation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class PrematureErasureAcknowledgment(RuntimeError):
    """Raised when an instance attempts to acknowledge a deletion before every
    derived surface (summary versions, retrieval cache, peer contexts) is
    observably empty. Acknowledging early is a compliance and safety defect."""
    pass


@dataclass
class ErasureObligation:
    record_id: str
    source_version: int
    derived_summaries: list = field(default_factory=list)   # (summary_id, version)
    cache_keys: list = field(default_factory=list)
    peer_recipients: list = field(default_factory=list)      # instance ids
    opened_at: float = field(default_factory=time.time)
    acknowledged: bool = False


def probe_surfaces(memory, obligation: ErasureObligation) -> dict:
    """Read-after-forget probe across every surface the record could touch.
    Must run against the write-consistent primary, not a lagging replica."""
    report = {"primary": memory.read(obligation.record_id) is None}
    # A summary is clean only if no *version >= source_version* still encodes it.
    report["summaries"] = all(
        memory.summary_version(sid) < obligation.source_version
        for sid, _ in obligation.derived_summaries
    )
    report["cache"] = all(
        memory.cache_get(k) is None for k in obligation.cache_keys
    )
    report["peers"] = all(
        memory.peer_retraction_acked(pid, obligation.record_id)
        for pid in obligation.peer_recipients
    )
    return report


def acknowledge_erasure(memory, obligation: ErasureObligation,
                        flush_window_s: float = 90.0) -> None:
    """Acknowledge a GDPR erasure only after a clean multi-surface probe.
    Refuses (raises) rather than emitting a false acknowledgment."""
    if obligation.peer_recipients and not memory.has_retraction_channel():
        raise PrematureErasureAcknowledgment(
            f"record {obligation.record_id} was externalized to "
            f"{obligation.peer_recipients} but no retraction channel exists; "
            f"obligation is unfulfillable, refusing to acknowledge."
        )

    # Wait out the distiller flush window and cache TTL before trusting the probe.
    elapsed = time.time() - obligation.opened_at
    if elapsed < flush_window_s:
        time.sleep(flush_window_s - elapsed)

    report = probe_surfaces(memory, obligation)
    dirty = [surface for surface, clean in report.items() if not clean]
    if dirty:
        raise PrematureErasureAcknowledgment(
            f"erasure of {obligation.record_id} not materially complete; "
            f"surfaces still holding content: {dirty}. "
            f"Holding acknowledgment open."
        )

    obligation.acknowledged = True
    memory.emit_erasure_ack(obligation.record_id, evidence=report)
