# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-context-poisoning-when-anomaly-scores-are-computed-over-retrieval-drift-rather-than-write-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-context-poisoning-when-anomaly-scores-are-computed-over-retrieval-drift-rather-than-write-provenance.warrant.json
# Markdown SHA-256:   a74f9d969e61a348eeb4ab202db34a1add1a0b78cf36f5d76767fe437cec440d
# Code AST SHA-256:   6b2533c419b0d2a2ec0fd9943a700564bc01d414fa8840cf10fa04f390de717b
# Verified Classes:   ContextPoisoningDetectorError, MemoryWrite, PoisoningDetector
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ContextPoisoningDetectorError(RuntimeError):
    """Raised when a poisoning verdict cannot be trusted because the
    detector relies on retrieval drift without write provenance."""
    pass


class MemoryWrite:
    def __init__(self, record_id: str, source_tool: str, written_at: float):
        self.record_id = record_id
        self.source_tool = source_tool
        self.written_at = written_at


class PoisoningDetector:
    def __init__(self, baseline_frozen_at: float, burst_window_s: float = 60.0,
                 burst_threshold: int = 25):
        self.baseline_frozen_at = baseline_frozen_at
        self.burst_window_s = burst_window_s
        self.burst_threshold = burst_threshold
        self._writes: list[MemoryWrite] = []

    def record_write(self, w: MemoryWrite) -> None:
        if w.written_at < self.baseline_frozen_at:
            # Writes older than the frozen baseline cannot be scored against it.
            raise ContextPoisoningDetectorError(
                f"write {w.record_id} predates frozen baseline; "
                "baseline immutability violated"
            )
        self._writes.append(w)

    def assess(self, drift_score_sigma: float, has_provenance_feature: bool) -> str:
        # Invariant: a low drift score is only admissible as evidence of health
        # if an independent write-provenance feature is present.
        if drift_score_sigma < 1.0 and not has_provenance_feature:
            raise ContextPoisoningDetectorError(
                "low drift without provenance feature: detector is a "
                "retrieval-stability monitor, not a poisoning detector"
            )
        recent = [w for w in self._writes
                  if w.written_at >= self.baseline_frozen_at]
        if len(recent) >= self.burst_threshold:
            span = max(w.written_at for w in recent) - min(
                w.written_at for w in recent)
            if span <= self.burst_window_s:
                return "QUARANTINE: write-burst provenance anomaly"
        return "HEALTHY" if drift_score_sigma < 3.0 else "ALERT: drift"
