Metadata Filtering
Restricting retrieval by tenant, permission, recency, or type is done with metadata filters — and where the filter runs decides both correctness and recall.
Builds on Prompt & Context Engineering and APIs & Async Programming in the Agentic AI roadmap.
Key points
- Filters are predicates over chunk metadata; store every field you will ever filter on.
- Post-filtering fails on selective filters; pre-filtering fights graph indexes — measure recall with the real filter.
- Tenant isolation is enforced in the query and derived from the session, never left to the model.
- ACLs are mirrored onto chunks and synced; fail closed when permissions cannot be resolved.
- Apply the same filters to every retriever in a hybrid setup.
- Hard filters for correctness and security; soft boosts for recency and relevance.
Filters are part of retrieval, not a decoration
A retriever that returns the 5 most similar chunks in the whole corpus is rarely what you want. The real query is "the 5 most similar chunks *among those this user is allowed to see, in this workspace, from the current version of the docs*". Those constraints are expressed as predicates over chunk metadata: tenant_id = "acme", acl && user.groups, updated_at > now() - 90d, doc_type IN ("policy", "runbook").
This is why Ingestion: Parsing & Chunking insists on rich metadata: every filter you will ever need must be a field on the chunk. Filtering by something you did not store means re-ingesting.
Pre-filtering vs post-filtering
Post-filtering runs the ANN search first (top-k across everything), then drops results that fail the predicate. It is simple and fast, and it is wrong whenever the filter is selective: if tenant acme owns 1% of chunks and you fetch top-20, on average 0.2 of them belong to acme — the user gets zero or one result even though acme has hundreds of relevant chunks. Over-fetching (top-2000 then filter) papers over this at the cost of latency and still fails for very small tenants.
Pre-filtering applies the predicate first and searches nearest neighbours only within the surviving set. This is exact with respect to the filter but interacts badly with graph indexes: HNSW navigates neighbour links, and if most neighbours are filtered out the greedy walk gets stuck and recall collapses. Stores handle this differently — some fall back to brute force when the filter is selective, some build per-partition indexes, some integrate the filter into the graph traversal. In pgvector, a partial index or a partitioned table per tenant sidesteps the problem entirely.
The practical rule: know your filter selectivity. For low-selectivity filters (exclude 10% of chunks) post-filtering with modest over-fetch is fine. For high-selectivity filters (a tenant, a single document) use pre-filtering, partitioning, or a separate index per partition. Always test recall with the real filter, because unfiltered benchmark numbers tell you nothing.
Tenant isolation
In a multi-tenant product, a retrieval that returns another tenant's chunk is a data breach, full stop. Tenant isolation must be enforced *in the retrieval query* — never by asking the LLM to ignore passages it should not have seen. The filter must be applied on every retriever in a hybrid setup, on every index, and it must be impossible to omit: derive tenant_id from the authenticated session, not from the request body, and make the retriever function require it as a non-optional argument.
Stronger isolation options, in increasing cost: a mandatory WHERE tenant_id = $1 plus row-level security in the database; a separate index or partition per tenant; a separate database per tenant for regulated customers. Row-level security is attractive because it enforces the filter even when an engineer forgets it in a new code path.
Access control at retrieval time
Within a tenant, documents have permissions: HR docs for HR, a customer's contract for its account team. Model this as an acl array on each chunk (group ids or principal ids, mirrored from the source system) and filter with acl overlaps user.groups. Sync the ACLs when the source changes, because a document made private yesterday must stop being retrievable today — and remember that the index is a *copy* of the data with its own permissions to maintain.
Two subtleties. First, the LLM's answer can leak content even when a chunk is technically permitted, if the chunk itself quotes something sensitive — ACLs on chunks are only as good as ACLs on the source. Second, never fall back to "no filter" when the user's groups cannot be resolved; fail closed and return nothing.
1def retrieve(query: str, *, tenant_id: str, groups: list[str], k: int = 20,2 since: datetime | None = None) -> list[Chunk]:3 if not tenant_id or not groups:4 return [] # fail closed, never "no filter"5 where = ["tenant_id = %(t)s", "acl && %(g)s"]6 params = {"t": tenant_id, "g": groups, "v": embed(query), "k": k}7 if since is not None:8 where.append("updated_at >= %(since)s")9 params["since"] = since10 sql = f"""11 SELECT id, doc_id, text, updated_at, 1 - (embedding <=> %(v)s) AS score12 FROM chunks WHERE {' AND '.join(where)}13 ORDER BY embedding <=> %(v)s LIMIT %(k)s"""14 return db.query(sql, params)Recency and other soft filters
Not every constraint is a hard predicate. "Prefer recent docs" should usually be a boost, not a cutoff: multiply the similarity score by a decay such as 0.5 ** (age_days / 180), or add a recency term during Reranking. A hard updated_at > 1 year cutoff hides the one runbook nobody has touched because it still works.
Hard filters are for correctness (tenant, ACL, document version, language); soft boosts are for relevance (recency, popularity, doc type preference). Keep the distinction explicit in code so a relevance tweak can never weaken a security guarantee.
When to use — and when not to
- Any multi-tenant deployment.
- Corpora with per-document permissions.
- Versioned docs where only the current version should answer.
- Scoping queries to a doc type, product, or language.
- Recency as a hard cutoff — use a boost unless staleness is a correctness issue.
- Filtering by something not stored on the chunk — re-ingest first.
- Relying on prompt instructions to hide content the retriever already returned.
Failure modes
Reference · showHide
- Post-filtering returns empty results for small tenants.
- HNSW recall collapses under a selective pre-filter and nobody measured it.
- Filter present on the dense retriever, missing on BM25; cross-tenant leak.
- ACL changes in the source system never reach the index.
- Permission lookup fails and the code falls back to unfiltered retrieval.
Check yourself
Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.
How do you apply least privilege to an agent's tools, and why is it harder than for a normal service?
Show a strong answerHide the answer
Least privilege means the agent can only do what this task for this user requires. Mechanisms: expose a per-task subset of tools rather than the whole catalogue; back tools with credentials scoped to the user's own permissions (the agent acts as the user, not as an admin); split read and write tools so read-only tasks never carry write capability; and constrain arguments (tenant id injected by the tool handler, not supplied by the model). See Tool Permissions and Least Privilege and Permissions, Authentication and Authorisation.
It is harder than for a service because the caller is a model that decides at runtime what to call with what arguments, influenced by content it reads. A service calls the database the way its code says; an agent may call
deletebecause a document told it to. So the permission boundary must be enforced in the tool layer and the backend, never by the prompt, and should assume adversarial arguments.Operationally: credentials stay in the tool server, short-lived tokens per run, audit logs of every tool call with arguments, and alerts on calls outside the task's expected set.
Full interview question, with follow-ups and red flags →When should you use hybrid (dense + sparse) retrieval instead of pure vector search?
Show a strong answerHide the answer
Dense retrieval matches meaning: paraphrases, synonyms, conceptual questions. It is weak on exact tokens the embedding model treats as noise: product codes, error strings, identifiers, names, version numbers, rare technical terms. Sparse retrieval (BM25) is the opposite. Hybrid runs both and fuses the ranked lists, typically with reciprocal rank fusion, then often reranks the merged top-N with a cross-encoder. See Dense, Sparse & Hybrid Retrieval and Reranking.
So I use hybrid when the corpus or queries contain exact-match signals: technical docs, logs, legal citations, product catalogs, anything with SKUs or error codes. I stay with dense only when queries are conversational and the corpus is prose, and I add BM25 when evals show recall failures on identifier-style queries.
Hybrid costs a second index, a fusion step, and tuning of the weighting; it is not free. The decision comes from a golden set with a mix of query types and recall@k per type.
Full interview question, with follow-ups and red flags →The agent needs write access for 1 in 50 tasks. How do you handle it?
Show a strong answerHide the answer
Default read-only; escalate to a write-capable run with a gate when the task type requires it; never grant by default.
Full interview question, with follow-ups and red flags →