# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-forget-the-deletion-tombstone-before-it-forgets-the-embedding-right-to-erasure-drift-across-vector-and-episodic-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-forget-the-deletion-tombstone-before-it-forgets-the-embedding-right-to-erasure-drift-across-vector-and-episodic-stores.warrant.json
# Markdown SHA-256:   dae60a0fe8669bf75c8b907c8d09da46335ba820ef209702707f1c2eaf0ebd1a
# Code AST SHA-256:   7924e2c02a5278cb7b6aa69431a1eebf33ecb6868c97b21190b0de8f4a78a619
# Verified Classes:   ErasureResurrectionError, ErasureLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ErasureResurrectionError(RuntimeError):
    """Raised when a distillation cycle re-emits facts for an erased key,
    or when a tombstone loses its erasure key during summarization."""
    pass


class ErasureLedger:
    """Write-once control store, outside the distillation read set."""

    def __init__(self):
        self._tombstones = {}  # key -> ts, append-only, never summarized

    def record(self, key: str, ts: float) -> None:
        if key in self._tombstones:
            return
        self._tombstones[key] = ts

    def is_active(self, key: str) -> bool:
        return key in self._tombstones

    def key_intact(self, key: str) -> bool:
        return key in self._tombstones


def distill(episodic_events, ledger: ErasureLedger, vector_store):
    emitted = []
    for ev in episodic_events:
        key = ev.get("user_id")
        if key is None:
            continue
        if ledger.is_active(key):
            # Hard gate: never emit for an erased key, never summarize the tombstone.
            continue
        emitted.append(ev)

    # Post-cycle integrity assertion: every active tombstone must still resolve.
    for key in list(ledger._tombstones):
        if not ledger.key_intact(key):
            raise ErasureResurrectionError(
                f"tombstone key {key!r} lost during distillation; cycle invalid"
            )

    # Detect resurrection: any emitted fact whose key is erased is a violation.
    for fact in emitted:
        key = fact.get("user_id")
        if key is not None and ledger.is_active(key):
            raise ErasureResurrectionError(
                f"fact for erased key {key!r} re-emitted by distiller"
            )

    vector_store.upsert(emitted)
    return emitted


def close_erasure_request(key: str, ledger: ErasureLedger, substrates) -> None:
    for name, sub in substrates.items():
        if not sub.physically_forgotten(key):
            raise ErasureResurrectionError(
                f"substrate {name!r} has not physically forgotten {key!r}; "
                f"request must remain PENDING"
            )
    ledger.record(key, ts=0.0)  # tombstone retained for audit, key intact
