# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-a-forget-acknowledgement-as-a-retention-scope-proof-rather-than-a-deletion-fact-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-a-forget-acknowledgement-as-a-retention-scope-proof-rather-than-a-deletion-fact-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   fb5631c98623bb127e34fca05ceb52f3ec5e5e2f8ec9064d94f0e8b638bf3da9
# Code AST SHA-256:   b9504308ea841640f37c74cbf07bb739189ea46172bcaf404e97c021a8c01000
# Verified Classes:   RetentionScopeViolation, ForgetAck
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional

class RetentionScopeViolation(RuntimeError):
    """Raised when an instance treats a forget acknowledgement as a deletion fact
    without the fields required to make that inference valid."""
    pass

@dataclass
class ForgetAck:
    status: str
    tombstoned: bool
    logical_ts: Optional[int]
    derivatives_invalidated: bool
    reuse_policy: Optional[str]
    audit_id: Optional[str]

def classify_forget(ack: ForgetAck, read_ts: int) -> str:
    # Undecidable timestamp: cannot reason about "after the acknowledgement".
    if ack.logical_ts is None:
        raise RetentionScopeViolation(
            f"forget ack {ack.audit_id!r} has no comparable logical_ts; "
            "exclusion-before-timestamp invariant is undecidable"
        )
    if ack.logical_ts > read_ts:
        raise RetentionScopeViolation(
            f"read_ts={read_ts} precedes ack logical_ts={ack.logical_ts}; "
            "value may still be visible to this read"
        )
    # Full deletion fact: derivatives invalidated AND reuse policy declared.
    if ack.derivatives_invalidated and ack.reuse_policy is not None:
        return "deletion_fact"
    # Otherwise: scope proof only. Re-writing the key is undefined behavior.
    return "retention_scope_proof"

def safe_rewrite(ack: ForgetAck, key: str, read_ts: int) -> str:
    kind = classify_forget(ack, read_ts)
    if kind == "retention_scope_proof":
        raise RetentionScopeViolation(
            f"refusing to re-write key={key!r}: ack is a scope proof "
            f"(derivatives_invalidated={ack.derivatives_invalidated}, "
            f"reuse_policy={ack.reuse_policy!r}); stale derivatives may resurface"
        )
    return f"rewrite_allowed:{key}:{ack.reuse_policy}"

def require_audited_deletion(ack: ForgetAck, audit_lookup) -> None:
    if ack.audit_id is None:
        raise RetentionScopeViolation("no audit_id; deletion is not auditable")
    if audit_lookup(ack.audit_id) != "hard_deleted":
        raise RetentionScopeViolation(
            f"audit {ack.audit_id!r} not yet hard_deleted; resume would read a reaper-emptied key"
        )
