# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-a-provenance-weighted-retrieval-score-is-dominated-by-a-single-high-trust-write.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-a-provenance-weighted-retrieval-score-is-dominated-by-a-single-high-trust-write.warrant.json
# Markdown SHA-256:   1ff2ee8664c4c16a9f5165b36ebf278aff121ad359334fcdb7b9f32947678786
# Code AST SHA-256:   7f0ab69d0d67681196e821f7042247d69390d565012d3ab2f9e6a547ab488b27
# Verified Classes:   ProvenanceDominanceError, Record
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence

TAU = 0.5          # relevance threshold for admissibility
EPS = 0.1          # bounded provenance tiebreaker
TIER_RANK = {"T0": 3, "T1": 2, "T2": 1}


class ProvenanceDominanceError(RuntimeError):
    """Raised when a single high-trust record dominates retrieval across queries,
    or when a store's tier weights violate the relevance-dominance invariant."""


@dataclass
class Record:
    id: str
    tier: str
    similarity: float


def admit_and_rank(query_id: str, records: Sequence[Record],
                   history: dict[str, int]) -> list[Record]:
    # Invariant check 1: high-trust, below-threshold records must never outrank
    # low-trust, above-threshold records.
    high_below = [r for r in records if r.tier == "T0" and r.similarity < TAU]
    low_above = [r for r in records if r.tier != "T0" and r.similarity >= TAU]
    if high_below and low_above:
        # Under scalar weighting this is exactly the poisoning window.
        raise ProvenanceDominanceError(
            f"query {query_id}: {len(high_below)} below-threshold T0 records "
            f"compete with {len(low_above)} above-threshold lower-tier records; "
            f"scalar provenance weighting would invert relevance."
        )

    admissible = [r for r in records if r.similarity >= TAU]
    ranked = sorted(
        admissible,
        key=lambda r: r.similarity * (1 + EPS * TIER_RANK[r.tier]),
        reverse=True,
    )

    # Invariant check 2: single-record occupancy across queries.
    for r in ranked:
        history[r.id] = history.get(r.id, 0) + 1
        if history[r.id] > 1 and ranked.index(r) < len(ranked) // 2:
            raise ProvenanceDominanceError(
                f"record {r.id} occupies top-half of top-k across "
                f"{history[r.id]} queries; require contradiction-check before use."
            )
    return ranked
