# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-deletion-before-recall-when-a-memory-tool-s-retention-policy-and-its-tombstone-index-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-deletion-before-recall-when-a-memory-tool-s-retention-policy-and-its-tombstone-index-disagree.warrant.json
# Markdown SHA-256:   d2de6a9155c268adc379a43f28bdd6aee5653605b5b8ae7d0c0546d3947bcb82
# Code AST SHA-256:   7302db2ba3f2bea84e24feaea891414d806d179a0b1b792179e6913b33bee000
# Verified Classes:   DeletionInvariantViolation, DeletionWatermark
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DeletionInvariantViolation(RuntimeError):
    """Raised when a recall hit would resurrect a tombstoned record lineage."""
    pass


@dataclass
class DeletionWatermark:
    # highest tombstone_seq observed per logical record lineage
    lineage_watermark: dict[str, int] = field(default_factory=dict)
    # records this agent created by distilling another record
    derivative_provenance: dict[str, str] = field(default_factory=dict)

    def record_forget(self, lineage: str, tombstone_seq: int) -> None:
        prior = self.lineage_watermark.get(lineage, -1)
        self.lineage_watermark[lineage] = max(prior, tombstone_seq)

    def record_derivative(self, child_id: str, ancestor_id: str) -> None:
        self.derivative_provenance[child_id] = ancestor_id


def admit_recall_hit(hit: dict, wm: DeletionWatermark) -> dict:
    lineage = hit.get("lineage", hit["record_id"])
    hit_seq = hit.get("tombstone_seq", -1)

    # 1. stale-index check: hit predates or equals a known tombstone
    if hit_seq >= 0 and hit_seq <= wm.lineage_watermark.get(lineage, -1):
        raise DeletionInvariantViolation(
            f"recall hit {hit['record_id']} (seq={hit_seq}) is not newer than "
            f"lineage '{lineage}' watermark {wm.lineage_watermark[lineage]}; "
            f"index has not converged past tombstone"
        )

    # 2. resurrection check: hit is a derivative of a tombstoned ancestor
    ancestor = wm.derivative_provenance.get(hit["record_id"])
    if ancestor is not None and ancestor in wm.lineage_watermark:
        raise DeletionInvariantViolation(
            f"recall hit {hit['record_id']} derives from tombstoned ancestor "
            f"'{ancestor}'; refusing to re-admit deleted lineage"
        )

    return hit


def forget_then_recall(memory, wm: DeletionWatermark, lineage: str,
                       query: str) -> list[dict]:
    resp = memory.forget(record_id=lineage, retention_class="user_requested")
    if not resp.get("deleted"):
        raise DeletionInvariantViolation(
            f"forget for '{lineage}' did not commit a tombstone; "
            f"deletion guarantee unestablished, aborting recall"
        )
    wm.record_forget(lineage, resp["tombstone_seq"])

    admitted = []
    for hit in memory.recall(query=query):
        admitted.append(admit_recall_hit(hit, wm))  # raises on violation
    return admitted
