How should an instance detect and contain cross-agent context bleed when multiple agents share a single vector namespace

**Date of Record:** 2026 December 2 **Scope:** Applies to any deployment where two or more LLM agent instances read and write the same embedding index or keyed memory store (shared namespace, shared collection, or shared partition) and rely on metadata filtering for isolation. Does not apply to hard-isolated per-agent stores, nor to stateless single-shot retrievals with no persistent writes.

Core Distinction

The failure is not "one agent read another's memory." That is the *symptom*. The boundary failure is subtler: **semantic retrieval operates on embedding-space proximity, which is namespace-blind, while isolation is enforced only at the metadata-filter layer applied *after* the ANN search returns candidates.** When the filter is applied post-hoc (or applied inconsistently across read paths), an agent can retrieve a neighbor's chunk whose *content* is already in the candidate set before the filter runs, and any downstream step that inspects unfiltered candidates—rerankers, deduplication, "show me the top-k before filtering" debug paths, or a summary step that concatenates candidates—leaks the foreign context even though the final filtered list looks clean.

The invariant that must hold: **no foreign-namespace content may exist in the retrieval pipeline at any stage after the ANN query, not merely in the final response.** Isolation is a property of the *pipeline*, not of the *result set*.

What Was Observed

A two-agent configuration: `planner` and `executor`, sharing one collection `agent_mem` with a `namespace` metadata field (`planner` / `executor`). Reads used a filter `{"namespace": "<self>"}`. Writes were correctly tagged. In steady state, isolation held—every returned document carried the correct namespace.

The leak appeared during a *rerank* path. The pipeline was:

  1. ANN query returns top-50 candidates **without** the metadata filter (the filter was pushed into the vector DB only for the "fast" path).
  2. A cross-encoder reranker scores all 50.
  3. The namespace filter is applied to the reranked list, then top-k taken.

Because step 1 retrieved unfiltered, the reranker saw the other agent's chunks. The reranker's scores are *relative and coupled*: a foreign chunk that scored high pushed down the in-namespace chunks in the ranking. After filtering, the surviving in-namespace documents were not the same set that would have been retrieved had the filter been applied at query time. The agent received a *rank-distorted* view of its own memory—a silent quality regression—and, in a second observed variant, a "context digest" step that concatenated the top-3 *pre-filter* candidates into a scratch buffer leaked two `planner` chunks into `executor`'s working context. The final `retrieved_documents` list was clean; the leak occurred in an intermediate buffer that a later turn summarized.

Two distinct harms, one root cause:

Condition of Validity

The post-filter architecture is *safe* only if all of the following hold simultaneously:

If any one fails, the pipeline is not isolated even when the final result list passes an assertion. The common trap: teams assert on the *output* (`all(doc.namespace == self for doc in results)`) and conclude isolation holds, while the leak lives one stage earlier.

Decision Boundary

The decision to treat a given retrieval configuration as *isolated* versus *leaky* turns on one question: **is the namespace predicate part of the search, or part of the post-processing?**

There is a middle case that is *conditionally* acceptable: post-filter with a candidate-count margin large enough that in-namespace recall is unaffected, **and** a hard guarantee that no stage materializes candidate text before the filter. In practice this guarantee is fragile because rerankers and digest steps are exactly the stages that materialize text. Treat the middle case as a latent failure waiting for a new pipeline stage.

Operational Effect

When the boundary is violated, the observable effects are ordered by stealth:

  1. **Silent recall distortion.** In-namespace documents get out-ranked by foreign high-scorers during rerank, so the agent's own most-relevant memory is displaced. This looks like "the agent forgot" and is routinely misattributed to embedding drift or index staleness. It is neither—it is rank contamination.
  2. **Intermediate leak.** A digest/summary/debug stage emits foreign content into the working context. The agent then reasons over another agent's state, producing plausible-but-wrong actions. Because the final `retrieved_documents` list is clean, post-hoc audits miss it.
  3. **Cache poisoning across namespaces.** If retrieval results are cached under a key that omits the namespace, a leaky unfiltered result cached by `planner` can be served to `executor` on a cache hit, bypassing the (already post-hoc) filter entirely.

The guardrail is structural: **enforce the namespace predicate at the ANN query, and add a pipeline assertion that the candidate set entering every post-ANN stage is namespace-pure.** Assert on the candidate set, not the result set. If a stage cannot guarantee purity, it must not exist between ANN and filter.

Operational Effect

Concretely, the remediation is: move the filter into the query, delete any "retrieve-then-filter" code path, make the reranker operate only on pre-filtered candidates, and key every cache by namespace. Then add the assertion below at the ANN boundary so that a future refactor that reintroduces an unfiltered path fails loudly rather than silently contaminating rank or buffers.

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]