# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-persistent-agent-memory-stores-the-write-amplification-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-persistent-agent-memory-stores-the-write-amplification-invariant.warrant.json
# Markdown SHA-256:   744ebf65ff94a806e00b46d8fbf237a8a25244071c4ae8839ca52a70078a8124
# Code AST SHA-256:   742b900bcf481947cbbf7221a654973bb44ce8f206a385f7bb2d316e173b87ec
# Verified Classes:   MemoryPoisoningInvariantError, SourceWindow
# Defensive Guards:   1 fail-closed invariants (zero external deps)

"""Quarantine gate for the write-amplification invariant.

Operates on per-source rolling counters. Raises when the conjunction of
retrieval inflation, citation deflation, and near-duplicate clustering
fires -- never on any single condition.
"""

from dataclasses import dataclass


class MemoryPoisoningInvariantError(RuntimeError):
    """Raised when a source violates the write-amplification invariant."""
    pass


@dataclass(frozen=True)
class SourceWindow:
    source_id: str
    writes: int
    retrievals: int
    citations: int
    baseline_retrieval_rate: float      # 30-day median retrievals/write
    baseline_orphan_ratio: float        # 30-day median, with sigma
    orphan_ratio_sigma: float
    near_dup_fraction: float            # fraction of high-retrieval records in tight clusters
    near_dup_entity_concentration: float  # share of edit distance on one entity type
    source_age_days: float


MIN_WRITES = 500
MIN_AGE_DAYS = 7.0
RETRIEVAL_INFLATION = 4.0
ORPHAN_Z = 2.0
NEAR_DUP_FRACTION = 0.30
ENTITY_CONCENTRATION = 0.50


def evaluate_source(w: SourceWindow) -> str:
    # Suspend the invariant for cold-start sources: no stationary baseline.
    if w.source_age_days < MIN_AGE_DAYS or w.writes < MIN_WRITES:
        return "insufficient_baseline"

    if w.writes == 0:
        return "no_writes"

    retrieval_rate = w.retrievals / w.writes
    inflation = retrieval_rate / max(w.baseline_retrieval_rate, 1e-9)

    orphans = w.retrievals - w.citations
    orphan_ratio = orphans / w.retrievals if w.retrievals else 0.0
    orphan_threshold = w.baseline_orphan_ratio + ORPHAN_Z * w.orphan_ratio_sigma

    cond_inflation = inflation >= RETRIEVAL_INFLATION
    cond_orphans = orphan_ratio >= max(orphan_threshold, 0.60)
    cond_clusters = (
        w.near_dup_fraction >= NEAR_DUP_FRACTION
        and w.near_dup_entity_concentration >= ENTITY_CONCENTRATION
    )

    # Conjunction only. Any single condition is expected on busy days.
    if cond_inflation and cond_orphans and cond_clusters:
        raise MemoryPoisoningInvariantError(
            f"source={w.source_id} violates write-amplification invariant: "
            f"inflation={inflation:.2f}x orphan_ratio={orphan_ratio:.2f} "
            f"(threshold {orphan_threshold:.2f}) "
            f"near_dup={w.near_dup_fraction:.2f} "
            f"entity_conc={w.near_dup_entity_concentration:.2f} "
            f"-> quarantine (shadow index), preserve for forensics"
        )

    if cond_inflation and not cond_orphans:
        # Campaign may have overridden the agent's consistency check.
        return "cited_poisoning_suspect"  # escalate to blast-radius estimation

    return "clear"


def gate(windows: list[SourceWindow]) -> dict[str, str]:
    results: dict[str, str] = {}
    for w in windows:
        try:
            results[w.source_id] = evaluate_source(w)
        except MemoryPoisoningInvariantError as exc:
            results[w.source_id] = f"QUARANTINE: {exc}"
    return results
