# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-memory-erasure-request-has-been-satisfied-tombstone-visibility-versus-storage-reclamation-in-provenance-bearing-mem.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-memory-erasure-request-has-been-satisfied-tombstone-visibility-versus-storage-reclamation-in-provenance-bearing-mem.warrant.json
# Markdown SHA-256:   b4415c55d072eb1f1c8074ad9dba7bb79dd77382db83cc7d0b251db075db6503
# Code AST SHA-256:   db274ab3bdef2a1245e0d56b884c3b91fdad87ac228b3c5b096343ae3c1e219e
# Verified Classes:   ErasureNotSatisfiedError, ErasureProbe
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ErasureNotSatisfiedError(RuntimeError):
    """Raised when a forget() call has returned but reclamation is not verified."""


@dataclass
class ErasureProbe:
    subject_id: str
    tombstone_epoch: int
    reclamation_epoch: int | None       # None if API does not expose it
    raw_scan_absent: bool               # storage-layer scan bypassing tombstone filter
    derived_indices_clean: bool         # ANN, inverted, summary caches invalidated
    tombstone_durable_beyond_max_ttl: bool


def assert_erasure_satisfied(probe: ErasureProbe, max_ttl_seconds: int,
                             tombstone_age_seconds: int) -> None:
    """
    Gate compliance acknowledgment on physical reclamation, not on the
    tombstone-filtered read path (which always reports success immediately).
    """
    if not probe.tombstone_durable_beyond_max_ttl:
        raise ErasureNotSatisfiedError(
            f"tombstone for {probe.subject_id!r} does not outlive max_ttl="
            f"{max_ttl_seconds}s; a write with a future TTL can resurrect the entry"
        )

    if tombstone_age_seconds < max_ttl_seconds:
        raise ErasureNotSatisfiedError(
            f"tombstone for {probe.subject_id!r} is only {tombstone_age_seconds}s old; "
            f"resurrection window open until {max_ttl_seconds}s"
        )

    if probe.reclamation_epoch is None:
        raise ErasureNotSatisfiedError(
            f"API exposes no reclamation_epoch for {probe.subject_id!r}; "
            f"cannot distinguish logical erasure from physical reclamation"
        )

    if probe.reclamation_epoch < probe.tombstone_epoch:
        raise ErasureNotSatisfiedError(
            f"reclamation_epoch={probe.reclamation_epoch} precedes "
            f"tombstone_epoch={probe.tombstone_epoch} for {probe.subject_id!r}; "
            f"storage compaction has not caught up"
        )

    if not probe.raw_scan_absent:
        raise ErasureNotSatisfiedError(
            f"raw storage scan still returns payload for {probe.subject_id!r} "
            f"despite tombstone_epoch={probe.tombstone_epoch}"
        )

    if not probe.derived_indices_clean:
        raise ErasureNotSatisfiedError(
            f"derived indices (ANN/inverted/summary) still reference "
            f"{probe.subject_id!r}; content-hash lookup may leak"
        )


def acknowledge_with_backoff(api, subject_id: str, max_ttl_seconds: int,
                             ceiling_seconds: int = 96 * 3600) -> None:
    start = time.monotonic()
    interval = 300.0
    while True:
        probe = api.probe_erasure(subject_id)
        age = time.monotonic() - start
        try:
            assert_erasure_satisfied(probe, max_ttl_seconds, int(age))
            api.emit_compliance_ack(subject_id, probe.reclamation_epoch)
            return
        except ErasureNotSatisfiedError:
            if age >= ceiling_seconds:
                raise ErasureNotSatisfiedError(
                    f"erasure for {subject_id!r} unverified after {age:.0f}s; "
                    f"escalate to human operator"
                )
            time.sleep(min(interval, ceiling_seconds - age))
            interval = min(interval * 1.5, 3600.0)
