# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-forgetting-by-a-proof-of-erasure-rather-than-a-proof-of-absence-the-deletion-receipt-distillation-resurrection-boundary-i.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-forgetting-by-a-proof-of-erasure-rather-than-a-proof-of-absence-the-deletion-receipt-distillation-resurrection-boundary-i.warrant.json
# Markdown SHA-256:   66492a1dea28f69db6e36ec41f39a2d799495b1a7f5ac4c49b9115446886cb02
# Code AST SHA-256:   67bf9d16dc04b8e5f72ab129d78ec3d7629bb8cecf10935b9c2b5074da801fab
# Verified Classes:   DeletionClosureError, DeletionRequest, DerivationGraph
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set, Dict, List


class DeletionClosureError(RuntimeError):
    """Raised when a deletion receipt's claim exceeds the swept derivation closure."""
    pass


@dataclass
class DeletionRequest:
    record_id: str
    claim_scope: str  # "closure" | "scoped" | "pending"


@dataclass
class DerivationGraph:
    # forward index: primary record -> derived artifact ids (facts, vectors, checkpoints, replicas)
    edges: Dict[str, Set[str]] = field(default_factory=dict)
    # which store each derived artifact lives in
    store_of: Dict[str, str] = field(default_factory=dict)

    def closure(self, root: str) -> Set[str]:
        seen: Set[str] = set()
        stack = [root]
        while stack:
            node = stack.pop()
            if node in seen:
                continue
            seen.add(node)
            stack.extend(self.edges.get(node, set()))
        return seen


def emit_receipt(req: DeletionRequest, graph: DerivationGraph,
                  swept_stores: Set[str], tombstone_consulted_by_distiller: bool) -> dict:
    closure = graph.closure(req.record_id)
    required_stores = {graph.store_of.get(a, "episodic") for a in closure}

    # Invariant 1: distillation must consult tombstones, else resurrection race is open.
    if not tombstone_consulted_by_distiller:
        raise DeletionClosureError(
            f"distiller does not consult tombstones for {req.record_id}; "
            "resurrection race open, refusing full-scope receipt"
        )

    # Invariant 2: claim scope must not exceed swept closure.
    if req.claim_scope == "closure" and not required_stores.issubset(swept_stores):
        missing = required_stores - swept_stores
        raise DeletionClosureError(
            f"claim_scope=closure but derived artifacts survive in {sorted(missing)} "
            f"for record {req.record_id}; downgrade to scoped or purge before attesting"
        )

    # Invariant 3: embedding stores must be physically swept, not merely invalidated.
    if "ann_index" in required_stores and "ann_index" not in swept_stores:
        raise DeletionClosureError(
            f"ann_index holds vectors derived from {req.record_id}; "
            "invalidation is not erasure, physical vector removal required"
        )

    return {
        "record_id": req.record_id,
        "claim_scope": req.claim_scope,
        "swept_stores": sorted(swept_stores),
        "closure_size": len(closure),
        "residual": sorted(required_stores - swept_stores),
        "attested": req.claim_scope != "pending",
    }
