# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-agent-memory-poisoning-from-surviving-quarantine-rollback-in-shared-vector-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-agent-memory-poisoning-from-surviving-quarantine-rollback-in-shared-vector-stores.warrant.json
# Markdown SHA-256:   768447fcc094fed2f8f0198a959f2599fdd4df9c872da17de2693485fe453c9f
# Code AST SHA-256:   2e06e357fa410d1054daec8f030243602ddde671c781ec619de667238e137623
# Verified Classes:   AncestryInvariantViolation, MemoryEntry, SharedMemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AncestryInvariantViolation(RuntimeError):
    """Raised when a live memory entry has a quarantined ancestor, or when
    quarantine propagation is attempted on a graph that cannot support it."""
    pass


@dataclass
class MemoryEntry:
    entry_id: str
    confidence: float
    derived_from: list[str] = field(default_factory=list)
    quarantined: bool = False


class SharedMemoryStore:
    DISCOUNT_PER_EDGE = 0.7
    MAX_CASCADE = 100

    def __init__(self) -> None:
        self.entries: dict[str, MemoryEntry] = {}
        self.quarantine: set[str] = set()

    def add(self, entry: MemoryEntry) -> None:
        self.entries[entry.entry_id] = entry

    def ancestors(self, entry_id: str) -> set[str]:
        seen: set[str] = set()
        stack = list(self.entries[entry_id].derived_from)
        while stack:
            nid = stack.pop()
            if nid in seen or nid not in self.entries:
                continue
            seen.add(nid)
            stack.extend(self.entries[nid].derived_from)
        return seen

    def effective_confidence(self, entry_id: str) -> float:
        entry = self.entries[entry_id]
        depth = len(self.ancestors(entry_id))
        return entry.confidence * (self.DISCOUNT_PER_EDGE ** depth)

    def retrieve(self, entry_id: str, min_confidence: float = 0.5) -> MemoryEntry:
        if entry_id in self.quarantine:
            raise AncestryInvariantViolation(
                f"entry {entry_id} is quarantined and must not be served"
            )
        poisoned = self.ancestors(entry_id) & self.quarantine
        if poisoned:
            raise AncestryInvariantViolation(
                f"entry {entry_id} has quarantined ancestor(s) {sorted(poisoned)}; "
                f"backward ancestry check failed — refusing to serve laundered poison"
            )
        if self.effective_confidence(entry_id) < min_confidence:
            raise AncestryInvariantViolation(
                f"entry {entry_id} effective confidence "
                f"{self.effective_confidence(entry_id):.3f} below threshold "
                f"{min_confidence} after ancestry discounting"
            )
        return self.entries[entry_id]

    def quarantine_deep(self, entry_id: str) -> list[str]:
        descendants = [
            eid for eid in self.entries
            if entry_id in self.ancestors(eid) and eid not in self.quarantine
        ]
        if len(descendants) > self.MAX_CASCADE:
            raise AncestryInvariantViolation(
                f"cascade fanout {len(descendants)} exceeds MAX_CASCADE "
                f"{self.MAX_CASCADE} for {entry_id}; escalate to human review "
                f"rather than auto-tombstoning a memory blackout"
            )
        self.quarantine.add(entry_id)
        for d in descendants:
            self.quarantine.add(d)
        return [entry_id] + descendants
