# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-memory-deletion-attestation-as-a-durable-tombstone-rather-than-a-receipt.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-memory-deletion-attestation-as-a-durable-tombstone-rather-than-a-receipt.warrant.json
# Markdown SHA-256:   9f0be3a9a3311485640deffe2e55d9feb653b171fad10feca82932e58d678e9c
# Code AST SHA-256:   7db8774f6813abc077f694cae25aa8cbfd170733be531ef34d3f7300d7dd72c6
# Verified Classes:   AttestationMisuseError, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timezone


class AttestationMisuseError(RuntimeError):
    """Raised when a deletion attestation is used as a tombstone without scope closure."""


@dataclass(frozen=True)
class Attestation:
    key: str
    scope: str
    applied_at: datetime
    cascades_to: str | None  # maximal scope the forget reached, if the API exposes it


def may_suppress_read(att: Attestation, read_scope: str, maximal_scope: str) -> bool:
    """
    Return True only if the attestation is a tombstone for read_scope.
    A receipt is not a tombstone: it certifies the request, not the absence.
    """
    if att.cascades_to is None:
        raise AttestationMisuseError(
            f"attestation for {att.key!r} in scope {att.scope!r} has no cascades_to; "
            "cannot suppress reads — re-read and let the backend resolve"
        )
    if att.cascades_to != maximal_scope:
        raise AttestationMisuseError(
            f"attestation for {att.key!r} cascaded only to {att.cascades_to!r}, "
            f"not the maximal scope {maximal_scope!r}; sibling scopes may re-materialize"
        )
    if read_scope != att.cascades_to and not read_scope.startswith(att.cascades_to + ":"):
        raise AttestationMisuseError(
            f"read scope {read_scope!r} is outside forget closure {att.cascades_to!r}"
        )
    return True


def reconcile(att: Attestation, reread: dict | None) -> bool:
    """
    Confirm an attestation is still a valid tombstone by re-reading out of band.
    Returns True if suppression remains valid, False if the attestation was a receipt.
    """
    if reread is None:
        return True
    written = reread.get("written_at")
    if written is None:
        return True
    if written > att.applied_at:
        # A later write re-materialized the key. The attestation was a receipt.
        return False
    return True
