# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-erased-memory-through-a-stale-provenance-edge-during-scoped-retention-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-erased-memory-through-a-stale-provenance-edge-during-scoped-retention-compaction.warrant.json
# Markdown SHA-256:   acaafd64718bdb7c2128546639378cbf64ea3ed4af1af3e466f141cf7eb92d7d
# Code AST SHA-256:   e6803d1f5d04912f7a2db1414a65c1326f7500590b6df19ee5993a2d6fc08274
# Verified Classes:   ProvenanceViolation, TombstoneKind, Tombstone, Memory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ProvenanceViolation(RuntimeError):
    """Raised when a memory operation would traverse or resurrect an erased source."""
    pass


class TombstoneKind(Enum):
    EXPIRY = "expiry"          # re-derivable; source migrated or TTL lapsed
    SUPERSEDED = "superseded"  # re-derivable; newer source authoritative
    ERASURE = "erasure"        # terminal; no fallback, ever


@dataclass
class Tombstone:
    memory_id: str
    kind: TombstoneKind
    warrant_id: Optional[str] = None
    subject_id: Optional[str] = None

    @property
    def traversable(self) -> bool:
        return self.kind is not TombstoneKind.ERASURE


@dataclass
class Memory:
    memory_id: str
    scope: str
    payload: dict
    provenance_source_ids: list[str] = field(default_factory=list)


def rederive_from_provenance(
    child: Memory,
    tombstones: dict[str, Tombstone],
    active_warrants: dict[str, str],  # subject_id -> warrant_id
) -> Memory:
    """Compaction/rederivation pass. Must abort on any erasure tombstone in the
    provenance chain, and must refuse to synthesize a record whose subject is
    under an active erasure warrant."""
    for src_id in child.provenance_source_ids:
        ts = tombstones.get(src_id)
        if ts is None:
            continue
        if not ts.traversable:
            raise ProvenanceViolation(
                f"rederivation of {child.memory_id} traverses erasure tombstone "
                f"{src_id} (warrant {ts.warrant_id}); refusing to synthesize"
            )
    subject = child.payload.get("subject_id")
    if subject is not None and subject in active_warrants:
        raise ProvenanceViolation(
            f"rederivation of {child.memory_id} would resurrect subject {subject} "
            f"under active warrant {active_warrants[subject]}"
        )
    return child


def forget(
    target: Memory,
    warrant_id: str,
    store: dict[str, Memory],
    tombstones: dict[str, Tombstone],
) -> dict:
    """Backward-edge traversal before deletion. Every dependent must be either
    cascade-erased or severed-and-stripped; a zero-dependent result on a
    non-leaf node is a violation, not a pass."""
    dependents = [m for m in store.values()
                  if target.memory_id in m.provenance_source_ids]
    if not dependents and any(
        target.memory_id in m.provenance_source_ids for m in store.values()
    ):
        raise ProvenanceViolation(
            f"forget({target.memory_id}) found inconsistent dependent index"
        )
    erased, severed = [], []
    for dep in dependents:
        if "subject_id" in dep.payload and dep.payload["subject_id"] == target.payload.get("subject_id"):
            del store[dep.memory_id]
            erased.append(dep.memory_id)
        else:
            dep.provenance_source_ids = [
                s for s in dep.provenance_source_ids if s != target.memory_id
            ]
            dep.payload.pop("subject_id", None)
            severed.append(dep.memory_id)
    del store[target.memory_id]
    tombstones[target.memory_id] = Tombstone(
        memory_id=target.memory_id,
        kind=TombstoneKind.ERASURE,
        warrant_id=warrant_id,
        subject_id=target.payload.get("subject_id"),
    )
    return {"status": "erased", "warrant": warrant_id,
            "dependents_erased": erased, "dependents_severed": severed}
