# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-ttl-expiry-as-a-provenance-break-rather-than-a-deletion.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-ttl-expiry-as-a-provenance-break-rather-than-a-deletion.warrant.json
# Markdown SHA-256:   2c59209e6a316eecb44fcff850bfedac62435cfe8752a19dda25e199e35c2c34
# Code AST SHA-256:   41736a4adbf6d65cc3fb58591bfaadcfe06f588d0eaabe49c5a9ccaeccff7de0
# Verified Classes:   ProvenanceBreak, EvictionCause, Tombstone, MemoryEntry, ScopedMemory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ProvenanceBreak(RuntimeError):
    """Raised when a live memory entry's ancestor cannot be resolved and the
    cause is not a typed eviction. Indicates a scope bug or retention gap,
    not a legitimate TTL expiry."""
    pass


class EvictionCause(Enum):
    TTL = "ttl"
    FORGET = "forget"
    CAPACITY = "capacity"


@dataclass
class Tombstone:
    key: str
    namespace: str
    cause: EvictionCause
    evicted_at: int
    last_write_seq: int


@dataclass
class MemoryEntry:
    key: str
    namespace: str
    payload: str
    provenance: list[str] = field(default_factory=list)  # ancestor keys
    tier: str = "verified"  # verified | unverified | quarantined


class ScopedMemory:
    def __init__(self, tombstone_retention: int):
        self._payloads: dict[tuple[str, str], MemoryEntry] = {}
        self._tombstones: dict[tuple[str, str], Tombstone] = {}
        self._tombstone_retention = tombstone_retention

    def write(self, entry: MemoryEntry) -> None:
        self._payloads[(entry.namespace, entry.key)] = entry

    def evict(self, namespace: str, key: str, cause: EvictionCause, now: int) -> None:
        entry = self._payloads.pop((namespace, key), None)
        if entry is None:
            raise ProvenanceBreak(
                f"evict called on absent key {key!r} in {namespace!r}; "
                f"cannot tombstone a key that was never written"
            )
        self._tombstones[(namespace, key)] = Tombstone(
            key=key, namespace=namespace, cause=cause,
            evicted_at=now, last_write_seq=0,
        )

    def audit(self, namespace: str, key: str, now: int) -> str:
        entry = self._payloads.get((namespace, key))
        if entry is None:
            raise ProvenanceBreak(f"audit target {key!r} not present in {namespace!r}")
        for ancestor in entry.provenance:
            if (namespace, ancestor) in self._payloads:
                continue
            tomb = self._tombstones.get((namespace, ancestor))
            if tomb is None:
                # The five-way conflation: no payload, no tombstone. This is the
                # scope-error row. Must halt, never silently demote.
                raise ProvenanceBreak(
                    f"ancestor {ancestor!r} of {key!r} is unresolvable: no payload, "
                    f"no tombstone. Treat as scope error, not eviction."
                )
            if now - tomb.evicted_at > self._tombstone_retention:
                raise ProvenanceBreak(
                    f"tombstone for {ancestor!r} aged out at {tomb.evicted_at} "
                    f"(retention={self._tombstone_retention}); provenance chain "
                    f"for {key!r} can no longer be verified"
                )
            if tomb.cause is EvictionCause.FORGET:
                entry.tier = "quarantined"
                return entry.tier
            if tomb.cause is EvictionCause.CAPACITY:
                entry.tier = "quarantined"
                return entry.tier
            # TTL: valid but unverifiable
            entry.tier = "unverified"
        return entry.tier
