# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-write-audit-trail-whose-embedding-space-anomaly-score-is-clean.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-write-audit-trail-whose-embedding-space-anomaly-score-is-clean.warrant.json
# Markdown SHA-256:   36a51c18943de484de3de132159d343ffef96843f6f2b3d88f9238d987e9b58d
# Code AST SHA-256:   3fa9c8b97c420978dfd4fb09a9bd26b521c9fb114fc0dbcb29834063167a8150
# Verified Classes:   MemoryPoisoningBoundaryError, CandidateWrite
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class MemoryPoisoningBoundaryError(RuntimeError):
    """Raised when a write passes the single-axis anomaly gate but violates
    the contradiction/provenance invariant required for safe admission."""
    pass


@dataclass
class CandidateWrite:
    vector_z: float                 # anomaly score vs rolling centroid
    slot: str                       # e.g. "service:billing:region"
    value: str                      # e.g. "eu-west-1"
    actor: str
    input_taint: bool               # True if writer consumed untrusted input
    merkle_ok: bool


def admit_write(
    write: CandidateWrite,
    bound_slots: dict[str, str],     # slot -> currently bound value
    centroid_drift: float,
    drift_bound: float = 0.08,
    z_quarantine: float = 2.5,
) -> str:
    # Invariant 0: if the baseline itself has drifted, no score is trustworthy.
    if centroid_drift > drift_bound:
        raise MemoryPoisoningBoundaryError(
            f"Centroid drift {centroid_drift:.3f} exceeds bound {drift_bound}; "
            f"anomaly scores are invalid — refuse all admissions until rebaselined."
        )

    if not write.merkle_ok:
        raise MemoryPoisoningBoundaryError(
            f"Audit chain broken for actor={write.actor}; write rejected."
        )

    conflict: Optional[str] = bound_slots.get(write.slot)
    has_conflict = conflict is not None and conflict != write.value
    is_novel = write.vector_z >= z_quarantine

    # The dangerous quadrant: clean score AND contradiction.
    if has_conflict and not is_novel:
        raise MemoryPoisoningBoundaryError(
            f"Manifold-conforming poison suspected: slot={write.slot} "
            f"asserts {write.value!r} but bound value is {conflict!r}, "
            f"yet anomaly_z={write.vector_z:.2f} is clean. "
            f"actor={write.actor} taint={write.input_taint}. "
            f"Reject and flag actor; route through supersede path with attestation."
        )

    # Novel + contradicting: also reject, highest suspicion.
    if has_conflict and is_novel:
        raise MemoryPoisoningBoundaryError(
            f"Novel contradicting write on slot={write.slot}; reject."
        )

    # Tainted provenance on a slot write: require supersede attestation.
    if write.input_taint and write.slot in bound_slots:
        raise MemoryPoisoningBoundaryError(
            f"Tainted-provenance write to bound slot={write.slot} from "
            f"actor={write.actor}; requires two-actor supersede, not append."
        )

    if is_novel:
        return "quarantine"   # novel, non-conflicting: human/auditor review
    return "accept"
