# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-eviction-memory-tools-from-resurrecting-evicted-facts-through-summarization-side-channels.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-eviction-memory-tools-from-resurrecting-evicted-facts-through-summarization-side-channels.warrant.json
# Markdown SHA-256:   ff088cf29430ca0ac6490602629596678bf9ea12f58e2b7725d85f3ac9343e9a
# Code AST SHA-256:   8a69e7a102fdf69949b8c93fa56420a483565285e7b9d35976e97669fe6152f7
# Verified Classes:   EvictionProvenanceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EvictionProvenanceError(RuntimeError):
    """Raised when a derived memory node would be readable despite an evicted ancestor."""
    pass


def write_derived(summary_text, source_records, store, active_evictions):
    """
    Write a semantic summary node, enforcing eviction closure under derivation.
    source_records: the episodic records fed to the summarizer.
    active_evictions: list of predicates (callables) currently in force.
    """
    # Rule 1: never derive from an evicted source.
    for src in source_records:
        if src.get("evicted"):
            raise EvictionProvenanceError(
                f"summary derives from evicted record {src['id']}; "
                f"refusing to write resurrection node"
            )

    # Rule 2: retention monotonicity — derived node cannot outlive its shortest-lived source.
    source_ttls = [s.get("ttl") for s in source_records if s.get("ttl") is not None]
    derived_ttl = min(source_ttls) if source_ttls else None
    if any(s.get("ttl") is None for s in source_records) and derived_ttl is not None:
        # mixed provenance: a permanent source justifies permanence, but flag it for audit
        derived_ttl = None

    # Rule 3: the derived node must be checked against every active eviction predicate,
    # not just the ones that matched its source tags.
    candidate = {
        "text": summary_text,
        "tags": derive_tags(summary_text),
        "provenance": [s["id"] for s in source_records],
        "ttl": derived_ttl,
    }
    for predicate in active_evictions:
        if predicate(candidate):
            raise EvictionProvenanceError(
                f"derived node matches active eviction predicate {predicate.__name__}; "
                f"write blocked to preserve eviction closure"
            )

    return store.write(candidate)


def forget_with_closure(predicate, store, summarizer):
    """
    Two-phase forget: hide sources, run distillation barrier, then re-sweep
    derived nodes for provenance overlap.
    """
    evicted_ids = store.mark_evicted(predicate)
    if not evicted_ids:
        return []

    # Phase 2: force the distillation cycle so any in-flight summary lands now.
    summarizer.run_barrier()

    # Phase 3: evict any semantic node whose provenance touches an evicted id.
    resurrected = []
    for node in store.iter_semantic():
        if set(node["provenance"]) & set(evicted_ids):
            store.mark_evicted_by_id(node["id"])
            resurrected.append(node["id"])

    if resurrected:
        # Surface this: it means the summarizer ran after eviction despite the barrier.
        raise EvictionProvenanceError(
            f"distillation resurrected {len(resurrected)} evicted facts: {resurrected}"
        )
    return evicted_ids
