# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-vector-store-write-before-it-becomes-a-durable-memory-detecting-late-arriving-poison-via-retrieval.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-vector-store-write-before-it-becomes-a-durable-memory-detecting-late-arriving-poison-via-retrieval.warrant.json
# Markdown SHA-256:   59be61fb8b83941825b1dd633ad9b0c3410554de42b31d77837f8b5a64f80081
# Code AST SHA-256:   f7118d0239cd86ba6308749efba589b58d896b39f0b2f020c69b114c756d9d05
# Verified Classes:   ShadowInvariantViolation, QuarantineRequired, ProbeQuery, MemoryRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass, field
from typing import Sequence

class ShadowInvariantViolation(RuntimeError):
    """Raised when a stored record's retrieval shadow cannot be bounded."""
    pass

class QuarantineRequired(ShadowInvariantViolation):
    """Raised when a record must be demoted before it shadows foreign queries."""
    pass

@dataclass
class ProbeQuery:
    text: str
    expected_ids: frozenset[str]

@dataclass
class MemoryRecord:
    record_id: str
    embedding: Sequence[float]
    quarantined: bool = False

def _cosine(a: Sequence[float], b: Sequence[float]) -> float:
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(y * y for y in b))
    if na == 0.0 or nb == 0.0:
        return 0.0
    return dot / (na * nb)

def _top_k(
    query_vec: Sequence[float],
    records: Sequence[MemoryRecord],
    k: int,
    exclude: str | None = None,
) -> list[str]:
    scored = [
        (_cosine(query_vec, r.embedding), r.record_id)
        for r in records
        if not r.quarantined and r.record_id != exclude
    ]
    scored.sort(reverse=True)
    return [rid for _, rid in scored[:k]]

def compute_shadow(
    candidate: MemoryRecord,
    probes: Sequence[ProbeQuery],
    records: Sequence[MemoryRecord],
    query_vecs: dict[str, Sequence[float]],
    k: int = 3,
) -> tuple[int, int]:
    """Return (own_displacement, foreign_displacement) for the candidate.

    own     = probe queries where candidate is an expected answer.
    foreign = probe queries where candidate is NOT expected but enters top-k
              and pushes an expected record out of top-k.
    """
    own = 0
    foreign = 0
    for probe in probes:
        qv = query_vecs[probe.text]
        with_cand = _top_k(qv, records, k)
        without = _top_k(qv, records, k, exclude=candidate.record_id)
        if candidate.record_id not in with_cand:
            continue
        if candidate.record_id in probe.expected_ids:
            own += 1
            continue
        # Foreign hit: candidate displaced an expected record from the top-k.
        displaced = probe.expected_ids.intersection(without) - set(with_cand)
        if displaced:
            foreign += 1
    return own, foreign

def enforce_shadow_invariant(
    candidate: MemoryRecord,
    probes: Sequence[ProbeQuery],
    records: Sequence[MemoryRecord],
    query_vecs: dict[str, Sequence[float]],
    k: int = 3,
    foreign_floor: int = 5,
    ratio_bound: float = 3.0,
) -> None:
    if not probes:
        raise ShadowInvariantViolation(
            "no probe set: shadow invariant is unmeasurable and void"
        )
    own, foreign = compute_shadow(candidate, probes, records, query_vecs, k)
    if foreign >= foreign_floor and (own == 0 or foreign / own > ratio_bound):
        candidate.quarantined = True
        raise QuarantineRequired(
            f"record {candidate.record_id} shadows {foreign} foreign probes "
            f"(own={own}); demote to scoped retrieval tier"
        )
