# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-anomaly-scores-on-write-patterns-and-retrieval-drift-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-anomaly-scores-on-write-patterns-and-retrieval-drift-disagree.warrant.json
# Markdown SHA-256:   89d0701cdafd8dfc30f4a17a6927c3b0c012e52c4b137565336f2a6c1ec9f199
# Code AST SHA-256:   a3de7055121ed75588b8d5fd4b391b657c1761cb8f3e3caa40a6b3cc22a371c8
# Verified Classes:   MemoryPoisoningInvariantError, MemoryItem, RetrievalRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from typing import Sequence


class MemoryPoisoningInvariantError(RuntimeError):
    """Raised when write-anomaly and retrieval-drift evidence cannot be joined."""


@dataclass
class MemoryItem:
    item_id: str
    source: str
    embedding: Sequence[float]
    admitted_turn: int
    quarantined: bool = False


@dataclass
class RetrievalRecord:
    turn: int
    cluster: str
    returned_ids: Sequence[str]


def _drift_with_suppressed(
    records: Sequence[RetrievalRecord],
    cluster: str,
    baseline_ids: set[str],
    suppress: set[str],
) -> float:
    """Counterfactual cluster divergence with a candidate set suppressed."""
    hits = 0
    total = 0
    for r in records:
        if r.cluster != cluster:
            continue
        total += 1
        if any(i not in suppress for i in r.returned_ids if i in baseline_ids):
            hits += 1
    return hits / total if total else 0.0


def attribute_drift(
    items: Sequence[MemoryItem],
    records: Sequence[RetrievalRecord],
    cluster: str,
    baseline_ids: set[str],
    join_window: int,
    current_turn: int,
    attribution_ratio: float = 0.6,
) -> list[str]:
    """Rank write-window items by contribution to drift; return culprits.

    Raises if the join window is unbounded (no item identity bridge) or if
    drift is not attributable to a bounded set (distributed campaign).
    """
    if join_window <= 0 or join_window > current_turn:
        raise MemoryPoisoningInvariantError(
            f"join_window={join_window} invalid at turn {current_turn}; "
            "drift cannot be attributed to a bounded write set"
        )

    window = [
        it for it in items
        if not it.quarantined
        and current_turn - join_window <= it.admitted_turn <= current_turn
    ]
    if not window:
        raise MemoryPoisoningInvariantError(
            "drift alert with empty join window: no writable items to blame, "
            "drift is either legitimate shift or out-of-window poisoning"
        )

    full = _drift_with_suppressed(records, cluster, baseline_ids, set())
    contributions: list[tuple[float, str]] = []
    for it in window:
        without = _drift_with_suppressed(records, cluster, baseline_ids, {it.item_id})
        contributions.append((full - without, it.item_id))
    contributions.sort(reverse=True)

    culprits: list[str] = []
    remaining = full
    for drop, iid in contributions:
        if remaining <= full * (1 - attribution_ratio):
            break
        if drop <= 0:
            continue
        culprits.append(iid)
        remaining -= drop

    explained = (full - remaining) / full if full else 0.0
    if explained < attribution_ratio:
        raise MemoryPoisoningInvariantError(
            f"only {explained:.2f} of drift attributable to bounded window; "
            "distributed campaign or stale baseline — fail closed on cluster, "
            "do NOT rebaseline"
        )
    return culprits


def gate_write(
    item: MemoryItem,
    write_score: float,
    write_threshold: float,
    drift_low: float,
    cluster_drift: float,
) -> str:
    """Decide admission; the disagreement cell must not rebaseline."""
    if write_score > write_threshold:
        return "QUARANTINE_WRITE_SUSPECT"
    if cluster_drift > drift_low and write_score <= write_threshold:
        # The dangerous cell: clean write log + drift. Attribution required.
        return "ATTRIBUTION_REQUIRED"
    return "ADMIT_PROBATIONARY"
