# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-write-path-anomaly-score-silently-invert-after-memory-store-compaction-defeating-poisoning-detection.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-write-path-anomaly-score-silently-invert-after-memory-store-compaction-defeating-poisoning-detection.warrant.json
# Markdown SHA-256:   6b29d64c0fd48c277fc484a4368f78e945802dc58a794adeea8e87eb5aab6f89
# Code AST SHA-256:   218d2df2383827db42a840f6b1f4d532ead2011750ecc90ede765a6e4f4aec99
# Verified Classes:   ReferenceContaminationError, WitnessPrunedError, ReferenceSnapshot, MemoryEntry, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class ReferenceContaminationError(RuntimeError):
    """Raised when a candidate's anomaly score is not invariant to live-store compaction."""
    pass


class WitnessPrunedError(RuntimeError):
    """Raised when compaction attempts to prune an entry pinned as a consistency witness."""
    pass


@dataclass
class ReferenceSnapshot:
    version: int
    mean: Dict[str, float]
    stddev: Dict[str, float]


@dataclass
class MemoryEntry:
    entry_id: str
    features: Dict[str, float]
    compaction_epoch: int
    witness_pinned: bool = False


@dataclass
class MemoryStore:
    entries: Dict[str, MemoryEntry] = field(default_factory=dict)
    compaction_epoch: int = 0
    reference: Optional[ReferenceSnapshot] = None

    def score(self, features: Dict[str, float], reference: ReferenceSnapshot) -> float:
        z_total = 0.0
        for k, v in features.items():
            mu = reference.mean[k]
            sd = reference.stddev[k] or 1e-9
            z_total += abs((v - mu) / sd)
        return z_total / max(len(features), 1)

    def compact(self, keep_ids: List[str]) -> None:
        # Refuse to prune any witness-pinned entry; fail closed.
        for eid, entry in self.entries.items():
            if entry.witness_pinned and eid not in keep_ids:
                raise WitnessPrunedError(
                    f"compaction would prune witness-pinned entry {eid!r}; "
                    f"resolve open consistency check first"
                )
        self.entries = {eid: e for eid, e in self.entries.items() if eid in keep_ids}
        self.compaction_epoch += 1
        # NOTE: reference is deliberately NOT recomputed here.

    def admit(
        self,
        candidate: MemoryEntry,
        threshold: float,
        pre_compaction_score: float,
    ) -> bool:
        if self.reference is None:
            raise ReferenceContaminationError("no pinned reference snapshot; refusing to score")

        score = self.score(candidate.features, self.reference)

        # Invariant: score must be invariant to compaction of the live store.
        # If the live store's composition has drifted since the reference was
        # pinned, the score is not trustworthy and we must fail closed.
        if abs(score - pre_compaction_score) > 1e-6 and self.compaction_epoch > 0:
            raise ReferenceContaminationError(
                f"candidate {candidate.entry_id!r} score drifted "
                f"{pre_compaction_score:.3f} -> {score:.3f} after compaction "
                f"(epoch {self.compaction_epoch}); reference version "
                f"{self.reference.version} is stale"
            )

        if score > threshold:
            return False  # quarantined
        self.entries[candidate.entry_id] = candidate
        return True
