# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-memory-writes-that-pass-every-provenance-check-but-fail-on-write-path-anomaly-scoring.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-memory-writes-that-pass-every-provenance-check-but-fail-on-write-path-anomaly-scoring.warrant.json
# Markdown SHA-256:   d05c9c26d16eaff3244ced4b1c0710ac48b4e7cf9c93c7a27d3b6cfdff3f1685
# Code AST SHA-256:   2484bc8c4c8b9dca982b3c8834d17b2db34d8f94a73bae2a82d0d237d57f174c
# Verified Classes:   BaselineContaminationError, WriteBatch, FrozenBaselineGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field

class BaselineContaminationError(RuntimeError):
    """Raised when a write batch would score against a baseline it has itself perturbed."""
    pass

@dataclass
class WriteBatch:
    session_id: str
    region: str
    writes: list
    provisional: list = field(default_factory=list)

class FrozenBaselineGate:
    PER_WRITE_REJECT = 0.82
    PER_WRITE_PROVISIONAL = 0.60
    BATCH_DRIFT_SIGMA = 1.5
    COLD_BATCH_DRIFT_SIGMA = 2.0

    def __init__(self, frozen_snapshot, cold_region_loader):
        self.frozen = frozen_snapshot          # immutable for the batch
        self.cold_loader = cold_region_loader   # provenance-anchored, pre-suspicion
        self.drift_accumulator = {}

    def score_write(self, write, baseline):
        return baseline.score(write)  # composite 5-dim anomaly score

    def admit_batch(self, batch: WriteBatch):
        for w in batch.writes:
            s = self.score_write(w, self.frozen)
            if s > self.PER_WRITE_REJECT:
                raise BaselineContaminationError(
                    f"write {w.id} rejected at {s:.2f} against frozen baseline"
                )
            if s >= self.PER_WRITE_PROVISIONAL:
                batch.provisional.append(w)
                self.drift_accumulator[batch.region] = (
                    self.drift_accumulator.get(batch.region, 0.0)
                    + self.frozen.centroid_shift(batch.region, w)
                )
            # NOTE: provisional writes are NOT folded into self.frozen.
            # Folding them here is exactly the contamination this gate prevents.

        drift = self.drift_accumulator.get(batch.region, 0.0)
        if drift > self.BATCH_DRIFT_SIGMA or len(batch.provisional) > max(
            3, int(0.1 * self.frozen.region_size(batch.region))
        ):
            cold = self.cold_loader(batch.region)
            for w in batch.provisional:
                cs = self.score_write(w, cold)
                if cs > self.PER_WRITE_REJECT:
                    raise BaselineContaminationError(
                        f"provisional write {w.id} re-scored {cs:.2f} "
                        f"against cold baseline; batch quarantined"
                    )
            if cold.centroid_shift(batch.region, batch.provisional) > self.COLD_BATCH_DRIFT_SIGMA:
                raise BaselineContaminationError(
                    f"batch collective drift exceeds cold threshold in region {batch.region}"
                )
        return True
