# RAG is not a single vector query: unpacking two pipelines

Date: 2026-07-02
Category: Technology
Tags: RAG, Retrieval, Architecture
Summary: Split retrieval tools into two pipelines—offline indexing and online retrieval—and examine latency, version consistency, and fault attribution hop by hop to explain why you shouldn't rush to switch models when an answer is wrong

The previous post ended with a question: when "retrieval knowledge base" is made into a tool, what does it actually look like inside? I've seen many people write this tool as a single vector query, stuff the results straight into the context, and then complain that RAG performs poorly. In a real system, behind this one tool are two pipelines that can be deployed independently, evolved independently, and even maintained by different teams.

The symptoms when either pipeline goes wrong look very similar: what the user sees is "a wrong answer." One might be wrong because a new document was never indexed three days ago; the other might be wrong because tonight's query rewrite stripped out the keywords. Without separating them, you can't attribute the failure.

> Post 4/15 of this series · [Previous: Tool Calling Protocol: From Schema to Idempotency](/2025/09/23/agent-tool-calling-protocol-and-idempotency/) · [Next: Chunking Is Not About Splitting Characters, It's About Splitting Semantic Boundaries](/2025/09/16/rag-chunking-structure-aware-splitting/)

## First distinguish missing facts from missing behavior

Knowledge in a model is parametric: compressed into weights during training, expensive to update, and with no provenance. RAG introduces non-parametric knowledge: external corpora can be added or removed at any time, hits can carry document IDs and positions, and answers are traceable. This difference determines that some scenarios can basically only use retrieval.

Internal tickets, a price list changed just yesterday, current inventory — none of these can exist in model weights. For customer service scripts, compliance Q&A, and medical or financial scenarios, "which document and which section the answer comes from" is often more important than the answer itself. Then there are long-tail facts: low-frequency proper nouns, error codes, internal codenames. Parametric memory is unreliable for these to begin with, and stuffing them into the prompt is too expensive.

But retrieval cannot solve "the model can't reason." Ask it to compute year-over-year growth from ten financial reports: if it recalls ten passages of raw text and the model is bad at arithmetic, the answer will still be wrong. Fine-tuning is good at changing behavior distributions — output format, domain tone, stable task patterns; RAG is good at injecting facts. The two are not mutually exclusive, but I've seen too many cases of "performance is bad, let's fine-tune," only to find the problem was that tables were flattened into a blob of messy text during document parsing.

My judgment is simple: if the error manifests as "doesn't know a certain fact," check the retrieval pipeline; if it manifests as "knows the material but answers in a non-compliant way," check the prompt, the model, and the generation constraints.

## Offline pipeline: the index is a versioned data product

```mermaid
flowchart LR
  subgraph OFF["离线：索引是一份有版本的数据产品"]
    direction LR
    A[数据源] --> B[采集]
    B --> C[解析清洗]
    C --> D[切分]
    D --> E[元数据挂载]
    E --> F[嵌入]
    F --> G[索引]
    G --> H[发布快照]
  end
  H --> V[active_version]
```

The defining trait of the offline pipeline is that "mistakes aren't discovered immediately," so every step must leave behind reproducible intermediate artifacts. My approach is to store the cleaned documents, the split chunks, and the final index as separate snapshots, tied together by the same `corpus_version`. That way, when a recall anomaly occurs, you can pull up the chunk snapshot directly and determine whether it's a splitting problem or a vector problem, without re-crawling the source site.

Parsing and cleaning are easily underestimated. PDF two-column layouts, cross-page tables, headers and footers; HTML navigation and related-reading blocks; Markdown table-of-contents blocks — mixed into the corpus, these become high-similarity noise. When processing a personal blog corpus, after cleaning out a substantial proportion of non-body URLs, the change in retrieval quality was far more noticeable than swapping the embedding model.

Metadata attachment determines whether filtering and freshness handling are possible later. At minimum you need `doc_id`, `source_uri`, `section_path`, `published_at` / `updated_at`, permission tags (`acl`), `corpus_version`. Metadata is best attached to each chunk at split time, rather than joining against a document table at query time; filtering must take effect at the recall stage, because post-hoc filtering silently shrinks `top_k`.

Incremental updates and consistency also need to be thought through in advance. New documents go through incremental writes; deletions and updates must rely on precise invalidation via `doc_id`. I once hit a pitfall: after a document was revised, a new `doc_id` was generated from the content hash, the old chunks were not deleted, and retrieval recalled both old and new versions together, leading the model to give self-contradictory conclusions. Now `doc_id` always uses a stable identifier, and content changes only bump `revision`.

Full rebuilds are equally unavoidable. Changing the embedding model, altering the splitting strategy, or adjusting the tokenizer all require rebuilding the index; old and new vectors must not be mixed in the same index. Therefore, before launch, reserve the ability to run dual indexes in parallel: the new index runs evaluation in a shadow environment, and after passing, `active_version` is switched atomically.

## Online pipeline: every hop loses information

```mermaid
flowchart LR
  subgraph ON["在线：每一跳都在损失信息"]
    direction LR
    Q[query] --> N[归一化与改写]
    N --> R[多路召回]
    R --> F[融合与重排]
    F --> C[上下文构造]
    C --> G[生成]
    G --> P[后置校验]
  end
```

The most common design mistake in this pipeline is taking top_k at every hop. The first hop recalls 20, fusion keeps 10, reranking keeps 5, and construction cuts it to 3 — if the true answer ranked 21st in the first hop, none of the later stages has a chance. My default configuration is for recall depth to be far greater than final context capacity: 50 to 100 per route, 30 to 50 into reranking after fusion, and only 5 to 10 passages sent in the end. Wide in, narrow out — push precision decisions as late as possible, because later stages are more expensive but also more accurate.

Post-generation validation is often omitted, but it's the only place that can catch "citation hallucination." After generation, check whether the `chunk_id` cited in the answer actually appear in the context that was sent in; if not, regenerate, or degrade directly to "cannot confirm." This check is cheap but pays off enormously.

## How to allocate the latency budget

For a user-facing RAG request, the end-to-end budget usually needs to stay within 1 to 3 seconds (with the first token earlier). I split it roughly like this:

| Stage | Typical magnitude | Levers |
| --- | --- | --- |
| Query rewrite (if using a model) | 100–400ms | Small model, cacheable, skippable |
| Multi-route recall | 20–80ms | Concurrent execution, ANN parameters |
| Reranking | 50–300ms | Candidate count, batch, model size |
| Context construction | <10ms | Pure code |
| First generated token | from 300ms | Context length, model, streaming |

The biggest variable here is actually generation, not retrieval. Every extra 1000 tokens stuffed into the context raises first-token latency and cost, so the context compression discussed in post 10 is not just a quality issue but also a latency and cost issue.

If query rewriting also calls an LLM, the pipeline has two model calls, and tail latency will look ugly. My current default is not to rewrite, and to trigger it only when a clear signal is detected: the query is too short (fewer than 4 characters), contains multiple parallel sub-questions, or first-round recall confidence is uniformly low. Unconditional rewriting often "optimizes" the user's precisely entered error code into natural language, washing away the only literal clue that could have matched.

## Failure attribution: first see which hop the symptom falls on

When an answer is wrong, don't rush to swap the model — locate it by symptom first:

| Symptom | High-probability stage | Verification method |
| --- | --- | --- |
| Relevant document clearly exists but doesn't make the top 20 | Recall / chunking / embedding | Inspect the chunk snapshot directly: is the target text in the store, and how was it split? |
| Correct chunk retrieved but the answer doesn't use it | Context construction / generation | Print the actual prompt sent to the model; check chunk position and order |
| Exact IDs and error codes can't be found | Tokenization and representation of pure vectors | Try a pure lexical search once and compare the two result sets |
| Old and new conclusions contradict each other | Offline consistency / metadata | Check whether `doc_id` are duplicated and whether freshness fields are missing |
| Questions absent from the corpus get confident answers | Missing refusal policy | Test with a "no-answer" question set; add a threshold or two-stage judgment |
| Paraphrasing breaks retrieval | Query-side vocabulary gap | Compare the recall lists for the original query and the colloquial query |

Behind this table is a very plain engineering habit: log the input and output of every hop into a trace. At minimum you must be able to answer three questions: is it in the store, was it recalled, was it sent to the model. A RAG system without traces means tuning is basically guesswork.

## Coupling points between the two pipelines

Offline and online are not fully independent; at least three contracts must be aligned:

1. Embedding model and dimension. Query vectors must use exactly the same model and preprocessing as the index (normalization, query prefix, truncation length). If you switch models and forget to sync the online side, the symptom is a uniform drop in similarity across all queries, with no error raised by the system.
2. Chunking strategy and context construction. If offline uses small-to-big (retrieve with small chunks, return large chunks for reading), the online side must know the parent-document mapping; that mapping is part of the index.
3. Metadata schema. Online filter expressions depend on field names. When the offline side adds fields or changes types, there must be version negotiation; otherwise filter conditions silently fail, which is far more dangerous than an error.

I pin these three things down in a `index_manifest`, read and validated at online service startup. On mismatch, the service refuses to start rather than running gracefully with a broken configuration.

## Strengths, weaknesses, and boundaries

RAG's core advantages are that knowledge is updatable, traceable, and filterable by permission, and that no retraining is needed for each new batch of data. The cost is a whole data engineering stack: parsing, chunking, indexing, rebuilding, evaluation, monitoring. The failure surface is an order of magnitude larger than "a single model call." The ceiling on quality isn't the model either; it's corpus quality and retrieval quality. What isn't in the corpus, no amount of generation can produce.

When it doesn't apply is also clear: a tiny, stable corpus (a few pages fit in the system prompt more easily), tasks that are essentially style transfer or reasoning rather than factual QA, and scenarios requiring extremely low latency with a fixed answer set. One easily overlooked case: when the corpus itself is contradictory with no authority markers, RAG feeds the contradictions to the model together, and the output looks less trustworthy than the pure model. What's needed then is data governance, not retrieval tuning.

The next five posts go hop by hop down the online pipeline: chunking, embedding, vector stores, hybrid recall, reranking. Each maps to a different symptom in the table above. On your current pipeline, can you print, within five minutes, "the exact chunks actually sent to the model" for a given answer? If not, add traces first—that takes priority over tuning any parameter.
