# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-erasure-it-has-already-acknowledged-the-tombstone-ordering-invariant-across-scoped-persistence-ttl-decay-and-gdp.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-erasure-it-has-already-acknowledged-the-tombstone-ordering-invariant-across-scoped-persistence-ttl-decay-and-gdp.warrant.json
# Markdown SHA-256:   403d29a9a24245dbde7833f875834581bc23e4df7cfb98cb53f0bf10d965e212
# Code AST SHA-256:   a19f9fcba46368b5f88e44d1cd4408fbb68d0577419e072bb3daa79b2e826704
# Verified Classes:   ErasureLineageViolation, DerivedRecord, ForgetResult, MemoryErasureGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ErasureLineageViolation(RuntimeError):
    """Raised when a forget acknowledgement would be observationally reversible."""
    pass


@dataclass
class DerivedRecord:
    scope: str
    version: int
    source_keys: list[str]


@dataclass
class ForgetResult:
    key: str
    tombstone_v: int
    status: str


class MemoryErasureGuard:
    def __init__(self, lineage_index, context_window_keys):
        self.lineage = lineage_index          # scope -> list[DerivedRecord]
        self.context_keys = set(context_window_keys)

    def certify(self, key: str, result: ForgetResult, readable_scopes: list[str]) -> dict:
        if result.status != "deleted":
            raise ErasureLineageViolation(
                f"forget for {key!r} returned status={result.status!r}; cannot certify"
            )

        # Invariant 1: no live derived record may out-version the tombstone.
        for scope in readable_scopes:
            for d in self.lineage.get(scope, []):
                if key in d.source_keys and d.version >= result.tombstone_v:
                    raise ErasureLineageViolation(
                        f"derived record in scope={scope!r} v={d.version} "
                        f">= tombstone_v={result.tombstone_v} for key={key!r}; "
                        f"erasure is observationally reversible"
                    )

        # Invariant 2: the erased value must not still be live in context.
        if key in self.context_keys:
            raise ErasureLineageViolation(
                f"key={key!r} still present in active context window; "
                f"redact before acknowledging"
            )

        return {
            "erasure": "physical_and_derived",
            "certified": True,
            "tombstone_v": result.tombstone_v,
            "residual_scopes": [],
        }
