# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-memory-write-whose-audit-score-was-computed-against-a-poisoned-baseline.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-memory-write-whose-audit-score-was-computed-against-a-poisoned-baseline.warrant.json
# Markdown SHA-256:   fc9ff5fcd66075e86839a84c6d8c7b73d04a5d177d5fcab467f64214249025c9
# Code AST SHA-256:   ecdf0ca135bad43d0bc604cb4a610964e4980d1963bf537a1535e880b34a332d
# Verified Classes:   BaselineCaptureError, WriteAuditGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Callable


class BaselineCaptureError(RuntimeError):
    """Raised when a write-audit baseline has drifted beyond its anchored reference,
    indicating the scoring distribution has been influenced by the writes it scores."""


@dataclass
class WriteAuditGate:
    slow_baseline_score: Callable[[dict], float]   # pinned, human-reviewed, not refit from writes
    fast_baseline_score: Callable[[dict], float]   # trailing-window, refit from committed writes
    quarantine_threshold: float = 0.92
    divergence_limit: float = 0.35                 # max allowed fast-vs-slow score gap per region

    _region_divergence: dict[str, float] = field(default_factory=dict)

    def _region_key(self, write: dict) -> str:
        # Region is a coarse topic bucket; must not be derived from write mass.
        return hashlib.sha256(write["topic"].encode()).hexdigest()[:16]

    def admit(self, write: dict) -> bool:
        region = self._region_key(write)
        slow = self.slow_baseline_score(write)
        fast = self.fast_baseline_score(write)

        # Guardrail 1: anchored baseline must not flag the write as anomalous.
        if slow >= self.quarantine_threshold:
            return False

        # Guardrail 2: fast baseline must also not flag it.
        if fast >= self.quarantine_threshold:
            return False

        # Guardrail 3: divergence monitor. If the fast baseline has drifted
        # substantially below the slow baseline for this region, the region's
        # fast baseline has been captured by accumulated sub-threshold writes.
        divergence = slow - fast
        self._region_divergence[region] = max(
            self._region_divergence.get(region, 0.0), divergence
        )
        if self._region_divergence[region] > self.divergence_limit:
            raise BaselineCaptureError(
                f"region {region} fast-baseline divergence {divergence:.3f} "
                f"exceeds limit {self.divergence_limit:.3f}; "
                f"baseline has likely absorbed adversarial writes; freeze region and roll back"
            )

        return True
