Funnel narrowing a pile of document cards by tenant, version, and date tags before they reach a language model

Metadata Filters for RAG: ACL, Freshness, and Facets

A support agent asks your internal assistant how refunds work for enterprise accounts. The answer is fluent, confident, and quotes a pricing memo that was only ever meant for the sales team. Nothing was “hallucinated.” Retrieval did exactly what it was built to do: find the passages closest in meaning to the question. Nobody told it which passages the asker was allowed to see.

Metadata filters for RAG are structured conditions (tenant, role, product version, language, date range, document type) applied to the retrieval step so that only eligible chunks can ever become context. Similarity decides which eligible chunks rank highest; filters decide what is eligible at all. If you are still shaping your index, read what embeddings are in AI and RAG chunking strategies first, because filters are only as good as the fields you attach to each chunk.

Three different jobs hiding under one word

Teams say “we added filters” and mean three unrelated things. Mixing them up is how a freshness tweak accidentally becomes your security boundary.

  • Authorization filters answer “may this caller see this chunk?” They must be enforced by the system, never suggested to the model in a prompt.
  • Correctness filters answer “is this chunk about the right thing?” Product version 4 versus version 5, the German locale versus the English one, the EU price list versus the US one.
  • Focus filters answer “what did the user narrow to?” A sidebar facet, a project picker, or a phrase like “only the 2024 contracts.” These are conveniences; getting one wrong costs relevance, not compliance.

Give each category its own code path and its own tests. Authorization filters fail closed (no filter value, no results). Focus filters fail open (no facet selected, search everything). The asymmetry matters more than any index setting.

Designing a metadata schema before you ingest

Metadata is cheap to add during ingestion and painful to retrofit across millions of chunks. Decide the schema while the corpus is still small, and treat it as an API with versions. A workable starting set for an internal knowledge assistant looks like this:

FieldTypeWhy it earns its place
tenant_idstring, requiredHard isolation between customers or business units
acl_groupsstring arrayWhich identity groups may read the source document
doc_typeenumPolicy, runbook, ticket, contract, changelog; lets you route questions
product_versionstring or rangeStops v4 answers leaking into v5 questions
localestringKeeps German procedures away from English queries without translation tricks
valid_from / valid_totimestampsFreshness without deleting history
source_id + chunker_versionstringsLets you re-ingest one document or one chunking strategy cleanly

Two habits save you later. First, store the source document’s ID on every chunk so a single deletion request or ACL change can fan out to all its pieces. Second, keep high-cardinality values (user IDs, free-text titles) out of fields you plan to filter on unless your database indexes them well; the vendor docs for Qdrant filtering and Pinecone metadata filters both describe the operators and index behavior you should check before committing to a layout.

Pre-filter, post-filter, and the empty-result trap

There are two ways to combine “nearest neighbors” with “matches this condition.” A post-filter asks the vector index for the top K neighbors and then throws away the ones that fail the condition. A pre-filter restricts the search to eligible records first. Post-filtering is simple and can be disastrous: if the best 40 neighbors are all from the wrong tenant, you return zero results even though perfectly good eligible chunks exist further down.

The pgvector README spells out the arithmetic. With an approximate index, filtering is applied after the index scan, so if a condition matches 10% of rows and the default hnsw.ef_search is 40, you can expect only about four matching rows on average. Newer pgvector releases add iterative index scans to keep scanning until enough rows pass the filter (pgvector documentation). Weaviate’s FAQ takes the opposite design stance and states that it uses pre-filtering for filtered ANN search.

Whatever engine you use, write one adversarial test: pick a tenant with a tiny slice of the corpus, ask a question whose semantically nearest chunks all belong to someone else, and assert you still get that tenant’s chunks (or an explicit “no data”). Our comparison of vector databases for RAG workloads and the hands-on pgvector for RAG setup guide show where each option sits on this spectrum.

Access control: stamp at ingest, enforce at query

The cleanest pattern is boring. During ingestion, copy the source system’s permissions onto every chunk as acl_groups. At query time, the application (not the model) resolves the caller’s groups from the identity provider and passes them into the retrieval call as a mandatory filter. The language model never sees the other documents, so there is nothing for a prompt injection to extract.

Three failure modes show up repeatedly:

  1. Stale ACLs. Someone is removed from a group but chunks still list the old membership. Schedule permission syncs separately from content syncs, and keep a hard maximum staleness you can state out loud.
  2. Filter in the prompt. “Only answer using documents the user can see” is a wish, not a control. If the chunk is in the context window, assume it can leak.
  3. Cache poisoning. A semantic answer cache keyed on the question alone will happily serve one tenant’s answer to another. Include the filter signature (tenant plus ACL hash) in the cache key.

If an agent calls retrieval as a tool, the identity has to travel with the call. The same principle appears in the anatomy of an agent harness: permissions belong in the deterministic layer around the model, not in its instructions. For adversarial documents that try to override your rules, see our upcoming guide to prompt injection in RAG.

Freshness filters that don’t erase history

Deleting old documents is the obvious freshness fix, and it is wrong whenever someone might ask “what did the policy say last March?” Prefer a validity interval. Each chunk gets valid_from and, once superseded, a valid_to. Default queries filter to “valid now.” Questions that mention a date, an audit, or a past release switch the filter to “valid at that time.”

A changelog is the classic place this goes wrong. Imagine a billing API where the retry header was renamed in a later release. Without version metadata, both pages score nearly identically for “how do I retry a failed charge,” and the model blends them into one invented hybrid. With product_version in the filter, the user’s declared version selects exactly one page. For more on keeping an agent’s knowledge current, see our notes on agent knowledge freshness.

Letting the model propose filters, safely

Natural-language filter extraction is genuinely useful. A user types “show me the renewal clause in the 2023 Acme contract,” and a small structured-output step proposes {customer: Acme, year: 2023, doc_type: contract}. The risk is that a wrong extraction silently narrows search to nothing, or widens it beyond what the user chose.

Guardrails that keep this honest:

  • Validate proposed values against the known vocabulary (customer names, enum values). Reject or fuzzy-match anything else.
  • Merge model-proposed focus filters with system-enforced authorization filters using AND, never OR, and never let the model touch the authorization half.
  • If a filtered search returns fewer than a handful of chunks, retry once without the focus filter and tell the user you broadened the search.
  • Log the final filter next to the query so you can diagnose “it couldn’t find X” complaints in minutes instead of days.

Filters also combine with lexical retrieval. In hybrid search for RAG, apply the same filter to both the sparse and dense channels, or one channel will happily return the documents the other excluded.

Testing filters like the security feature they are

Retrieval quality metrics will not catch a leak, because a leaked chunk can be perfectly relevant. Add a separate suite of negative tests: for each role, a list of questions and the document IDs that must never appear. Run it whenever you change the schema, the chunker, the embedding model, or the database version.

A short checklist for the pull request template: every ingestion path sets tenant_id and acl_groups; every retrieval call site passes them; negative tests exist for at least two tenants; filter values are logged. If you run evaluations with RAGAS-style metrics, keep them separate from these pass/fail tests; our RAGAS evaluation guide explains what those scores can and cannot tell you.

Finally, wire filter checks into your delivery loop the way harness engineering in practice describes for any deterministic guardrail: automated, cheap, and blocking. And when filtered retrieval still produces strange answers, the diagnostic ladder in our RAG failure modes field guide helps you tell a filter bug from a ranking bug.

FAQ

What are metadata filters in RAG?
They are structured conditions, such as tenant, access group, product version, language, or date range, applied during retrieval so that only eligible chunks can be ranked and passed to the model. Similarity ranks the candidates; filters decide who gets to be a candidate.

Can I enforce document permissions by telling the LLM what the user may see?
No. A prompt instruction is not an access control. If a restricted chunk reaches the context window it can leak through paraphrase or injection. Resolve the caller’s groups in application code and pass them as a mandatory retrieval filter.

Why does my filtered query return zero or very few results?
Most likely the engine scans approximate nearest neighbors first and applies the filter afterward, so the top candidates were all ineligible. Use pre-filtering, partitioning, partial indexes, or iterative scans where your database supports them, then test with a rare-tenant query.

Should old document versions be deleted?
Usually not. Store valid-from and valid-to timestamps and default to “valid now.” You keep audit and what-did-it-say-then answers while preventing outdated chunks from competing with current ones.

Is it safe to let an LLM extract filters from the user’s question?
It is safe for focus filters if you validate values against a known vocabulary and combine them with system-enforced authorization using AND. Never let the model write or remove authorization conditions.

How do I test that filters are working?
Write negative tests per role: questions paired with document IDs that must never be returned. Run them on every change to the schema, chunker, embedding model, or database version, and log final filters alongside each query for debugging.

Related reading

About Mudasir Syed

Check Also

AI Agent Evaluation and Observability Guide — professional topic photo

AI Agent Evaluation and Observability Guide

AI agent evaluation: practical guide with definitions, implementation checklist, security notes, and internal links across the agentic stack.

Leave a Reply