# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-verified-memory-before-it-can-poison-a-downstream-retrieval-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-verified-memory-before-it-can-poison-a-downstream-retrieval-chain.warrant.json
# Markdown SHA-256:   2b57dc6b74772c2691887330cd03dcb4bb4bca0308281cf676d6d89e088b0e8a
# Code AST SHA-256:   9eb33faf213fd61db6ccc96943be510f54cd82da190f528bf47fdefc76249c35
# Verified Classes:   LineageIncompleteError, TrustInvariantViolation, MemoryEntry, ProvenanceStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LineageIncompleteError(RuntimeError):
    """Raised when an entry's derivation graph cannot be walked to its roots."""
    pass


class TrustInvariantViolation(RuntimeError):
    """Raised when an entry is admitted despite a dirty or flagged ancestor."""
    pass


@dataclass
class MemoryEntry:
    entry_id: str
    content: str
    own_trust: float
    parent_ids: list[str] = field(default_factory=list)
    lineage_dirty: bool = False


class ProvenanceStore:
    def __init__(self) -> None:
        self._entries: dict[str, MemoryEntry] = {}
        self._invalidated: set[str] = set()

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

    def invalidate(self, entry_id: str) -> None:
        self._invalidated.add(entry_id)
        # mark all transitive descendants dirty
        stack = [entry_id]
        while stack:
            current = stack.pop()
            for eid, entry in self._entries.items():
                if current in entry.parent_ids:
                    entry.lineage_dirty = True
                    stack.append(eid)

    def effective_trust(self, entry_id: str, _seen: Optional[set[str]] = None) -> float:
        seen = _seen or set()
        if entry_id in seen:
            raise LineageIncompleteError(f"cycle detected at {entry_id}")
        seen.add(entry_id)

        entry = self._entries.get(entry_id)
        if entry is None:
            # ancestor referenced but not present: lineage truncated
            raise LineageIncompleteError(
                f"missing ancestor {entry_id}; cannot compute effective trust"
            )

        if entry_id in self._invalidated:
            return 0.0

        trust = entry.own_trust
        for parent in entry.parent_ids:
            trust = min(trust, self.effective_trust(parent, seen))
        return trust

    def admit_for_retrieval(self, entry_id: str, threshold: float = 0.5) -> MemoryEntry:
        try:
            eff = self.effective_trust(entry_id)
        except LineageIncompleteError:
            # default to quarantine under uncertainty
            raise TrustInvariantViolation(
                f"entry {entry_id} quarantined: lineage not walkable"
            )
        if eff < threshold:
            raise TrustInvariantViolation(
                f"entry {entry_id} quarantined: effective_trust={eff:.3f} < {threshold}"
            )
        return self._entries[entry_id]
