# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-erasure-audit-divergence-when-tombstoned-agent-memories-are-re-derived-from-surviving-episodic-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-erasure-audit-divergence-when-tombstoned-agent-memories-are-re-derived-from-surviving-episodic-traces.warrant.json
# Markdown SHA-256:   604986a313e21f4640c3209f71a638121a56f4feca81d231054ae9ffa4a04bb5
# Code AST SHA-256:   5b368641a364057d50cb45bc7afb1a527b91c2204aee0b657e96751f2c4bfd1d
# Verified Classes:   ErasureDerivabilityViolation, ErasureRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ErasureDerivabilityViolation(RuntimeError):
    """Raised when an erased predicate is re-derivable from surviving stores."""
    pass


def predicate_hash(entity: str, attribute: str, value: str) -> str:
    canonical = f"{entity.strip().lower()}|{attribute.strip().lower()}|{value.strip().lower()}"
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class ErasureRecord:
    erasure_id: str
    suppressed_predicates: set[str] = field(default_factory=set)
    scrubbed_episodic_spans: set[str] = field(default_factory=set)


def distill(episodic_spans, suppression: ErasureRecord):
    """Nightly distillation with a content-keyed suppression filter at the READ boundary."""
    emitted = []
    for span in episodic_spans:
        if span["span_id"] in suppression.scrubbed_episodic_spans:
            continue
        for fact in span["extracted_facts"]:
            ph = predicate_hash(fact["entity"], fact["attribute"], fact["value"])
            if ph in suppression.suppressed_predicates:
                continue  # content-addressed suppression: survives new record_ids
            emitted.append({**fact, "predicate_hash": ph, "record_id": hashlib.sha256(
                f"{ph}:{span['span_id']}".encode()).hexdigest()})
    return emitted


def audit_derivability_closure(episodic_spans, semantic_store, suppression: ErasureRecord):
    """Re-derivation probe: the audit must FAIL CLOSED if the fact can be rebuilt."""
    rederived = distill(episodic_spans, suppression)
    live = {r["predicate_hash"] for r in semantic_store} | {r["predicate_hash"] for r in rederived}
    for ph in suppression.suppressed_predicates:
        if ph in live:
            raise ErasureDerivabilityViolation(
                f"erasure {suppression.erasure_id} not closed: predicate {ph[:12]} "
                f"is re-derivable from surviving episodic traces or live semantic records"
            )
    return True


# --- triggering trace: tombstone-only erasure, no read-path filter ---
episodic = [{"span_id": "s1", "extracted_facts": [
    {"entity": "user", "attribute": "employer", "value": "Acme"}]}]
erased_ph = predicate_hash("user", "employer", "Acme")

weak_erasure = ErasureRecord(erasure_id="e-001", suppressed_predicates=set())  # BUG: never wired
try:
    audit_derivability_closure(episodic, semantic_store=[], suppression=ErasureRecord(
        erasure_id="e-001", suppressed_predicates={erased_ph}))
except ErasureDerivabilityViolation as exc:
    print(f"audit caught resurrection: {exc}")
    # remediation: install read-path suppression AND scrub the source span
    fixed = ErasureRecord(erasure_id="e-001",
                          suppressed_predicates={erased_ph},
                          scrubbed_episodic_spans={"s1"})
    assert audit_derivability_closure(episodic, [], fixed)
