# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-rising-memory-write-anomaly-score-as-evidence-of-context-poisoning-rather-than-benign-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-rising-memory-write-anomaly-score-as-evidence-of-context-poisoning-rather-than-benign-drift.warrant.json
# Markdown SHA-256:   e4524f0df46f66287e41f16c3a24e719fd1fae31e904d14b799d4c66e97aa0b2
# Code AST SHA-256:   d100b72d0dd4890720c5d1c4f9c5cffc09069841576876f8f1f1e89ea48366b7
# Verified Classes:   UngroundedWriteError, DriftMisclassifiedError, MemoryOp
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class UngroundedWriteError(RuntimeError):
    """Raised when a write is anomalous AND cannot be grounded to its claimed reads."""


class DriftMisclassifiedError(RuntimeError):
    """Raised when a benign drift write is about to be quarantined (amnesia bug)."""


@dataclass
class MemoryOp:
    op_id: str
    kind: str                    # "read" | "write"
    embedding: Sequence[float]
    provenance: list[str] = field(default_factory=list)


def _dist(a: Sequence[float], b: Sequence[float]) -> float:
    return sum((x - y) ** 2 for x, y in zip(a, b)) ** 0.5


def classify_write(
    write: MemoryOp,
    recent_reads: list[MemoryOp],
    older_reads: list[MemoryOp],
    anomaly_score: float,
    theta: float,
    asym_floor: float = 0.25,
) -> str:
    if write.kind != "write":
        raise ValueError("classify_write called on non-write op")

    # Grounding: every claimed provenance id must appear in the recent read window.
    read_ids = {r.op_id for r in recent_reads}
    ungrounded = [p for p in write.provenance if p not in read_ids]

    if anomaly_score <= theta:
        return "commit"

    d_recent = min((_dist(write.embedding, r.embedding) for r in recent_reads), default=float("inf"))
    d_older = min((_dist(write.embedding, r.embedding) for r in older_reads), default=float("inf"))
    asym = d_recent - d_older

    if ungrounded and asym >= asym_floor:
        # Anomalous + ungrounded + diverging from recent reads => poisoning.
        raise UngroundedWriteError(
            f"write {write.op_id} ungrounded (provenance {ungrounded}) "
            f"with asym={asym:.3f} >= {asym_floor}; quarantine and taint sources"
        )

    if not ungrounded and abs(asym) < asym_floor:
        # Anomalous but reads and writes moved together => drift; rebaseline.
        return "rebaseline_and_commit"

    if asym < -asym_floor:
        # Closer to older reads than recent ones => stale replay; dedupe.
        return "dedupe"

    # Anomalous, grounded, but asymmetric in a way we cannot attribute safely.
    raise DriftMisclassifiedError(
        f"write {write.op_id} ambiguous (asym={asym:.3f}); "
        f"do not quarantine blindly — route to entailment cross-check"
    )
