# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-retention-governed-forget-operations-against-a-memory-store-whose-schema-aliases-read-write-and-forget-through-a-shared.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-retention-governed-forget-operations-against-a-memory-store-whose-schema-aliases-read-write-and-forget-through-a-shared.warrant.json
# Markdown SHA-256:   d12e74d5f8e5ad3bd46bb3d0281a947a03bd54eb4bd66125a7256c171d3775af
# Code AST SHA-256:   300a9e3d6cc1a82570c691a505e90df24e918572d3f4050f465895f163fd5bbd
# Verified Classes:   RetentionClosureViolation, DanglingProvenanceError, Record
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class RetentionClosureViolation(RuntimeError):
    """Raised when a forget target's provenance closure contains a held ancestor."""


class DanglingProvenanceError(RuntimeError):
    """Raised when a read resolves a derived_from pointer to a non-tombstoned absence."""


@dataclass(frozen=True)
class Record:
    record_id: str
    tier: str                # "episodic" | "semantic" | "legal_hold"
    derived_from: Optional[str]
    deleted: bool = False
    tombstone: bool = False


TIER_RANK = {"episodic": 0, "semantic": 1, "legal_hold": 2}
MAX_CLOSURE_DEPTH = 8


def assert_forget_admissible(
    target_id: str,
    token_tier: str,
    store: dict[str, Record],
) -> None:
    """Refuse a bare forget if any ancestor in the provenance closure outranks the token."""
    seen: set[str] = set()
    cursor: Optional[str] = target_id
    depth = 0
    while cursor is not None and depth < MAX_CLOSURE_DEPTH:
        if cursor in seen:
            raise RetentionClosureViolation(
                f"cycle detected in provenance closure at {cursor}"
            )
        seen.add(cursor)
        rec = store.get(cursor)
        if rec is None or rec.tombstone:
            # A tombstoned ancestor is already policy-deleted; admissible.
            break
        if TIER_RANK[rec.tier] > TIER_RANK[token_tier]:
            raise RetentionClosureViolation(
                f"forget({target_id}) blocked: ancestor {cursor} "
                f"tier={rec.tier} outranks token tier={token_tier}"
            )
        cursor = rec.derived_from
        depth += 1
    if depth >= MAX_CLOSURE_DEPTH:
        raise RetentionClosureViolation(
            f"forget({target_id}) blocked: closure depth exceeded {MAX_CLOSURE_DEPTH}"
        )


def read_provenance(record_id: str, store: dict[str, Record]) -> str:
    rec = store.get(record_id)
    if rec is None:
        raise DanglingProvenanceError(
            f"record {record_id} absent with no tombstone; cannot distinguish "
            f"policy-deletion from never-existed"
        )
    if rec.deleted and not rec.tombstone:
        raise DanglingProvenanceError(
            f"record {record_id} deleted without tombstone; provenance unresolvable"
        )
    return rec.derived_from or "root"
