# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-survives-provenance-checks-contradiction-tolerant-retrieval-masking-injected-writes-under-multi-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-survives-provenance-checks-contradiction-tolerant-retrieval-masking-injected-writes-under-multi-hop.warrant.json
# Markdown SHA-256:   9993e5e344d0ea6169db6f852a9670b0169236acf7140857ecbb2cc0be584f2e
# Code AST SHA-256:   9599615b90638cc41869902d680d062509fec899dae8b04d0cadc229c21fa139
# Verified Classes:   ProvenanceDivergenceError, MemoryRecord, CoRetrievalNeighbor
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Sequence


class ProvenanceDivergenceError(RuntimeError):
    """Raised when a record's co-retrieval topology and trust gap indicate
    it is acting as an unverified slot-filler under multi-hop query pressure."""


@dataclass(frozen=True)
class MemoryRecord:
    record_id: str
    trust_tier: int          # 1 = highest trust, 5 = lowest
    query_family_hits: dict  # family -> co-retrieval count


@dataclass(frozen=True)
class CoRetrievalNeighbor:
    record_id: str
    trust_tier: int


THETA_D = 4.0
MIN_GAP = 1


def divergence_score(rec: MemoryRecord) -> float:
    hits = [c for c in rec.query_family_hits.values() if c > 0]
    if len(hits) < 2:
        return 1.0  # cannot condition on a single family; treat as non-divergent
    hits_sorted = sorted(hits)
    median = hits_sorted[len(hits_sorted) // 2]
    return max(hits) / max(median, 1)


def provenance_gap(
    rec: MemoryRecord, neighbors: Sequence[CoRetrievalNeighbor]
) -> int:
    if not neighbors:
        return 0
    tiers = sorted(n.trust_tier for n in neighbors)
    median_tier = tiers[len(tiers) // 2]
    return median_tier - rec.trust_tier


def gate_retrieval(
    rec: MemoryRecord,
    neighbors: Sequence[CoRetrievalNeighbor],
    corroborator_lookup: Callable[[str], bool],
) -> str:
    """Returns 'use', 'corroborate', or raises ProvenanceDivergenceError."""
    d = divergence_score(rec)
    g = provenance_gap(rec, neighbors)

    if d > THETA_D and g >= MIN_GAP:
        if corroborator_lookup(rec.record_id):
            return "corroborate"  # demote, do not delete
        raise ProvenanceDivergenceError(
            f"record {rec.record_id} is an unverified slot-filler: "
            f"D={d:.2f} (> {THETA_D}), G={g} (>= {MIN_GAP}), "
            f"no independent corroborator found; abstain on slot."
        )
    return "use"
