# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-verified-deletion-from-silently-surviving-in-a-re-embedded-episodic-store.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-verified-deletion-from-silently-surviving-in-a-re-embedded-episodic-store.warrant.json
# Markdown SHA-256:   92892ecfe9ba8feb93db714693e4e5d9f26ab1e338ed6f3ecfcfb428f3e1e66b
# Code AST SHA-256:   7f8f15a3a542f95489e52c8dae55de2ee37aba46cddabda1ade219c562982c3c
# Verified Classes:   ErasureClosureError, Fact, EpisodicStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Iterable

SIMILARITY_TAINT_THRESHOLD = 0.92


class ErasureClosureError(RuntimeError):
    """Raised when an erasure cannot be proven closed over derived artifacts."""


@dataclass
class Fact:
    fact_id: str
    text: str
    source_ids: frozenset[str]
    embedding: tuple[float, ...]
    tainted: bool = False


@dataclass
class EpisodicStore:
    records: dict[str, str] = field(default_factory=dict)
    facts: dict[str, Fact] = field(default_factory=dict)
    fence: set[str] = field(default_factory=set)

    def distill(self, record_id: str, fact_id: str, text: str,
                embedding: tuple[float, ...]) -> Fact:
        # Guardrail: distillation must refuse to run over a fenced source.
        if record_id in self.fence:
            raise ErasureClosureError(
                f"distillation attempted over fenced record {record_id}"
            )
        fact = Fact(fact_id, text, frozenset({record_id}), embedding)
        self.facts[fact_id] = fact
        return fact


def _cosine(a: tuple[float, ...], b: tuple[float, ...]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = sum(x * x for x in a) ** 0.5
    nb = sum(y * y for y in b) ** 0.5
    return dot / (na * nb) if na and nb else 0.0


def erase(store: EpisodicStore, record_id: str,
          record_embedding: tuple[float, ...]) -> dict:
    if record_id not in store.records and record_id not in store.fence:
        raise ErasureClosureError(f"unknown record {record_id}")

    # 1. Fence first so no concurrent distillation can re-launder it.
    store.fence.add(record_id)
    store.records.pop(record_id, None)

    # 2. Propagate along provenance edges: any fact citing the record is tainted.
    for fact in store.facts.values():
        if record_id in fact.source_ids:
            fact.tainted = True

    # 3. Similarity backstop: catch facts re-instantiated from a sibling record
    #    whose source set does NOT cite the deleted record (the laundering case).
    laundered = [
        f.fact_id for f in store.facts.values()
        if _cosine(f.embedding, record_embedding) >= SIMILARITY_TAINT_THRESHOLD
    ]
    for fact_id in laundered:
        store.facts[fact_id].tainted = True

    # 4. Closure check: no retrievable, untainted artifact may remain.
    survivors = [
        f for f in store.facts.values()
        if not f.tainted and (record_id in f.source_ids
                              or _cosine(f.embedding, record_embedding)
                              >= SIMILARITY_TAINT_THRESHOLD)
    ]
    if survivors:
        raise ErasureClosureError(
            f"erasure of {record_id} not closed; survivors: "
            f"{[s.fact_id for s in survivors]}"
        )

    return {"record_id": record_id, "fenced": True,
            "tainted_facts": laundered}
