# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-self-editing-context-policy-silently-resurrect-evicted-facts-when-relevance-scores-are-recomputed-against-a-stale-query-vector.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-self-editing-context-policy-silently-resurrect-evicted-facts-when-relevance-scores-are-recomputed-against-a-stale-query-vector.warrant.json
# Markdown SHA-256:   764ea410b2d87c07dd8450d86e147ccd47b48a5e31da1c72eca451d0597cb1df
# Code AST SHA-256:   a3cdc267fe17937842991050c8e65e07244f7f028ed0edcefe7369e3e4e28045
# Verified Classes:   ContextRewriteInconsistency, EvictionLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ContextRewriteInconsistency(RuntimeError):
    """Raised when compaction re-admits a fact that was previously evicted."""


@dataclass
class EvictionLedger:
    entries: Dict[str, dict] = field(default_factory=dict)  # fact_id -> {embedding, evicted_at_step, score}

    def record(self, fact_id: str, embedding, step: int, score: float) -> None:
        self.entries[fact_id] = {
            "embedding": embedding,
            "evicted_at_step": step,
            "score_at_eviction": score,
        }


def compact_and_verify(
    active_facts: Set[str],
    fresh_retrievals: Set[str],
    ledger: EvictionLedger,
    current_step: int,
    tau: float,
    score_fn,
    current_query_vec,
) -> Set[str]:
    """
    Rewrite-time consistency gate. Re-admission from the ledger is forbidden;
    any ledger entry scoring above tau against the current query is a
    resurrection attempt and must be rejected, not restored.
    """
    post_compact = set(active_facts) | set(fresh_retrievals)

    for fact_id, entry in ledger.entries.items():
        if fact_id in post_compact:
            raise ContextRewriteInconsistency(
                f"Fact {fact_id!r} present in active context at step {current_step} "
                f"but was evicted at step {entry['evicted_at_step']} "
                f"(score_at_eviction={entry['score_at_eviction']:.3f}). "
                f"Re-admission from ledger is prohibited; re-retrieve from source."
            )

        residual = score_fn(current_query_vec, entry["embedding"])
        if residual > tau:
            # Stale-embedding resurrection vector detected. Do NOT restore.
            # Escalate as an audit event; the correct action is fresh retrieval.
            raise ContextRewriteInconsistency(
                f"Ledger entry {fact_id!r} scores {residual:.3f} > tau={tau} against "
                f"rewritten query at step {current_step}. Stale-embedding resurrection "
                f"path is open; compact() must re-baseline or clear the ledger before "
                f"scoring. Refusing to restore."
            )

    return post_compact
