# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-tool-s-forget-as-a-tombstone-rather-than-an-erasure-and-why-does-the-distinction-break-recall.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-memory-tool-s-forget-as-a-tombstone-rather-than-an-erasure-and-why-does-the-distinction-break-recall.warrant.json
# Markdown SHA-256:   e4e1e0157b2aebf9654a7380d0cb928ff11ab5e8b0542e9293e0116b9c3cdc7e
# Code AST SHA-256:   56452e3663e00c30afbb5c4373d11e66414a0ac059ae661067c9317980f25a44
# Verified Classes:   ResurrectionLeakError, ForgetRecord, ForgetSet
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Optional


class ResurrectionLeakError(RuntimeError):
    """Raised when a read returns content the agent has forgotten and cannot quarantine."""
    pass


@dataclass
class ForgetRecord:
    key: str
    acked_at: datetime
    hard_token: Optional[str] = None
    retention_window: timedelta = timedelta(days=30)

    def is_hard_deleted(self, now: datetime) -> bool:
        if self.hard_token is not None:
            return True
        return (now - self.acked_at) >= self.retention_window


@dataclass
class ForgetSet:
    records: dict[str, ForgetRecord] = field(default_factory=dict)

    def record_forget(self, key: str, hard_token: Optional[str] = None) -> None:
        self.records[key] = ForgetRecord(
            key=key, acked_at=datetime.utcnow(), hard_token=hard_token
        )

    def quarantine(self, read_result: dict, now: Optional[datetime] = None) -> dict:
        """Drop any returned chunk whose provenance key is in the forget-set
        and not yet hard-deleted. Raises if a quarantined chunk cannot be
        attributed to a key (provenance gap => fail closed)."""
        now = now or datetime.utcnow()
        clean_chunks = []
        for chunk in read_result.get("chunks", []):
            prov_key = chunk.get("provenance_key")
            if prov_key is None:
                raise ResurrectionLeakError(
                    f"read returned chunk with no provenance key; cannot verify "
                    f"against forget-set. path={read_result.get('path')}"
                )
            rec = self.records.get(prov_key)
            if rec is not None and not rec.is_hard_deleted(now):
                # tombstoned but not erased: drop it, log the filter gap
                read_result.setdefault("quarantine_events", []).append(
                    {"key": prov_key, "path": read_result.get("path"),
                     "reason": "tombstone_not_erased"}
                )
                continue
            clean_chunks.append(chunk)
        read_result["chunks"] = clean_chunks
        return read_result


def safe_read(forget_set: ForgetSet, read_fn, *, path: str, **kwargs) -> dict:
    result = read_fn(path=path, **kwargs)
    result["path"] = path
    cleaned = forget_set.quarantine(result)
    if cleaned.get("quarantine_events"):
        # surface the gap; do not silently proceed as if forget succeeded
        raise ResurrectionLeakError(
            f"read path '{path}' returned {len(cleaned['quarantine_events'])} "
            f"tombstoned record(s); read path is not honoring forget filter"
        )
    return cleaned
