# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-deletion-attestation-when-a-scoped-retention-policy-re-anchors-memory-under-a-new-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-deletion-attestation-when-a-scoped-retention-policy-re-anchors-memory-under-a-new-epoch.warrant.json
# Markdown SHA-256:   631641408b532af7edab8461ff91bbe469bdea2fc6090b05fe2687128709f944
# Code AST SHA-256:   27df2a1a3eae2abd52c4e7bc4790c93b2db09e6431094821a833fdd36223db85
# Verified Classes:   StaleAttestationError, Attestation, RecordState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a deletion attestation no longer covers the record's current epoch/scope."""


@dataclass(frozen=True)
class Attestation:
    record_id: str
    scope: str
    epoch: int
    record_hash: str
    attested_at: int


@dataclass(frozen=True)
class RecordState:
    record_id: str
    epoch: int
    scope_ancestry: frozenset
    record_hash: str
    last_policy_mutation: int


def verify_attestation(att: Attestation, state: Optional[RecordState]) -> bool:
    """Return True iff the attestation is authoritative for the record's CURRENT state.

    A None state means the record is physically absent -> attestation trivially holds.
    """
    if state is None:
        return True

    # Clause 1: epoch must match. Any advance means re-anchor -> assume resurrection.
    if att.epoch != state.epoch:
        raise StaleAttestationError(
            f"epoch mismatch for {att.record_id}: attested E{att.epoch}, current E{state.epoch}"
        )

    # Clause 2: attested scope must still dominate every scope retaining the record.
    if att.scope not in state.scope_ancestry:
        raise StaleAttestationError(
            f"scope {att.scope!r} no longer dominates {att.record_id} "
            f"(ancestry={sorted(state.scope_ancestry)})"
        )

    # Clause 3: content hash must be unchanged (no resurrection/rewrite).
    if att.record_hash != state.record_hash:
        raise StaleAttestationError(
            f"record {att.record_id} resurrected/rewritten under E{state.epoch}"
        )

    # Clause 4: no policy mutation after the attestation was issued.
    if att.attested_at < state.last_policy_mutation:
        raise StaleAttestationError(
            f"attestation for {att.record_id} predates last policy mutation "
            f"({att.attested_at} < {state.last_policy_mutation})"
        )

    return True


def resume_with_ledger(ledger: dict, store) -> dict:
    """Replay a forget-ledger, demoting stale entries to UNKNOWN and re-verifying."""
    resolved = {}
    for record_id, att in ledger.items():
        state = store.get_record_state(record_id)  # None if physically absent
        try:
            verify_attestation(att, state)
            resolved[record_id] = "FORGOTTEN"
        except StaleAttestationError:
            # Demote to UNKNOWN: must re-read or re-forget under current epoch.
            resolved[record_id] = "UNKNOWN"
    return resolved
