# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-write-path-provenance-weighted-retrieval-and-anomaly-scoring-for-memory-poisoning-detection.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-write-path-provenance-weighted-retrieval-and-anomaly-scoring-for-memory-poisoning-detection.warrant.json
# Markdown SHA-256:   29e619661770fd4c7d57235ec70920ddd97f2635e94e2a8fc2fc4aa292ed3378
# Code AST SHA-256:   373bd25550cee2e9fabbfeb432bb6918f78bc819d19e3371e1ccdf6bec4a783e
# Verified Classes:   MemoryPoisoningInvariantError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class MemoryPoisoningInvariantError(RuntimeError):
    """Raised when a write path's provenance weighting can no longer
    support trustworthy anomaly scoring (drift, contradiction, or
    weight-exploitation boundary crossed)."""
    pass


DRIFT_FRACTION = 0.5          # centroid drift as fraction of anomaly threshold
CONTRADICTION_BASELINE = 0.05  # expected pairwise contradiction rate
RETRIEVAL_WEIGHT_MULTIPLE = 3.0


def audit_write_path(source_id, centroid_drift, anomaly_threshold,
                     contradiction_rate, retrieval_count,
                     provenance_weight, contradicted):
    if anomaly_threshold <= 0:
        raise MemoryPoisoningInvariantError(
            f"source {source_id}: non-positive anomaly threshold "
            f"{anomaly_threshold}; scoring is undefined"
        )

    # Slow-poisoning inversion: centroid has drifted toward recent writes,
    # so this source's own unary scores are no longer trustworthy.
    if abs(centroid_drift) > DRIFT_FRACTION * anomaly_threshold:
        raise MemoryPoisoningInvariantError(
            f"source {source_id}: centroid drift {centroid_drift:.3f} exceeds "
            f"{DRIFT_FRACTION} x threshold {anomaly_threshold:.3f}; "
            f"quarantine source, do not trust its anomaly scores"
        )

    # High-trust-channel poisoning: contradiction surfaced at retrieval.
    if contradiction_rate > CONTRADICTION_BASELINE and provenance_weight >= 0.8:
        raise MemoryPoisoningInvariantError(
            f"source {source_id}: high-weight source ({provenance_weight}) "
            f"contradiction rate {contradiction_rate:.3f} above baseline; "
            f"weight-exploitation suspected"
        )

    # Weight-exploiting poison signature: over-retrieved yet contradicted.
    expected_share = max(provenance_weight, 1e-6)
    if (retrieval_count > RETRIEVAL_WEIGHT_MULTIPLE * expected_share
            and contradicted):
        raise MemoryPoisoningInvariantError(
            f"source {source_id}: retrieval {retrieval_count} far exceeds "
            f"weight-expected share {expected_share:.3f} with nonzero "
            f"contradictions; demote provenance weight"
        )

    return "trusted"


def admit_write(record, source_state):
    try:
        verdict = audit_write_path(
            source_id=record["source"],
            centroid_drift=source_state["centroid_drift"],
            anomaly_threshold=source_state["anomaly_threshold"],
            contradiction_rate=source_state["contradiction_rate"],
            retrieval_count=record.get("retrieval_count", 0),
            provenance_weight=record["provenance_weight"],
            contradicted=record.get("contradicted", False),
        )
    except MemoryPoisoningInvariantError:
        record["status"] = "quarantined"
        raise
    record["status"] = verdict
    return record
