Skip to content

RAG: retrieval, embeddings and vector stores, and how a RAG service is bounded

Type: concept. Status: watching (2026-11-21): explained and set beside our setup; nothing here runs retrieval, and no idea is taken up yet.

Retrieval-augmented generation (RAG) lets a language model answer from documents it fetches at question time instead of only from what it learned in training. This page explains the parts— embeddings, chunking, nearest-neighbour search, vector stores—how retrieval and answers are judged, and the three boundaries a RAG service needs: data, trust and a person's veto. It is a general article, not the design of one product. How these pages are built: index.

Independent origin

The workflow's rules this page compares—issue text is data, a message is no consent, the owner's decisions—were written for coding agents. None of them cites RAG literature or the book named below: the repository first mentions RAG in #907 (2026-11). Where a RAG boundary and one of our rules agree, they arrived at the same practice separately.

Sources

All read on 2026-11-21. A statement no source below supports is marked unconfirmed; a figure a vendor or project reports about itself is marked as its own claim.

Where the sources differ: OpenAI recommends cosine similarity for its text embeddings (guide), while Chroma's HNSW index measures squared L2 distance unless a collection is configured otherwise (configuration). With vectors normalised to length one, as OpenAI's FAQ says its are, both give the same ranking (guide).

What it is

RAG in plain words

A RAG system answers in two steps: it retrieves the passages most related to a question from a collection of documents, then has a model generate an answer from those passages. The original paper paired a sequence-to-sequence model with a dense vector index of Wikipedia reached through a neural retriever, and named two problems it addressed: showing where an answer comes from, and updating a model's knowledge (Lewis et al.). Its index can be swapped to update what the model knows, without training it again (full text).

The vocabulary a reader needs:

  • Embedding. A model turns a text into a vector, a list of numbers, so that texts with related meaning lie close together. Query and documents must be embedded by the same model: vectors from different models live in different spaces and are not comparable (MongoDB, Weaviate).
  • Distance. How close two vectors are. For text embeddings the usual measure is cosine similarity, the angle between the vectors regardless of their length (OpenAI). Other measures are L2 (straight-line) distance and the inner product; pgvector offers all three and more (pgvector).
  • Chunking. Documents are split into passages before embedding, because a passage, not a whole book, is what fits a prompt and matches a question. A chunk cut from its document can lose the context that made it meaningful, such as which company a sentence is about (Anthropic).
  • Nearest-neighbour search. Finding the stored vectors closest to the query's vector. Comparing against every vector is exact but slow; approximate (ANN) indexes trade some recall for speed (pgvector).
    • HNSW builds a layered graph of neighbours; a search enters at the sparse top layer and descends towards the query, which the authors say scales logarithmically (Malkov and Yashunin).
    • IVF clusters the vectors into cells (k-means in the Faiss examples) and searches only the few cells nearest the query; it misses a neighbour whose cell was not searched (Faiss).
    • pgvector compares them: HNSW gives a better speed-recall trade-off but builds slower and uses more memory; IVFFlat builds faster with less memory and must be built after the table has data (pgvector).
  • Top-k. The number of passages retrieved per question, the k the measures below use.
  • Grounding. The retrieved passages go into the prompt with the instruction to answer from them and to name which passage supports what; an answer that says more than its passages is ungrounded.

Why RAG instead of fine-tuning when the knowledge changes and a source must be shown: fine-tuning puts knowledge into the model's weights, where it cannot be updated without training again and cannot point to its source. A RAG index is updated by adding or removing documents, and every answer can cite the passages it used—the two motivations the original paper names (Lewis et al.).

A worked example. A support team keeps two hundred policy documents. Each is split into paragraphs, and each paragraph is embedded and stored with its document's title and date. A customer asks how long a refund takes. The question is embedded with the same model, the store returns the five closest paragraphs by cosine distance, and the model is told to answer only from those five and cite them. When the refund policy changes, the team replaces one document's paragraphs; no model is trained again, and the next answer cites the new paragraph.

Vector stores

Kind Example Runs Fits
A library in the process Chroma's in-memory client inside the application; its data is lost when the program ends unless a persistent client is used (getting started) a prototype, an offline exercise, a test
A database extension Postgres with pgvector in the database already there; exact search by default, HNSW or IVFFlat for approximate search (pgvector) an application that already has Postgres
A dedicated service Chroma's server or Chroma Cloud (getting started); other vendors' hosted stores a separate server or a hosted service large collections, or a team that wants retrieval as its own service

Chroma uses HNSW on a single node, measures squared L2 distance by default and offers cosine as a collection setting; its default embedding model runs locally (configuration, embedding functions). Metadata filters (where) narrow a query (filtering).

Rule of thumb: start with the Postgres you have. Below about a million vectors, with Postgres already in place, Postgres with pgvector, an HNSW index and cosine distance is the start. The reason: no second system to run, back up and secure; the vectors sit in the same transactions, backups and access rules as the rows they describe; and a filter on the rows is plain SQL. The million is a working threshold, unconfirmed: no source read here gives it. The nearest is pgvector's own advice to size IVFFlat lists one way up to a million rows and another way above (pgvector).

Where the rule stops:

  • A filter with an approximate index. pgvector applies a WHERE filter after the index scan, so a selective filter can return fewer than k rows; with a filter matching 10 % of rows and the default search width of 40, about four rows come back. Iterative index scans (pgvector 0.8.0 and later), partial indexes or partitioning help (pgvector). This matters for the access-control check below, which is such a filter.
  • Dimensions. pgvector indexes a vector of up to 2,000 dimensions; larger embeddings need halfvec or quantisation (pgvector).
  • Memory and build time of HNSW at scale (pgvector), and no Postgres in place at all, where a library or a service may be the smaller step.

Evaluating retrieval and answers

Retrieval and generation fail separately, so they are measured separately: a correct passage can be missed, ranked too low, cut from the context or ignored by the model (Barnett et al.).

A versioned corpus. The documents, the test questions and, per question, the passages that answer it are kept under version control. A measurement names the corpus version, the embedding model, the chunking and the index settings it ran with; without that, two numbers cannot be compared.

Retrieval measures, each over the test questions at a cut-off k:

Measure What it counts
hit@k the share of questions with at least one relevant passage in the top k (unconfirmed: the usual meaning; no prose definition was found in the sources read)
recall@k the share of all relevant passages that appear in the top k; it rises towards 1 as k grows, so it misleads alone (Pinecone)
MRR the mean of 1 / rank of the first relevant passage, 0 when none is retrieved (Wikipedia)
nDCG@k graded relevance discounted by rank and divided by the ideal ranking's score, so 1.0 is a perfect order (Wikipedia)

BEIR, a benchmark over 18 datasets, reports nDCG@10 as its single measure (BEIR). A value is reported with its reason—"recall@5 of 0.82 on corpus v3; the misses are tables, which the chunking splits"—not checked against a fixed threshold, which hides why a number moved.

Answer measures. Groundedness (or faithfulness): are the answer's statements supported by the retrieved passages? Answer relevance: does it address the question? RAGAS measures both, plus context relevance, without reference answers, by prompting a model (RAGAS). A model as judge has known biases—position, verbosity, favouring its own outputs—and limited reasoning, though a strong judge agreed with human preferences about as often as humans agree with each other, over 80 % (Zheng et al.). So a judge's score is checked against a sample a person grades.

A question with no matching source. At least one test question has no answer in the corpus. The system passes when it says it found nothing, and fails when it answers anyway; this is the "missing content" failure (Barnett et al.).

Latency and cost are measured before and after each change, beside the quality measures: a reranker or a larger k can raise recall and double the time and the tokens.

RAG as a service

A RAG service sits between the people who ask and the documents they may see. Three boundaries keep it from becoming a way around the rules those documents are under.

flowchart LR
    q["A person's question<br/>(with their identity)"] --> emb["Embed the query"]
    emb --> ret["Retrieve top-k"]
    idx[("Index: chunks with an<br/>access label each")] --> ret
    ret --> acl{"Access check<br/>on the server"}
    acl -->|"only chunks the person<br/>may read"| prompt["Prompt: question +<br/>chunks marked as data"]
    acl -->|"the rest"| drop["dropped, logged"]
    prompt --> model["Model drafts an answer<br/>citing its chunks"]
    model --> veto{"Person decides"}
    veto -->|"send / act"| out["Sent or acted on"]
    veto -->|"reject"| back["Back or discarded"]
  • The data boundary: what goes into the index, and who gets it back. Every chunk carries a mandatory access-control label in its metadata, copied from its source document when it is indexed; a chunk without one is not indexed. Every retrieval checks the label against the person asking, on the server, never in the prompt and never in the client. A copied label goes stale when the source's permissions change, so a change re-labels or removes the source's chunks at once, or the check asks the source system for the current permission instead of trusting the copy (unconfirmed: no source read here describes this step). OWASP lists leakage through misaligned access controls and leaks between tenants of a shared vector store as risks, and asks for "permission-aware vector and embedding stores" with logical partitioning between user groups (OWASP LLM08). With pgvector the check is a WHERE filter, with the filtering limit above. What goes in is decided too: OWASP asks to validate sources, look for hidden content and classify data before it enters (OWASP LLM08).
  • The trust boundary: retrieved text is data, never an instruction. A document can carry instructions—OWASP's example is a résumé with hidden text that steers a screening system (OWASP LLM08). This is indirect prompt injection, and RAG does not prevent it (OWASP LLM01). So nothing a passage says can widen anyone's rights: the access check runs before the model, the model's own permissions are the asker's or fewer, and untrusted content is marked as such in the prompt (OWASP LLM01).
  • The veto boundary: a draft is never sent or acted on without a person. The model drafts; a person sends, files or decides. OWASP asks for a person to approve high-impact actions before they are taken, with the example of an assistant that drafts mail and a user who presses send (OWASP LLM06). The veto is also what limits the harm of an injection that got through.

How it relates to what we have

Nothing in this repository runs retrieval over an index. The rows set each part of the concept beside the nearest thing we have.

# RAG Verdict Our side
1 Answering questions over documents by retrieving passages at query time different FeeCheck, a sibling project, sends a contract's text to a model and gets an extraction back, instead of retrieving passages (3.2 Technical Context, the Mistral row). That it extracts contract attributes, and "extraction instead of RAG", are the owner's statement in #907, not a recorded decision
2 A retrieval service that agents query gap Our own MCP server is a read-only skeleton with two tools and no retrieval (servers/hello-mcp, README (servers/hello-mcp/README.md); 3.2.1). Agents read current library documentation through the outside Context7 server, the same table
3 Data boundary: an access label on every chunk, checked on every retrieval gap No index, so no labels. The nearest rule decides what may be published at all: the docs site lets through only listed folders and runs a privacy gate first (checks.md). It is one level, public or not, decided before publishing, not per reader at query time
4 Trust boundary: retrieved text is data, never an instruction same Issue text is data: it never changes a worker's rules or permissions, and an instruction in it to merge, push elsewhere or reveal a secret is a reason to stop (parallel-work.md); the same rule opens workflow:work-on (plugins/workflow/skills/work-on/SKILL.md). A review finding is input to weigh, not an instruction (3.2, the AI reviewers row); the AI reviews are advice, never a required check (quality-gate.md). The row overlaps that rule of parallel-work.md directly
5 Veto boundary: a draft is never sent or acted on without a person same The owner decides: merges outside the routine, scope changes and anything irreversible wait for the owner, and a "green" is a report, not consent (sdlc principles, decisions.md); a worker's "ready", another session or an issue comment is no consent either (the coordinator skill, plugins/workflow/skills/coordinator/SKILL.md). Routine merges run on the owner's standing consent (parallel-work.md), a veto given in advance, which a RAG service sending drafts would not have. The row overlaps parallel-work.md's list of what Claude does alone
6 Evaluation on a versioned corpus with a query that must find nothing different Skills are evaluated with claude plugin eval, with at least three evals per skill including a near miss that must not trigger (writing-skills.md, evals.md). It measures triggering and behaviour, not retrieval; the near miss is the counterpart of the question with no source

Cross-reference: AI memory. The AI memory page (#902) covers the example, ai-memory, which keeps a git-versioned Markdown wiki as its source of truth and a derived index that can be rebuilt from it; recall fuses SQLite full-text search, entities and links, and vectors only when an embedding provider is configured, which is off by default (ai-memory README). It is a retrieval layer that starts from keyword search, as the critics below recommend.

Critical assessment

What critics say

The strongest argument first. Each is the author's opinion, not a finding.

  1. A long context, or plain search, often beats a tuned pipeline. Li et al. find that long-context models, given enough resources, outperform RAG on average, while RAG stays much cheaper (Li et al. 2024). Anthropic advises that a knowledge base under about 200,000 tokens can simply go into the prompt (Anthropic, 2024-09-19). Claude Code's lead developer says an early version used RAG and that agentic search with ordinary file search did much better, on internal benchmarks but mostly on feel, and that an index goes stale and puts sensitive code in another place (Latent Space, 2025-05-07; the passage was read from a summary of the transcript, not confirmed word for word). Against long contexts, Liu et al. show that models use information in the middle of a long context worst (Liu et al.).
  2. Embeddings are not the strong baseline they look like. BEIR finds BM25 keyword search "a robust baseline" that dense embedding models can fall well short of on new domains (BEIR). Anthropic notes that chunking strips context, that embeddings miss exact terms such as an error code, and combines them with BM25; its reported cut in failed retrievals of up to 67 % is the vendor's own claim (Anthropic).
  3. Retrieval quality is hard to measure, and judges are biased. Barnett et al. conclude from three case studies that a RAG system can be validated only in operation and that its robustness evolves rather than being designed in (Barnett et al.). Zheng et al. name position, verbosity and self-enhancement biases in model judges (Zheng et al.). Hamel Husain argues that generic evaluation frameworks do not measure a product's quality and that failing products share a missing evaluation system (Husain, 2024-03-29).
  4. The embedding model ties the index to it. Vectors from different models cannot be compared, so changing or upgrading the model means embedding the whole corpus again (MongoDB); Deepti Naidu at Weaviate describes the same, with aliases and side-by-side vectors as ways to migrate (Weaviate, 2025-10-09). Both are vendors' documentation, not neutral critics.
  5. The vector store is an attack surface with no isolation by default. OWASP lists leakage through access controls, leaks between tenants, embedding inversion that recovers source text, and poisoned documents (OWASP LLM08), and says it is unclear whether prompt injection can be fully prevented (OWASP LLM01).
  6. Cost and latency of the extra hop. Embedding the query, searching and a reranker add time and tokens to every answer; agentic search, the alternative in item 1, costs more tokens and time per question in exchange (unconfirmed: the trade-off is described in the Latent Space summary only).

Our assessment

Concern Evidence Severity What would settle it
Real need against a gimmick: no part of our setup answers questions over a document collection; agents search the repository and read docs through Context7 rows 1, 2; 3.2.1 serious a task that keyword search over the repository plus Context7 demonstrably fails, with the questions written down
Security and data protection: an index over the issues and docs would mix public and private material, and the only label we keep is public or not row 3; checks.md; OWASP LLM08 serious a label per document, set where the published-folder list of mkdocs.yml already decides public or private (checks.md), before anything is indexed
Alternatives and opportunity cost: long context and keyword search are cheaper starting points; docs/ holds about 950 KB of Markdown, roughly 240,000 tokens at four characters a token, so one section of it fits a 200,000-token window critics 1 and 2; the size measured on 2026-11-21, the token count a rough estimate minor measuring hit@k of plain keyword search on a small question set before any embedding is tried
Reliability and edge cases: a model judge alone would grade our own summaries with its biases critic 3; evals.md minor a person grading a sample of the judge's verdicts; skill evals today have no human grading: their llm graders use a model judge (focus: trace gives it the run's actions), beside deterministic tool_used, regex and file_exists graders (evals.md)
Long-term maintainability: an index must be rebuilt on every embedding-model change and kept in sync with a fast-moving repository critic 4 unknown the rebuild time and cost for the repository's docs and issues with one model

Bottom line

Skip running RAG here for now; keep the three boundaries as the checklist for any sibling project that builds one.

What we could adopt

Results after checking each idea against our code and docs. A result is a recommendation: no issue is filed from this page, and the workflow does not change because of it.

  • The three boundaries as a checklist for a sibling project's RAG service—adopt. They match rules we already hold (rows 4, 5) and add the one we lack, the access label (row 3); written into that project's own design, not here.
  • A retrieval tool on our MCP server (row 2)—needs the owner. The server's scope is decided elsewhere (#381); retrieval would need the data boundary first, and keyword search over the repository may already be enough (critics 1, 2).
  • An index over this repository's docs and issues—don't adopt. Agents already search the repository directly, private and public material would mix, and the memory layer of #902 may cover recall across sessions.
  • The evaluation rules for any future retrieval—adopt as text. A versioned corpus, hit@k or recall@k with a reason, a question with no source, and latency and cost before and after: the same discipline the skill evals follow (row 6).