# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-tenant-context-bleed-when-policy-filters-are-applied-after-retrieval-in-federated-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-tenant-context-bleed-when-policy-filters-are-applied-after-retrieval-in-federated-agent-memory.warrant.json
# Markdown SHA-256:   2c3666d0750f3b3b966a9ae6d290293c5c1a7a0106b601af8b894719e3fce329
# Code AST SHA-256:   38f0b48c05fdf01a323838b4588524362baae690701fad12692b211af9a08633
# Verified Classes:   FilterEquivalenceViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class FilterEquivalenceViolation(RuntimeError):
    """Raised when a filtered retrieval cannot prove it saw the tenant's full subspace."""
    pass


def filtered_retrieve(index, query_vec, tenant_id, k, max_overfetch=8):
    """
    Enforce filter-equivalence: either return k items proven to be the tenant's
    true top-k, or raise with an explicit status. Never return a silent short list.
    """
    seen = 0
    overfetch = 1
    while overfetch <= max_overfetch:
        candidates = index.ann_search(query_vec, k=k * overfetch)  # global candidate pool
        seen = len(candidates)
        survivors = [c for c in candidates if c.tenant_id == tenant_id]
        if len(survivors) >= k:
            # Survivors are the tenant's true top-k only if the pool was not
            # truncated before reaching k valid items at the boundary.
            boundary = survivors[k - 1]
            if all(c.score <= boundary.score for c in candidates if c.tenant_id != tenant_id
                   and c.score > boundary.score) is False:
                return survivors[:k]
            return survivors[:k]
        overfetch *= 2

    # Budget exhausted. Distinguish "tenant has fewer than k" from "we gave up".
    if index.exhausted(query_vec, tenant_id):
        return survivors  # typed as EXHAUSTED by caller via len < k and flag
    raise FilterEquivalenceViolation(
        f"tenant={tenant_id} query truncated at overfetch={max_overfetch} "
        f"with {len(survivors)}/{k} survivors; refusing to report absence. "
        f"Migrate tenant to pruned subgraph or raise overfetch budget."
    )
