# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-ttl-expiry-from-being-treated-as-deletion-in-scoped-memory-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-ttl-expiry-from-being-treated-as-deletion-in-scoped-memory-apis.warrant.json
# Markdown SHA-256:   d6afbe67fb575721ace6b3831964b96bc1b147f12d54a2082610050e049c28e1
# Code AST SHA-256:   50ae118d4a5cfa9d6c6ff09a3cb5ab996bf97ea7e236e5e53385cbe2439101f5
# Verified Classes:   Cause, LedgerIntegrityError, LedgerRecord
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class Cause(str, Enum):
    TTL_EXPIRY = "ttl_expiry"
    EXPLICIT_FORGET = "explicit_forget"
    POLICY_RETENTION = "policy_retention"


class LedgerIntegrityError(RuntimeError):
    """Raised when a ledger record violates the expiry/deletion attribution invariant."""


@dataclass(frozen=True)
class LedgerRecord:
    namespace: str
    key: str
    cause: Cause
    principal: Optional[str]
    clock_source: str  # "service" for expiry, "request" for forget


def _validate(rec: LedgerRecord) -> None:
    # Invariant: expiry is anonymous, deletion is attributed.
    if rec.cause is Cause.TTL_EXPIRY:
        if rec.principal is not None:
            raise LedgerIntegrityError(
                f"ttl_expiry for {rec.namespace}/{rec.key} carried principal "
                f"{rec.principal!r}; expiry must be anonymous"
            )
        if rec.clock_source != "service":
            raise LedgerIntegrityError(
                f"ttl_expiry for {rec.namespace}/{rec.key} used clock_source "
                f"{rec.clock_source!r}; expiry must use the service clock"
            )
    else:
        if rec.principal is None:
            raise LedgerIntegrityError(
                f"{rec.cause.value} for {rec.namespace}/{rec.key} has no principal; "
                f"attributed deletion requires an accountable actor"
            )
        if rec.clock_source != "request":
            raise LedgerIntegrityError(
                f"{rec.cause.value} for {rec.namespace}/{rec.key} used clock_source "
                f"{rec.clock_source!r}; attributed deletion must use the request clock"
            )


def forget(namespace: str, key: str, principal: str, ledger: list[LedgerRecord]) -> None:
    """Attest an explicit forget. Writes the record unconditionally, even if the
    key was already reaped by TTL, so idempotency of effect never suppresses
    attestation."""
    if not principal:
        raise LedgerIntegrityError("forget requires a non-empty principal")
    rec = LedgerRecord(
        namespace=namespace,
        key=key,
        cause=Cause.EXPLICIT_FORGET,
        principal=principal,
        clock_source="request",
    )
    _validate(rec)
    ledger.append(rec)
    # Physical removal is best-effort and independent of the attestation above.


def reap_expired(namespace: str, key: str, ledger: list[LedgerRecord]) -> None:
    rec = LedgerRecord(
        namespace=namespace,
        key=key,
        cause=Cause.TTL_EXPIRY,
        principal=None,
        clock_source="service",
    )
    _validate(rec)
    ledger.append(rec)


def assert_attributed(ledger: list[LedgerRecord], namespace: str, key: str) -> None:
    """Fail closed if a forget was requested but only anonymous expiry is on record."""
    for rec in ledger:
        if rec.namespace == namespace and rec.key == key:
            if rec.cause is Cause.EXPLICIT_FORGET and rec.principal:
                return
    raise LedgerIntegrityError(
        f"no attributed deletion on record for {namespace}/{key}; "
        f"expiry tombstones cannot satisfy a forget attestation"
    )
