# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-retrieved-context-by-provenance-taint-rather-than-by-content-similarity-and-why-similarity-based-san.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-retrieved-context-by-provenance-taint-rather-than-by-content-similarity-and-why-similarity-based-san.warrant.json
# Markdown SHA-256:   9528cc88beac8f279b6caf16152ece0478a96db5fc174df35c80e6e7230f61a2
# Code AST SHA-256:   af87b00f3e8f07f12343a836bc8921c0517e38cab3f8780cf0c60af203fafa0a
# Verified Classes:   TaintedContextAdmitted, ProvenanceUnattested, Chunk
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TaintedContextAdmitted(RuntimeError):
    """Raised when a tainted chunk would enter the admitted context set."""
    pass


class ProvenanceUnattested(RuntimeError):
    """Raised when a chunk has no provenance record and cannot be trust-classified."""
    pass


@dataclass(frozen=True)
class Chunk:
    text: str
    provenance_hash: str
    descends_from_untrusted: bool
    similarity: float


def admit_context(
    candidates: list[Chunk],
    k: int,
    authorized_provenance: Optional[frozenset[str]] = None,
    min_clean_coverage: float = 0.5,
) -> list[Chunk]:
    authorized = authorized_provenance or frozenset()
    clean: list[Chunk] = []

    for c in candidates:
        if not c.provenance_hash:
            # Fail closed: un-attested chunk is indistinguishable from forged.
            raise ProvenanceUnattested(
                f"chunk has no provenance record; refusing to rank it (sim={c.similarity:.2f})"
            )
        if c.descends_from_untrusted and c.provenance_hash not in authorized:
            # Quarantine BEFORE ranking. Never down-rank; exclude.
            continue
        clean.append(c)

    clean.sort(key=lambda c: c.similarity, reverse=True)
    admitted = clean[:k]

    # Invariant: no tainted chunk may occupy the admitted set.
    for c in admitted:
        if c.descends_from_untrusted and c.provenance_hash not in authorized:
            raise TaintedContextAdmitted(
                f"taint invariant violated by {c.provenance_hash}"
            )

    # If clean coverage is too thin, refuse rather than fall back to poison.
    if len(admitted) < k * min_clean_coverage:
        raise TaintedContextAdmitted(
            f"clean coverage {len(admitted)}/{k} below threshold; "
            f"refuse or escalate instead of admitting tainted context"
        )
    return admitted
