# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-weighted-retrieval-from-silently-laundering-poisoned-memory-into-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-weighted-retrieval-from-silently-laundering-poisoned-memory-into-consensus.warrant.json
# Markdown SHA-256:   700c3b837d54b8467f0be78a443eda7d997d7010d1e60f744e64be61a2a66bd8
# Code AST SHA-256:   f57fd2c8123b5fd5d680347b996d3d1998da71869cab864fb5621fb4ff58b406
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a retrieval/read event is used to mutate a gating signal,
    or when an entry's effective rank diverges from its immutable write-provenance
    beyond the tier width without quarantine."""
    pass


@dataclass
class MemoryEntry:
    entry_id: str
    source_trust: float              # immutable, set at write from attested registry
    write_corroboration: int = 0     # incremented only by distinct attested writes
    retrieval_corroboration: int = 0 # incremented by reads; RANKING ONLY
    quarantined: bool = False


TIER_WIDTH = 0.1          # trust tiers are 0.1 wide
RANK_PERCENTILE_CEIL = 0.75


def gating_weight(entry: MemoryEntry) -> float:
    """Weight used to decide ELIGIBILITY. Must depend only on write-provenance."""
    if entry.quarantined:
        return 0.0
    return entry.source_trust * math.log(1 + entry.write_corroboration)


def ranking_weight(entry: MemoryEntry) -> float:
    """Weight used only to ORDER already-eligible candidates. May use reads."""
    return gating_weight(entry) * math.log(1 + entry.retrieval_corroboration)


def record_retrieval(entry: MemoryEntry, rank_percentile: float) -> None:
    """A read event. May update ranking signal, must never touch gating signal.
    Enforces the disjointness invariant and the divergence quarantine."""
    if not (0.0 <= rank_percentile <= 1.0):
        raise ProvenanceLaunderingError(
            f"invalid rank percentile {rank_percentile} for {entry.entry_id}"
        )

    # Invariant: reads may not mutate write_corroboration.
    # (This is the laundering vector; we assert it explicitly.)
    before = entry.write_corroboration
    entry.retrieval_corroboration += 1
    if entry.write_corroboration != before:
        raise ProvenanceLaunderingError(
            f"read event mutated gating signal for {entry.entry_id}"
        )

    # Divergence check: high effective rank + low immutable trust => quarantine.
    if rank_percentile > RANK_PERCENTILE_CEIL and entry.source_trust < 0.4:
        entry.quarantined = True
        raise ProvenanceLaunderingError(
            f"provenance divergence on {entry.entry_id}: "
            f"rank_pct={rank_percentile:.2f} but source_trust={entry.source_trust:.2f}; "
            f"quarantined pending re-attestation"
        )


def attest_write(entry: MemoryEntry, attested_source_id: str, seen_sources: set) -> None:
    """The ONLY path that may raise gating weight. Requires a distinct attested source."""
    if attested_source_id in seen_sources:
        raise ProvenanceLaunderingError(
            f"duplicate attestation source {attested_source_id} for {entry.entry_id}"
        )
    seen_sources.add(attested_source_id)
    entry.write_corroboration += 1
    entry.quarantined = False


# --- demonstration of the laundering path being caught ---
if __name__ == "__main__":
    e = MemoryEntry(entry_id="inj-001", source_trust=0.30)
    sources = set()
    # attacker forces 200 incidental near-match retrievals
    for i in range(200):
        try:
            record_retrieval(e, rank_percentile=0.80)
        except ProvenanceLaunderingError as err:
            print(f"cycle {i}: BLOCKED -> {err}")
            break
    assert e.quarantined, "invariant failed: poison not quarantined"
    assert gating_weight(e) == 0.0, "quarantined entry still gating-eligible"
    print("gating weight after quarantine:", gating_weight(e))
