# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-whose-provenance-weight-crossed-the-detection-threshold-mid-retrieval-and-how-does-re-scoring-after-quaranti.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-whose-provenance-weight-crossed-the-detection-threshold-mid-retrieval-and-how-does-re-scoring-after-quaranti.warrant.json
# Markdown SHA-256:   c56ce69a6da38e790bbad96441c9f2877618714fed139372ac27ba829669915f
# Code AST SHA-256:   6f0bc72cba444b67c9e78c87e4ae314f6cd6ef96ce1df646264282d83d51ca17
# Verified Classes:   ProvenanceQuarantineViolation, ProvenanceStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceQuarantineViolation(RuntimeError):
    """Raised when a quarantined record re-enters a retrieval candidate set."""
    pass


class ProvenanceStore:
    def __init__(self):
        self._records = {}       # id -> {relevance, trust_tier, decay, quarantined}
        self._transient_scores = {}  # per-turn score cache (the trap)

    def register(self, rid, relevance, trust_tier, decay=1.0):
        self._records[rid] = {
            "relevance": relevance,
            "trust_tier": trust_tier,
            "decay": decay,
            "quarantined": False,
        }

    def quarantine(self, rid, alpha=0.1):
        # UNSAFE PATTERN: sets a durable flag but ALSO nudges a transient score.
        # The transient nudge is what fools the operator into believing it is excluded.
        rec = self._records[rid]
        rec["quarantined"] = True
        self._transient_scores[rid] = rec["relevance"] * rec["trust_tier"] * alpha

    def retrieve(self, threshold=0.25):
        # BUG: rebuilds candidates from provenance inputs, ignores the flag,
        # and consults the transient cache only if present this turn.
        out = []
        for rid, rec in self._records.items():
            if rid in self._transient_scores:
                score = self._transient_scores[rid]
            else:
                score = rec["relevance"] * rec["trust_tier"] * rec["decay"]
            if score >= threshold:
                out.append((rid, score, rec["quarantined"]))
        out.sort(key=lambda t: t[1], reverse=True)
        return out


def guarded_retrieve(store, threshold=0.25):
    results = store.retrieve(threshold=threshold)
    for rid, score, quarantined in results:
        if quarantined:
            raise ProvenanceQuarantineViolation(
                f"record {rid!r} re-entered candidate set at score {score:.3f} "
                f"despite quarantine=true; exclusion predicate was bypassed"
            )
    return results


if __name__ == "__main__":
    store = ProvenanceStore()
    store.register("mem-genuine", relevance=0.62, trust_tier=0.9)
    store.register("mem-poisoned", relevance=0.81, trust_tier=0.3)
    store.quarantine("mem-poisoned", alpha=0.1)

    # Simulate the next turn: transient cache is gone, flag remains.
    store._transient_scores.clear()
    guarded_retrieve(store)  # raises: poisoned record outranks genuine one
