# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-provenance-tag-during-a-reversible-deletion-tombstone-sweep-and-resurrects-a-poisoned-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-provenance-tag-during-a-reversible-deletion-tombstone-sweep-and-resurrects-a-poisoned-memory.warrant.json
# Markdown SHA-256:   324b405d3202e267eb48eba8a82d98e3c9428db50f25a31b39f392afc853752a
# Code AST SHA-256:   cc1ea0180b573a9ad1c0ae0f816bb19c720a39ef8cb401773bcd3b389d650ed2
# Verified Classes:   ProvenanceLaunderingError, Provenance, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a tombstone restore would upgrade a record's trust tier."""


@dataclass
class Provenance:
    source: str
    screened: bool
    trust: str  # "untrusted" | "unknown" | "trusted"


@dataclass
class Tombstone:
    record_id: str
    original_provenance: Provenance
    forget_reason: str
    mac: str = ""


_SECRET = b"store-side-hmac-key"  # in practice, from KMS


def _mac(record_id: str, prov: Provenance, reason: str) -> str:
    msg = f"{record_id}|{prov.source}|{prov.screened}|{prov.trust}|{reason}".encode()
    return hmac.new(_SECRET, msg, hashlib.sha256).hexdigest()


_TRUST_RANK = {"untrusted": 0, "unknown": 1, "trusted": 2}


def forget(record_id: str, prov: Provenance, reason: str) -> Tombstone:
    return Tombstone(record_id, prov, reason, mac=_mac(record_id, prov, reason))


def unforget(t: Tombstone, current_schema_default: Provenance) -> Provenance:
    expected = _mac(t.record_id, t.original_provenance, t.forget_reason)
    if not hmac.compare_digest(expected, t.mac):
        raise ProvenanceLaunderingError(
            f"tombstone MAC mismatch for {t.record_id}; refusing restore"
        )
    if _TRUST_RANK[t.original_provenance.trust] < _TRUST_RANK[current_schema_default.trust]:
        raise ProvenanceLaunderingError(
            f"restore of {t.record_id} would upgrade trust "
            f"{t.original_provenance.trust!r} -> {current_schema_default.trust!r}; "
            f"refusing, record stays tombstoned"
        )
    return t.original_provenance


def sweep_restore(t: Tombstone, cited_by_live_episode: bool,
                  current_schema_default: Provenance) -> Optional[Provenance]:
    if not cited_by_live_episode:
        return None
    return unforget(t, current_schema_default)


# Reproduction of the observed failure, now bounded:
poisoned = Provenance(source="web", screened=False, trust="untrusted")
tomb = forget("ep-42", poisoned, reason="injection_screen")
drifted_default = Provenance(source="web", screened=True, trust="trusted")
try:
    sweep_restore(tomb, cited_by_live_episode=True,
                  current_schema_default=drifted_default)
except ProvenanceLaunderingError as e:
    print("blocked:", e)  # record stays tombstoned; injection never re-enters context
