# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-quarantine-a-poisoned-memory-only-after-the-poison-has-already-been-retrieved-into-a-live-reasoning-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-quarantine-a-poisoned-memory-only-after-the-poison-has-already-been-retrieved-into-a-live-reasoning-trace.warrant.json
# Markdown SHA-256:   f9cc69f385344f0671aa79982ffb2c1c86c3feb447780b622f08ac5b7d80ceeb
# Code AST SHA-256:   614c63b937c0608274b958dc71b60a9bed6327fe58ed933190f717a674243b17
# Verified Classes:   TaintClosureViolation, MemoryRecord, PersistentStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TaintClosureViolation(RuntimeError):
    """Raised when a quarantined record's taint is not propagated to its
    derivation descendants or retrieval cache, allowing laundering."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    content: str
    derived_from: list[str] = field(default_factory=list)  # episode/record ids
    quarantined: bool = False
    tainted: bool = False
    retrieval_cache_entries: list[str] = field(default_factory=list)


class PersistentStore:
    def __init__(self, records: dict[str, MemoryRecord]):
        self._records = records

    def quarantine(self, record_id: str) -> None:
        """Quarantine a record and enforce taint closure.

        Forward-only guarantee requires: the record, all derivation
        descendants, and all cached retrieval entries are invalidated,
        and descendants are re-adjudicated against leaf episodes.
        """
        target = self._records.get(record_id)
        if target is None:
            raise TaintClosureViolation(f"unknown record {record_id}")

        target.quarantined = True
        target.tainted = True

        # Propagate taint DOWN the derivation graph (children cite parents).
        descendants = [
            r for r in self._records.values()
            if record_id in r.derived_from
        ]
        for child in descendants:
            child.tainted = True

        # Cached retrieval entries must not survive quarantine, or the
        # embedding cache will keep surfacing the poisoned record.
        if target.retrieval_cache_entries:
            target.retrieval_cache_entries.clear()

        # Invariant check: no active record may cite a tainted parent
        # without itself being tainted. Laundering through one derivation
        # hop is the exact failure this guards against.
        for r in self._records.values():
            if r.quarantined:
                continue
            if any(self._records[p].tainted for p in r.derived_from if p in self._records):
                if not r.tainted:
                    raise TaintClosureViolation(
                        f"record {r.record_id} cites tainted parent but is "
                        f"untainted; taint closure broken"
                    )

    def distill(self, episode_ids: list[str]) -> MemoryRecord:
        """Nightly distillation must skip tainted episodes, or the poison
        reincarnates with fresh provenance and a clean audit history."""
        for eid in episode_ids:
            ep = self._records.get(eid)
            if ep is not None and ep.tainted:
                raise TaintClosureViolation(
                    f"distillation attempted to read tainted episode {eid}; "
                    f"poison would regenerate as a clean-derived fact"
                )
        return MemoryRecord(
            record_id=f"semantic:{'-'.join(episode_ids)}",
            content="<distilled>",
            derived_from=list(episode_ids),
        )


def enforce_quarantine(store: PersistentStore, record_id: str) -> None:
    store.quarantine(record_id)
    # Post-condition: the quarantine must be forward-only AND
    # backward-reconciled. If any retrieval descendant was not
    # re-adjudicated, the guarantee is void.
    record = store._records[record_id]
    if record.retrieval_cache_entries:
        raise TaintClosureViolation(
            f"record {record_id} still has live retrieval cache after "
            f"quarantine; forward-only guarantee cannot hold"
        )
