Module 32 of 52 · Data and AI

Retrieval and RAG pipelines

30 min 5 outcomes Pipeline anatomy + chunking comparison 5 sources cited

By the end of this module you will be able to:

  • Explain retrieval-augmented generation as looking things up rather than memorising them
  • Walk the six pipeline stages and name what travels along each connector
  • Explain how a chunking decision changes which questions have good answers
  • Weigh keeping vector search inside an existing database against running a dedicated store
  • Name the freshness and governance failure modes a retrieval index introduces

Six stages of a RAG pipeline and what passes between them

What travels between the six stages changes at every arrow, passages, vectors, an index, candidates, ranked context, then an answer, so a poor answer can be traced to the stage that produced its payload rather than blamed on the model.

A retrieval pipeline is six stages, and what travels between them changes at every step: passages, vectors, an index, candidates, ranked context, then an answer. Evaluation returns to the chunking, so chunk size is a measured decision rather than a default.

Six stages of a RAG pipeline and what passes between them A serpentine chain in two regions. The top row reads left to right: Split the corpus, Encode meaning, Build the store, joined by arrows labelled passages and vectors. On the right a downward arrow labelled an index folds the chain into the second row, which reads right to left: Fetch candidates, Order by use, Write the answer, joined by arrows labelled candidates and ranked context. The Write the answer card is tinted red to mark the end of the forward chain. Below it an arrow labelled an answer reaches a red output card, Answer plus citations. A dashed arrow leaves the generate card, climbs the left margin and returns to the chunk card, labelled evaluation changes the chunking. RAG PIPELINE · SIX STAGES AND WHAT PASSES BETWEEN THEM 1 CHUNKSplit the corpusDocuments cut intounits that stand alone 2 EMBEDEncode meaningEach chunk becomes avector in one space 3 INDEXBuild the storeVectors written to asearchable structure 4 RETRIEVEFetch candidatesThe query pulls thenearest chunks back 5 RERANKOrder by useA second model scoreswhich chunks help 6 GENERATEWrite the answerThe model answersfrom the passages passages vectors an index candidates ranked context OUTPUTAnswer plus citationsThe only artefact a reader ever sees. Every claim in it should trace backto a retrieved passage, which is why citations belong to the pipeline. an answer evaluation changes the chunking

Chunk size changes what retrieval can find

The red bar marks the same answer text in both lanes, and it straddles three of the nine small units while sitting inside one of the three large ones, so chunk size settles in advance whether that question has a cheap answer.

Small chunks match a query sharply but cut answers in half; large chunks keep the argument together but dilute the match. Chunking is a modelling decision, because it settles in advance which questions the store can answer cheaply.

Chunk size changes what retrieval can find A comparison board with a shared origin. A full width band at the top carries the question Which clause covers late delivery, over the note that the document does not change. Two arrows drop from it, labelled the query meets 9 units and the query meets 3 units. The left lane, Option A Small chunks, draws the document as a strip cut into nine units. The right lane, Option B Large chunks, draws the same strip cut into three. A red bar marks the same answer text under both strips: it straddles three small units but sits inside one large unit. Two chips per lane name the effect on precision and on coherence; a tinted chip is what the cut makes easier, a plain chip what it costs. CHUNK SIZE · WHAT EACH CUT MAKES EASY AND WHAT IT COSTS ONE QUESTION, ONE DOCUMENTWhich clause covers late delivery?The document does not change. Only the way it is cut into units changes.the query meets 9 unitsOPTION ASmall chunksShort units, more of themSAME DOCUMENT, CUT INTO 9 UNITSPrecision rises: the matched unit is mostly answerCoherence falls: an answer that spans units splits the query meets 3 unitsOPTION BLarge chunksLong units, fewer of themSAME DOCUMENT, CUT INTO 3 UNITSPrecision falls: the match is diluted by other textCoherence rises: the surrounding argument stays tinted chip: what this cut makes easierplain chip: what it costsred bar: the answer textChunking is modelling: it decides which questions have cheap answers

Ask a language model on its own what your organisation charges for an out-of-hours callout and it will produce a number. The number will be plausible, formatted like a price, and unconnected to your price list, because the model is completing a pattern rather than consulting a record. Retrieval exists to close that gap. It converts the question from something the model has to remember into something the model has to read, and it moves the accuracy problem out of the model and into a corpus that a data team can actually own.

The shift from memory to lookup sounds like a small implementation detail. It changes who is accountable for a wrong answer, moving that accountability from a model nobody in the organisation trained onto a corpus somebody has to own.

32.1 Retrieval instead of recall

is a pattern in which the model looks information up at answer time instead of relying only on what it absorbed during training. A retriever searches an index for passages relevant to the question, those passages are placed in front of the model, and the model writes its answer from them. Lewis and colleagues introduced the combination in 2020, pairing a generator with a retriever over a dense index of documents for knowledge-intensive tasks.

Compare the two failure profiles, because that is what decides which pattern to use. A model answering from training alone is fast, has no dependency to maintain, and cannot tell you where an answer came from or notice that the policy changed last week. A retrieval system is slower, carries an index that has to be kept current, and can point at the passage it used. In a regulated setting that citation is not a nice presentational touch. It is the difference between an answer that can be checked and an answer that has to be trusted.

The consequence for a data team is that the index becomes a governance surface in its own right. It holds a copy of source material, it is queried by people whose entitlements differ, it goes stale, and it has to be included in deletion work. Each of those four properties is an obligation that arrives with the index and did not exist before it.

Common misconception

Retrieval stops the model hallucinating.

Retrieval changes what the model is guessing about, and reduces fabrication when the right passage is retrieved. It does not prevent the model from misreading a passage, from blending two passages that contradict each other, or from answering confidently when the retriever returned nothing useful. Retrieval quality sets the ceiling on answer quality, and a system with no measurement of retrieval quality has no evidence about either.

The pattern is easy to state and easy to build badly. Naming what travels between each pair of stages is what lets an engineer debug the stage that produced it.

32.2 The pipeline, stage by stage

The anatomy diagram above draws the pipeline as a chain that folds back on itself, and it labels every connector, because what passes along each one is a different kind of object. The six stages, and the payload each one hands on, are as follows.

  1. Chunk. Documents are cut into units that stand alone. What leaves this stage is passages. A passage is the smallest thing retrieval can ever return, so where the cut falls settles what any answer can contain.
  2. Embed. Each passage becomes a in one shared space. What leaves this stage is vectors. Every passage and every future query must go through the same model, or the distances mean nothing.
  3. Index. The vectors are written to a searchable structure. What leaves this stage is an index. This is the artefact with a refresh schedule, a size, a backup and an access story.
  4. Retrieve. The query is embedded and pulls back its nearest passages. What leaves this stage is candidates, usually more of them than the model will be shown.
  5. Rerank. A second model scores which candidates actually help answer this question, rather than which merely sit nearby. What leaves this stage is ranked context. Reranking is the cheapest quality improvement in most pipelines because it fixes the ordering that distance alone got wrong.
  6. Generate. The model writes the answer from the passages it was given. What leaves this stage is an answer, and it is the only artefact in the whole chain that a reader ever sees.

The return path in the diagram matters as much as the forward chain. Evaluation is drawn as an arrow from generation back to chunking, not as a seventh box on the end. Measuring answers is how a team learns that its passages are cut in the wrong place, which makes chunk size an evidence-driven setting rather than a default somebody picked in week one and nobody revisited.

Because only the last artefact is visible, an unmeasured pipeline gives a team no way to tell a generation problem from a retrieval problem. The discipline that helps is to log, for every answer, which passages were retrieved and which were actually shown. That log is the retrieval equivalent of , and it converts arguments about whether the assistant is any good into a question someone can check.

Of those six stages, one is settled before anything is measured and constrains everything after it. The comparison board draws the same document cut two ways.

32.3 Chunking changes the answer

is splitting a document into passages before indexing. The original retrieval-augmented generation work split a Wikipedia dump into disjoint fixed-length passages and embedded each one, and fixed-length splitting remains the common starting point. The size and the boundaries decide what a search can return, because a passage is the smallest unit that can come back.

The comparison board above puts one question across the top and draws the same document twice underneath it, cut into nine small units on the left and three large ones on the right. A red bar marks the same stretch of text in both. On the left that stretch straddles three units, so no single passage contains the whole answer. On the right it sits inside one unit, but that unit also carries a great deal of surrounding material.

Two effects move in opposite directions, and this is the entire trade. Small passages match a query sharply, because a short unit is mostly about one thing and its position in the space is not diluted. They also cut answers in half, and they strip the context that made a sentence interpretable, so the model receives a rule without its exception. Large passages keep an argument together and preserve the qualifying sentence, but their position is an average of everything they contain, so the match is blunter and a specific query can fail to surface the document that answers it.

Because the trade cannot be won, it has to be chosen deliberately against the questions the system will actually be asked. A corpus of short procedural steps answers well with small passages. A corpus of contracts, where the meaning of a clause depends on definitions three paragraphs earlier, does not. Cutting on structural boundaries such as sections and clauses rather than on a character count usually beats both extremes, and carrying a small overlap between neighbouring passages recovers some of what a hard boundary destroys. Whichever route is taken, every passage should keep the identifier of its source document and its position within it, because that is what makes the answer traceable and the passage deletable.

Common misconception

Chunk size is a tuning parameter, so we will start at 512 tokens and optimise later.

Chunking is a modelling decision wearing engineering clothes. It settles in advance which questions have cheap answers and which have none, and the same document chunked two ways gives an assistant two different answers to the same question. Optimising later means re-chunking, re-embedding and rebuilding the index, so the decision is worth an hour with the actual question set before the first build rather than after it.

Chunking settles what can be retrieved. The next question is where those vectors are stored, and the honest answer is less exotic than the vocabulary suggests.

32.4 Where vector search actually lives

means finding the stored vectors nearest to a query vector. Done exactly, it compares the query against every stored vector and returns the true nearest neighbours. Done approximately, it consults an index and trades some recall for speed. The pgvector documentation is explicit that its default behaviour is exact nearest neighbour search with perfect recall, and that adding an index changes the results you get back.

That single sentence carries a lesson many teams learn late. Approximate search is a quality setting, not only a performance setting. If nobody measures recall against exact results, an index tuned for speed can silently drop the passage that held the answer, and the symptom presents as the model being unhelpful. Measure recall against exact search before deciding the index is good enough.

On where it lives, the vocabulary implies a separate product more often than the architecture requires one. A is a store that holds embeddings and answers nearest-neighbour queries, and that capability is available as an extension to databases an organisation may already run: pgvector adds vector types, operators and indexes to PostgreSQL. Whichever way the choice goes, decide it on governance before benchmarks. Keeping vectors alongside the relational data keeps retrieval inside the access controls, backups, monitoring and lineage the organisation already operates, and it lets a query filter by tenant, classification or date in the same statement that ranks by similarity. A dedicated store earns its place where scale or workload justifies separate operational machinery, and the cost of that choice is a second system with its own permissions and its own backup story.

One more architectural point saves a great many disappointing demonstrations. runs keyword search and vector search over the same content and combines the two result lists, commonly with reciprocal rank fusion or by reranking the merged candidates. Keyword search catches exact names, product codes and rare words; vector search catches paraphrase. A part number or a surname is the query type vector search alone is weakest on, because a rare token carries little of the contextual signal that positioned it, and it is exactly the query an audience reaches for when invited to try the system. The keyword half is what recovers it. The pgvector documentation says to use the extension together with PostgreSQL full-text search for hybrid search, and points at reciprocal rank fusion or a cross-encoder to combine the results.

An index is a governed copy of source material. Copies age, copies escape their access rules, and copies survive deletion, which gives retrieval three failure modes of its own.

32.5 Freshness and governance failure modes

The first family of failures is freshness. An index is a snapshot, and a snapshot is wrong the moment the source changes. Three variants recur. Stale content, where the policy was updated and the index still holds the previous wording, so the assistant cites an obsolete rule with a confident tone. Orphaned content, where a document was withdrawn at source and its passages remain indexed, so the system answers from material the organisation has formally retracted. And partial refresh, where an incremental job fails quietly and half the corpus is a week older than the other half, which produces answers that contradict each other depending on which passage wins.

None of that is visible from the answer, so it has to be instrumented. Treat the index as a dataset and apply to it: watch the age of the oldest passage, the count of indexed documents against the count at source, and the failure rate of the refresh job. Carry the source document identifier and its last-modified date on every passage so an answer can state how old its evidence is. The Data on the Web Best Practices puts the underlying obligation plainly.

Provide complete information about the origins of the data and any changes you have made.

Data on the Web Best Practices (W3C Recommendation) - Best Practice 5, Data provenance

Written for publishing data on the web, and directly applicable to a retrieval corpus, which is a republication of somebody else's material in a new form. A passage stripped of its origin and its modification history cannot be checked, cannot be aged out on evidence, and cannot be removed reliably when the source is withdrawn. The same document also recommends indicating a version number or date for each dataset, which is the practice that lets an answer say how current it is.

The second family is access. An index flattens a corpus into passages, and passages lose the folder permissions, system boundaries and record-level restrictions that governed the originals. If everything is embedded into one store and the retriever queries it under a single service account, the assistant becomes a route around every access control the organisation set. The fix is to keep entitlement metadata on each passage and filter by the asking user before ranking, which is one of the reasons for keeping vectors where already applies. The related discipline is to decide what should not be indexed at all: special category records, material under legal restriction, and anything whose lawful basis does not extend to this use.

The third family is deletion. An index is a copy, so it falls within the same obligations as every other copy. Where a person exercises the , or where a expires, removing the source record while leaving its passages in the vector store leaves personal data in a live system that answers questions about it. Deleting a passage is easy to do and easy to forget, so it belongs in the deletion runbook explicitly, alongside backups and warehouse extracts, with evidence that it happened.

Underneath all three sits a definitional problem that the semantic layer module takes up in full. An assistant that reaches documents but not the agreed meaning of a measure will retrieve two passages that use active customer differently and reconcile them by guessing. Retrieval brings the words. It does not bring the agreement about what the words denote.

Common misconception

We deleted the customer record from the source system, so the assistant can no longer surface it.

The vector store holds an independent copy of the text, and it will keep answering from that copy until the passages are removed. Deletion work has to enumerate every location the data reached, and a retrieval index is now one of those locations alongside backups, warehouse extracts and reporting copies. Build the passage deletion into the same job that deletes the record, and keep the evidence.

32.6 Check your understanding

An assistant over a contract library answers well on general questions but repeatedly gives a rule without the exception that qualifies it three paragraphs earlier. Passages were cut at a fixed character count. What is the most likely cause?

A team adds an approximate index to speed up retrieval. Latency improves and nobody changes anything else, but answer quality is judged worse. What should be checked?

A customer exercises the right to erasure. The record is removed from the CRM and from the warehouse, but the support assistant still answers questions about that customer accurately. What has been missed?

Core distinctions

  • Retrieval-augmented generation makes the model read rather than remember, which moves accountability for a wrong answer from the model to a corpus a data team owns and can cite.
  • The pipeline is six stages and the payload changes at every step: passages, vectors, an index, candidates, ranked context, then an answer. Evaluation is a return path to chunking, not a stage bolted on the end.
  • Chunking is a modelling decision. Small passages match sharply but split answers; large passages hold an argument together but dilute the match. Cut on structure, keep the source identifier on every passage, and choose against the real question set.
  • Vector search can live inside a database the organisation already runs, for example through the pgvector extension for PostgreSQL, which keeps retrieval inside existing access controls; a dedicated store is a second system to govern. Approximate indexes trade recall for speed, so measure recall against exact search, and add keyword search alongside for codes and names.
  • An index is a copy, so it ages, it escapes source permissions, and it survives deletion. Instrument its freshness, filter by the asking user before ranking, and put passage deletion in the erasure and retention runbooks.

Standards and sources cited in this module

  1. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (Lewis et al., 2020)

    Model architecture and knowledge source

    The paper that introduced the pattern, pairing a generator with a retriever over a dense passage index and describing the fixed-length passage split.

  2. pgvector, vector similarity search for PostgreSQL

    Indexing, recall and hybrid search

    Primary source for exact search giving perfect recall, approximate indexes trading recall for speed, and combining vector with full-text search using reciprocal rank fusion or a cross-encoder.

  3. Data on the Web Best Practices (W3C Recommendation)

    Best Practice 5 (Data provenance) and Best Practice 7 (Version indicator)

    Sets the provenance and versioning expectations that a retrieval corpus inherits, because an index republishes source material in a new form.

  4. Guide to the UK GDPR (ICO)

    Storage limitation and the right to erasure

    The regulator guidance that makes a retrieval index part of deletion and retention work, since it is another copy of personal data held in a live system.

  5. Model Context Protocol Specification

    Connecting AI applications to data sources and tools

    Relevant where retrieval is one of several connected capabilities, and useful for seeing why access control on the connected system decides whether an answer is safe.

Module 32 of 52 · Data and AI