# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-cross-agent-context-bleed-when-multiple-agents-share-a-single-vector-namespace.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-cross-agent-context-bleed-when-multiple-agents-share-a-single-vector-namespace.warrant.json
# Markdown SHA-256:   17a92e1ff7ea4ef36668c1c874c43da16b86d06881c4c9d7718babea1e3f5fc0
# Code AST SHA-256:   03d5c98c74ceb77675bd61247bfe57333f830f015f5b970f03ea188dbc72332a
# Verified Classes:   CrossNamespaceLeak, Candidate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class CrossNamespaceLeak(RuntimeError):
    """Raised when a retrieval pipeline stage sees content outside its namespace."""
    pass


@dataclass(frozen=True)
class Candidate:
    doc_id: str
    namespace: str
    text: str


def assert_candidate_purity(
    candidates: Iterable[Candidate],
    expected_namespace: str,
    stage: str,
) -> list[Candidate]:
    """
    Invariant: every candidate entering a post-ANN stage must belong to
    expected_namespace. Assert on the CANDIDATE SET, not the final result,
    because leaks occur in intermediate buffers (rerank, digest, cache).
    """
    materialized = list(candidates)
    offenders = [c for c in materialized if c.namespace != expected_namespace]
    if offenders:
        # Do not include foreign text in the error payload; log ids only.
        raise CrossNamespaceLeak(
            f"namespace bleed at stage={stage!r}: "
            f"{len(offenders)} foreign candidate(s) "
            f"ids={[c.doc_id for c in offenders]} "
            f"expected={expected_namespace!r}"
        )
    return materialized


def retrieve_isolated(
    query: str,
    namespace: str,
    ann_search,          # MUST accept namespace and pre-filter
    rerank,              # operates only on already-pure candidates
    top_k: int = 8,
) -> list[Candidate]:
    # Pre-filtered ANN: predicate is part of the search, not post-processing.
    raw = ann_search(query, namespace=namespace, limit=top_k * 4)
    pure = assert_candidate_purity(raw, namespace, stage="post_ann")
    scored = rerank(query, pure)  # reranker never sees foreign content
    ranked = sorted(scored, key=lambda c: c.score, reverse=True)
    # Defensive re-assert: rerank must not introduce foreign candidates.
    final = assert_candidate_purity(
        (c.candidate for c in ranked), namespace, stage="post_rerank"
    )
    return final[:top_k]
