# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-a-memory-that-its-own-ttl-sweep-has-not-yet-reached-tombstone-consent-divergence-in-write-ahead-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-a-memory-that-its-own-ttl-sweep-has-not-yet-reached-tombstone-consent-divergence-in-write-ahead-memory-stores.warrant.json
# Markdown SHA-256:   c46df1df3db2595b85c550118eea03aad86779fcebd471baadded5e63b344746
# Code AST SHA-256:   c17b16e8aba051593c81f620d2243aaa93838165bac8734d62c9a3379a7148e5
# Verified Classes:   ProvenanceDivergence, DeletionReason, MemoryRow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ProvenanceDivergence(RuntimeError):
    """Raised when a memory's unreadability cannot be attributed to exactly one cause."""
    pass


class DeletionReason(str, Enum):
    TTL = "ttl"
    CONSENT = "consent"
    SUPERSEDED = "superseded"


@dataclass
class MemoryRow:
    memory_id: str
    unreadable_at: Optional[int] = None      # set by TTL sweep OR consent handler
    finalized_by: Optional[str] = None       # set ONLY by consent handler, with warrant id
    deletion_reason: Optional[DeletionReason] = None


def resolve_read(row: MemoryRow, audit_has_forget: bool) -> str:
    """
    Decide what an agent may do with a memory it cannot read.
    Enforces: finalized_by <=> forget audit row exists, and reason is non-null
    whenever unreadable_at is set.
    """
    if row.unreadable_at is None:
        return "readable"

    # Invariant 1: reason must be attributable.
    if row.deletion_reason is None:
        raise ProvenanceDivergence(
            f"memory {row.memory_id} is unreadable with no deletion_reason; "
            f"cannot distinguish ttl-suppression from consented-forget"
        )

    # Invariant 2: finalized_by and the forget audit row must agree.
    if (row.finalized_by is not None) != audit_has_forget:
        raise ProvenanceDivergence(
            f"memory {row.memory_id}: finalized_by={row.finalized_by!r} but "
            f"audit_has_forget={audit_has_forget}; tombstone/audit split-brain"
        )

    if row.deletion_reason is DeletionReason.TTL and row.finalized_by is None:
        # Suppressed, not forgotten. Route to consent queue; DO NOT re-derive.
        return "suppressed_route_to_consent"

    if row.deletion_reason is DeletionReason.CONSENT:
        # Genuinely forgotten. Subject is out of scope for the session.
        return "forgotten_do_not_rewrite"

    # SUPERSEDED or any unhandled reason: fail closed.
    raise ProvenanceDivergence(
        f"memory {row.memory_id} has unhandled deletion_reason="
        f"{row.deletion_reason!r}; halting to avoid re-derivation"
    )


def consent_handler(row: MemoryRow, warrant_id: str, audit_exists: bool) -> MemoryRow:
    """
    Consent approval must emit a forget audit row EVEN IF the row is already
    tombstoned by TTL. Idempotency is keyed on (memory_id, warrant_id), not on
    tombstone presence.
    """
    if row.unreadable_at is not None and row.deletion_reason is DeletionReason.TTL:
        # Do not suppress: stamp finalization and let the caller emit forget.
        row.finalized_by = f"consent:{warrant_id}"
        row.deletion_reason = DeletionReason.CONSENT
        return row
    if audit_exists:
        return row  # true idempotent replay of the same warrant
    row.finalized_by = f"consent:{warrant_id}"
    row.deletion_reason = DeletionReason.CONSENT
    return row
