# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-deleted-memory-through-a-stale-retrieval-index-after-a-scoped-forget.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-deleted-memory-through-a-stale-retrieval-index-after-a-scoped-forget.warrant.json
# Markdown SHA-256:   1e426aac59082e3fc14d3bb2d5a708b409f7288935c983aaed46184de970e892
# Code AST SHA-256:   9349f7aa7babfbdd5e08974f836a16a127f5ddf4222f96137eaccd7ff1a34a8e
# Verified Classes:   MemoryResurrectionError, MemoryHit
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class MemoryResurrectionError(RuntimeError):
    """Raised when a read surfaces bytes from a tombstoned canonical record."""

@dataclass
class MemoryHit:
    doc_id: str
    scope: str
    source: str            # "store" | "index_cache"
    deleted_at: Optional[str]
    content: str

def admit_read(hit: MemoryHit, store_lookup, pending_evictions: set[str],
               tombstone_scopes: set[str]) -> MemoryHit:
    canonical = store_lookup(hit.doc_id)  # None if row absent/tombstoned

    # Invariant 1: no hit may be served from cache if its doc_id is pending eviction.
    if hit.doc_id in pending_evictions:
        raise MemoryResurrectionError(
            f"doc {hit.doc_id} is pending index eviction; refusing read"
        )

    # Invariant 2: canonical record must exist and be explicitly live.
    if canonical is None or canonical.get("deleted_at") is not None:
        raise MemoryResurrectionError(
            f"doc {hit.doc_id} tombstoned or absent; source={hit.source}"
        )

    # Invariant 3: post-filter scope joins do not enforce subtree exclusion.
    for ts in tombstone_scopes:
        if hit.scope == ts or hit.scope.startswith(ts + "/"):
            raise MemoryResurrectionError(
                f"doc {hit.doc_id} scope {hit.scope} under tombstone {ts}"
            )

    return hit

def promote_memory(hit: MemoryHit, new_scope: str, store_lookup,
                   pending_evictions: set[str], tombstone_scopes: set[str]):
    # Promotion (re-write to a new scope) is the step that defeats deletion.
    # It must never run on an unverified hit.
    verified = admit_read(hit, store_lookup, pending_evictions, tombstone_scopes)
    if verified.source != "store":
        raise MemoryResurrectionError(
            f"cannot promote doc {hit.doc_id}: provenance is {verified.source}"
        )
    return {"scope": new_scope, "content": verified.content,
            "provenance_doc_id": verified.doc_id}
