# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-poisoned-memory-write-while-a-concurrent-reader-has-already-admitted-the-poisoned-record-into-its-own-worki.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-poisoned-memory-write-while-a-concurrent-reader-has-already-admitted-the-poisoned-record-into-its-own-worki.warrant.json
# Markdown SHA-256:   9c72b90c99eafc1f2f0119e9969826a52547315420449cb08c28d305230ea48d
# Code AST SHA-256:   b7b736193ec666b4def4afe822778ed5392405aed28dabf6348b4d62df2db402
# Verified Classes:   RollbackContainmentError, MemoryRecord, QuarantineResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class RollbackContainmentError(RuntimeError):
    """Raised when a quarantine/rollback cannot prove containment of a poisoned record."""


@dataclass(frozen=True)
class MemoryRecord:
    key: str
    version: str
    content: str
    derived_from: tuple[str, ...] = ()          # record identities, e.g. ("R_v7",)
    provenance: str = ""


@dataclass
class QuarantineResult:
    quarantined: list[str] = field(default_factory=list)
    suspect_unlinked: list[str] = field(default_factory=list)
    live_working_sets: list[str] = field(default_factory=list)


def quarantine_and_rollback(
    poisoned: MemoryRecord,
    store: dict[str, MemoryRecord],
    live_promotions: Iterable[tuple[str, str]],   # (reader_id, record_version)
    similarity_threshold: float = 0.85,
    similarity_fn=None,
) -> QuarantineResult:
    """
    Quarantine a poisoned record and everything transitively derived from it.

    Containment is only claimed if:
      - every derived record is reachable via derived_from edges, and
      - no live working set still holds the poisoned version, and
      - no content-similar record lacks a derivation edge (suspect-unlinked).
    """
    if similarity_fn is None:
        raise RollbackContainmentError("similarity_fn required; cannot assess unlinked records")

    result = QuarantineResult()
    frontier: list[str] = [poisoned.key]
    seen: set[str] = set()

    # --- graph traversal over derivation edges -------------------------------
    while frontier:
        current = frontier.pop()
        if current in seen:
            continue
        seen.add(current)
        result.quarantined.append(current)
        for rec in store.values():
            if current in rec.derived_from and rec.key not in seen:
                frontier.append(rec.key)

    # --- detect laundering: content-similar but no derivation edge -----------
    for rec in store.values():
        if rec.key in seen:
            continue
        if similarity_fn(rec.content, poisoned.content) >= similarity_threshold:
            if not rec.derived_from:
                result.suspect_unlinked.append(rec.key)

    # --- detect live working sets still holding the poisoned version --------
    poisoned_versions = {f"{poisoned.key}@{poisoned.version}"}
    for rec_key in result.quarantined:
        for rec in store.values():
            if rec.key == rec_key:
                poisoned_versions.add(f"{rec.key}@{rec.version}")
    for reader_id, promoted_version in live_promotions:
        if promoted_version in poisoned_versions:
            result.live_working_sets.append(reader_id)

    # --- containment invariant ----------------------------------------------
    if result.suspect_unlinked:
        raise RollbackContainmentError(
            "content-similar records lack derivation edges; poison may be laundered: "
            f"{result.suspect_unlinked}"
        )
    if result.live_working_sets:
        raise RollbackContainmentError(
            "live working sets still hold quarantined versions; readers must re-validate "
            f"before next use: {result.live_working_sets}"
        )

    # Only now is rollback of the source record safe to report as containment.
    return result


def apply_rollback(
    poisoned: MemoryRecord,
    store: dict[str, MemoryRecord],
    trusted_predecessor: MemoryRecord,
    live_promotions: Iterable[tuple[str, str]],
    similarity_fn,
) -> QuarantineResult:
    result = quarantine_and_rollback(
        poisoned=poisoned,
        store=store,
        live_promotions=live_promotions,
        similarity_fn=similarity_fn,
    )
    # Restore source record only after traversal proved containment.
    store[trusted_predecessor.key] = trusted_predecessor
    for key in result.quarantined:
        if key != trusted_predecessor.key:
            store.pop(key, None)
    return result
