# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-anomaly-score-is-itself-computed-over-the-poisoning-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-anomaly-score-is-itself-computed-over-the-poisoning-window.warrant.json
# Markdown SHA-256:   f9cd01fde8630581aa7985955dfc248e561d4fa1d36170dd60f93f991c4ba9ca
# Code AST SHA-256:   578a9a1caf78932581a7fdd5e6ef4d2556cb219622e7e55faebd3e7e460e4887
# Verified Classes:   ReferenceContaminationError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ReferenceContaminationError(RuntimeError):
    """Raised when the live anomaly window has drifted from the frozen baseline
    far enough that per-write scores can no longer be trusted."""
    pass


def score_write(
    write_drift: float,
    live_mean: float,
    live_sigma: float,
    frozen_mean: float,
    contamination_bound: float = 0.12,
    sigma_multiplier: float = 2.4,
) -> dict:
    # Primary gate: is the reference itself still valid?
    reference_drift = abs(live_mean - frozen_mean)
    if reference_drift > contamination_bound:
        # Do NOT score against the live window; it may be attacker-co-authored.
        raise ReferenceContaminationError(
            f"live window mean {live_mean:.3f} diverged from frozen baseline "
            f"{frozen_mean:.3f} by {reference_drift:.3f} > bound "
            f"{contamination_bound:.3f}; per-write scores untrustworthy, "
            f"halt scoring and replay against frozen baseline"
        )

    # Only reached if the reference is still anchored.
    threshold = frozen_mean + sigma_multiplier * live_sigma
    z = (write_drift - frozen_mean) / max(live_sigma, 1e-9)
    return {
        "flagged": write_drift > threshold,
        "z_score": z,
        "reference_drift": reference_drift,
        "scored_against": "frozen_baseline",
    }
