# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-write-audit-diff-false-negative-poisoning-detection-under-write-coalescing-and-legitimate-high-entropy-writes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-write-audit-diff-false-negative-poisoning-detection-under-write-coalescing-and-legitimate-high-entropy-writes.warrant.json
# Markdown SHA-256:   68d8bbf4243050d1e9e21488c915c1ae2b897f14e796bb108a704f80ea5b35a3
# Code AST SHA-256:   1ec57c4ee424c35474289303c00496065dfa9119e6ce1f7e529f2b00af42dbb0
# Verified Classes:   CoalescedDiffAttestationError, DiffInterval
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CoalescedDiffAttestationError(RuntimeError):
    """Raised when a clean anomaly score is being treated as a provenance
    attestation on a diff interval that is not atomic (multiple trust
    classes touched the same partition, or a benign bulk write was folded
    into the baseline)."""
    pass


class DiffInterval:
    def __init__(self, partition: str, writers: set[str], trust_classes: set[str],
                 bulk_write_folded_into_baseline: bool, baseline_entropy_shift_sigma: float):
        self.partition = partition
        self.writers = writers
        self.trust_classes = trust_classes
        self.bulk_write_folded_into_baseline = bulk_write_folded_into_baseline
        self.baseline_entropy_shift_sigma = baseline_entropy_shift_sigma


def attest_clean(interval: DiffInterval, anomaly_score: float, threshold: float = 0.6) -> bool:
    """Return True only if a low score is a valid provenance attestation."""
    if anomaly_score >= threshold:
        # High score: alert regardless; not the failure mode under study.
        return False

    if len(interval.trust_classes) > 1:
        raise CoalescedDiffAttestationError(
            f"partition {interval.partition!r} received writes from trust classes "
            f"{sorted(interval.trust_classes)} within one interval; "
            f"score {anomaly_score:.2f} bounds only the net delta and cannot "
            f"attest absence of poisoning (shadow-overwrite / deletion-restoration risk)."
        )

    if interval.bulk_write_folded_into_baseline and interval.baseline_entropy_shift_sigma > 1.0:
        raise CoalescedDiffAttestationError(
            f"baseline for {interval.partition!r} was widened by a bulk write "
            f"({interval.baseline_entropy_shift_sigma:.2f} sigma); targeted poisoning "
            f"now scores below threshold. Baseline is poisoned; re-derive from "
            f"stationary traffic before trusting score {anomaly_score:.2f}."
        )

    return True


def gate_retrieval_write(interval: DiffInterval, anomaly_score: float) -> str:
    if attest_clean(interval, anomaly_score):
        return "attested_clean"
    if anomaly_score >= 0.6:
        return "alert"
    # Low score but unattestable: must not be treated as clean.
    return "uninformative_do_not_serve"
