# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstoned-memory-from-resurrecting-through-provenance-preserving-read-paths.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstoned-memory-from-resurrecting-through-provenance-preserving-read-paths.warrant.json
# Markdown SHA-256:   01b89f571d37d814a1f986ab2ff345e2356c4e23b67d09807970f29126cc39d6
# Code AST SHA-256:   71e9701499f81dd70d740a93ee7d7ecec802362c3a5a5301cb609702f2b76419
# Verified Classes:   DeletionInvariantViolation, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class DeletionInvariantViolation(RuntimeError):
    """Raised when a read path would expose payload bytes of a tombstoned record."""
    pass

PAYLOAD_FIELDS = {"text", "snapshot", "summary", "source_span", "embedding"}

@dataclass
class MemoryRecord:
    id: str
    text: Optional[str] = None
    deleted: bool = False
    deleted_at: Optional[str] = None
    reason: Optional[str] = None
    content_hash: Optional[str] = None
    tombstone: dict = field(default_factory=dict)

def forget(record: MemoryRecord, reason: str, now: str) -> MemoryRecord:
    if record.deleted:
        # Idempotent: do not re-snapshot; never orphan a prior snapshot.
        record.reason = record.reason or reason
        return record
    # Hash the payload, then strip it. No snapshot, no summary, no span.
    record.content_hash = f"salted_hash::{record.id}::{hash(record.text)}"
    record.text = None
    record.tombstone = {"id": record.id, "deleted_at": now, "reason": reason,
                        "content_hash": record.content_hash}
    record.deleted = True
    record.deleted_at = now
    record.reason = reason
    return record

def read(record: MemoryRecord, purpose: str) -> dict:
    if record.deleted and purpose != "audit":
        # Recall path: refuse, do not return payload or tombstone body.
        return {"id": record.id, "status": "forgotten",
                "reason": record.reason}
    if record.deleted and purpose == "audit":
        # Audit path: tombstone only, and it must be payload-free.
        leaked = PAYLOAD_FIELDS & set(record.tombstone)
        if leaked:
            raise DeletionInvariantViolation(
                f"tombstone for {record.id} carries payload fields: {leaked}")
        return {"id": record.id, "status": "deleted", "tombstone": record.tombstone}
    return {"id": record.id, "status": "live", "text": record.text}

def serialize_for_model(result: dict) -> str:
    # Serializer must consult the same classifier as forget.
    if result.get("status") == "deleted":
        raise DeletionInvariantViolation(
            f"attempted to inline tombstone {result['id']} into model context")
    return str(result)

# Reproduction of the observed incident:
r = MemoryRecord(id="m1", text="Vendor X contract: SSN 000-00-0000")
forget(r, reason="user_request_pii", now="2025-06-13T00:00:00Z")
audit = read(r, purpose="audit")
try:
    serialize_for_model(audit)
except DeletionInvariantViolation as e:
    print("BLOCKED:", e)   # tombstone never reaches the model
