# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-scoped-write-visibility-against-ttl-expiry-before-trusting-a-forget-then-recall-sequence.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-scoped-write-visibility-against-ttl-expiry-before-trusting-a-forget-then-recall-sequence.warrant.json
# Markdown SHA-256:   a0b4d2f8ad4eb8a646a191b98fc3124c98c929aeb813c48fc00f072e409a1a56
# Code AST SHA-256:   e167c3fa2c5124102fd3ece4e1a282f942a26ea636897ebff1ecfcf5c32680cd
# Verified Classes:   UndecidableMemoryState, ForgetReceipt, RecallResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UndecidableMemoryState(RuntimeError):
    """Raised when a forget-then-recall sequence cannot be resolved to a verdict."""


@dataclass(frozen=True)
class ForgetReceipt:
    scope: str
    key: str
    tombstone_id: str
    consistency_token: int  # monotonic; usable as min_version on reads


@dataclass(frozen=True)
class RecallResult:
    scope: str
    key: str
    value: Optional[str]
    expires_at: Optional[float]
    served_version: int
    retrieval_mode: str  # "exact_scope" | "cascading"


def verify_forget(receipt: ForgetReceipt, recall: RecallResult, now: float) -> str:
    """
    Decide whether a forget was honored. Returns "honored" | "reverted"
    or raises UndecidableMemoryState when the read cannot speak to the forget.
    """
    # C1: scope must be pinned; cascading reads fall through to lower scopes
    if recall.retrieval_mode != "exact_scope" or recall.scope != receipt.scope:
        raise UndecidableMemoryState(
            f"recall scope={recall.scope!r} mode={recall.retrieval_mode!r} "
            f"cannot observe tombstone {receipt.tombstone_id} written to "
            f"scope={receipt.scope!r}; re-read with exact_scope and "
            f"min_version={receipt.consistency_token}"
        )

    # C2: the read must be at or after the tombstone's consistency token
    if recall.served_version < receipt.consistency_token:
        raise UndecidableMemoryState(
            f"recall served_version={recall.served_version} predates tombstone "
            f"token={receipt.consistency_token} (replica lag); retry with "
            f"read_your_writes"
        )

    # C3: TTL boundary — treat expires_at as exclusive at retrieval
    if recall.value is not None and recall.expires_at is not None:
        if now >= recall.expires_at:
            raise UndecidableMemoryState(
                f"recall returned value with expires_at={recall.expires_at} "
                f"at now={now}; store clock disagreement, do not act on value"
            )

    # A value at a token >= tombstone means the key was re-created after forget
    if recall.value is not None:
        return "reverted"  # investigate concurrent writer, not a lost tombstone
    return "honored"


def recall_for_action(receipt: ForgetReceipt, recall: RecallResult,
                      now: float, action_horizon: float) -> str:
    verdict = verify_forget(receipt, recall, now)
    # C4: returned values are immutable; enforce TTL against the action horizon
    if recall.value is not None and recall.expires_at is not None:
        if now + action_horizon >= recall.expires_at:
            raise UndecidableMemoryState(
                f"value expires_at={recall.expires_at} before action horizon "
                f"{now + action_horizon}; re-verify before acting"
            )
    return verdict
