# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-provenance-weighted-retrieval-after-a-quarantine-eviction-the-re-weighting-inversion-at-the-trust-deca.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-provenance-weighted-retrieval-after-a-quarantine-eviction-the-re-weighting-inversion-at-the-trust-deca.warrant.json
# Markdown SHA-256:   398f71d28c7afd39031efda56c49a9f63ca43ea24ce761a54157fcc0415d1dca
# Code AST SHA-256:   dc039e8142445b7c285d78c26ebaf115b4f6e0d790d0cf9654ec068569a56622
# Verified Classes:   ProvenanceInversionError, MemoryRecord, TrustLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceInversionError(RuntimeError):
    """Raised when a quarantine eviction would orphan a source's trust posterior."""


@dataclass
class MemoryRecord:
    record_id: str
    source_id: str
    content: str
    quarantined: bool = False


@dataclass
class TrustLedger:
    # Durable per-source evidence; survives record eviction.
    verified_writes: dict[str, int] = field(default_factory=dict)
    quarantine_events: dict[str, int] = field(default_factory=dict)

    def base_trust(self, source_id: str) -> float:
        v = self.verified_writes.get(source_id, 0)
        q = self.quarantine_events.get(source_id, 0)
        # Posterior must include quarantine events permanently.
        denom = v + q
        if denom == 0:
            return 0.0
        return v / denom

    def retrieval_weight(self, source_id: str) -> float:
        # Monotone non-increasing in quarantine_events, invariant to eviction.
        return self.base_trust(source_id)


def evict_quarantined(records: list[MemoryRecord], ledger: TrustLedger) -> list[MemoryRecord]:
    survivors = []
    for r in records:
        if r.quarantined:
            # Record leaves retrieval set AND its provenance is retained as
            # a permanent quarantine event in the ledger.
            ledger.quarantine_events[r.source_id] = (
                ledger.quarantine_events.get(r.source_id, 0) + 1
            )
            continue
        survivors.append(r)

    # Invariant check: no source may have a retrieval weight that ignores
    # a quarantine event recorded during this eviction.
    for source_id, q in ledger.quarantine_events.items():
        if q > 0 and ledger.retrieval_weight(source_id) >= 1.0:
            raise ProvenanceInversionError(
                f"source {source_id} has {q} quarantine event(s) but weight "
                f"{ledger.retrieval_weight(source_id):.3f}; posterior was not "
                f"recomputed from surviving evidence"
            )
    return survivors


def guarded_retrieve(records: list[MemoryRecord], ledger: TrustLedger, source_id: str) -> float:
    weight = ledger.retrieval_weight(source_id)
    if source_id in ledger.quarantine_events and weight >= 1.0:
        raise ProvenanceInversionError(
            f"retrieval weight for {source_id} is {weight:.3f} despite quarantine "
            f"history; refusing to inject at unaccountable weight"
        )
    return weight
