# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-benign-provenance-drift-from-adversarial-memory-poisoning-when-anomaly-scores-are-computed-on-writes-but-recall-is.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-benign-provenance-drift-from-adversarial-memory-poisoning-when-anomaly-scores-are-computed-on-writes-but-recall-is.warrant.json
# Markdown SHA-256:   304cd164a5cd7db4b562c0870146e978064aa2693b0797208b2eaaf675515184
# Code AST SHA-256:   302ed375f1f032a84f7933d8c1be9a0a0222f93ecb541358d7b7331587b07314
# Verified Classes:   ProvenanceDriftError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceDriftError(RuntimeError):
    """Raised when a write is flagged anomalous but retains trust weight
    sufficient to dominate recall — the unexamined cross-product regime."""
    pass


WRITE_THRESHOLD = 0.5
PROVENANCE_CAP = 0.3
PROVENANCE_MEDIAN = 0.45


def effective_recall_weight(
    write_anomaly_score: float,
    provenance_weight: float,
    record_id: str,
) -> float:
    """Compute the recall-time weight after applying the feedback cap.

    A record flagged at write time must not retain provenance weight
    above PROVENANCE_CAP, regardless of how trusted its writer is.
    """
    if not (0.0 <= write_anomaly_score <= 1.0):
        raise ProvenanceDriftError(
            f"record {record_id}: anomaly score {write_anomaly_score} out of range"
        )
    if not (0.0 <= provenance_weight <= 1.0):
        raise ProvenanceDriftError(
            f"record {record_id}: provenance weight {provenance_weight} out of range"
        )

    flagged = write_anomaly_score > WRITE_THRESHOLD

    if flagged and provenance_weight <= PROVENANCE_CAP:
        # Already safe; cap is a no-op but record the invariant held.
        return provenance_weight

    if flagged and provenance_weight > PROVENANCE_CAP:
        # The cross-product regime: flagged AND trusted. Demote at recall.
        # This is the exact condition the naive design misses.
        if provenance_weight > PROVENANCE_MEDIAN:
            # High-trust flagged record is the laundering signature.
            # Surface it loudly; silent demotion would hide the attack.
            raise ProvenanceDriftError(
                f"record {record_id}: flagged (s={write_anomaly_score:.2f}) "
                f"but provenance {provenance_weight:.2f} exceeds median "
                f"{PROVENANCE_MEDIAN:.2f}; possible trust laundering"
            )
        return PROVENANCE_CAP

    # Not flagged: legitimate-trust regime. Do not cap.
    return provenance_weight


def rank_recall(
    candidates: list[tuple[str, float, float]],
) -> list[tuple[str, float]]:
    """Rank (record_id, anomaly, provenance) by effective recall weight."""
    ranked = []
    for record_id, anomaly, provenance in candidates:
        try:
            weight = effective_recall_weight(anomaly, provenance, record_id)
        except ProvenanceDriftError:
            # Quarantine: exclude from ranking, surface for audit.
            weight = 0.0
        ranked.append((record_id, weight))
    return sorted(ranked, key=lambda kv: kv[1], reverse=True)
