# My RAG prototype gave a confident, well-formatted answer with citations. One line read:

My RAG prototype gave a confident, well-formatted answer with citations. One line read:

> Implement shuffle-sharding to improve resilience **\[3\]**.

Source \[3\] didn't say that. It wasn't advice at all. It was a list of conference talk titles, and one of them happened to contain the word "shuffle-sharding".

The tempting fix is in the prompt: "only cite sources that support the claim", "be careful with citations". I didn't touch the prompt. Instead I looked at what the model had been given, and then measured the whole corpus with SQL. Every root cause turned out to be in the data.

This post walks through how I debugged it: the hypotheses, the queries, the two theories that turned out to be wrong, and the before/after numbers.

---

## The setup

A small retrieval-augmented generation (RAG) pipeline, all running locally:

- **Documents:** public AWS PDFs, one of them over 1,000 pages
- **Ingestion:** PyMuPDF to extract text, split into ~1,200-character chunks inside document sections
- **Embeddings:** `nomic-embed-text` (768 dimensions) via Ollama
- **Vector store:** PostgreSQL with pgvector, an HNSW index, cosine similarity
- **Generation:** `llama3.2` (3B) via Ollama, with numbered sources in the prompt and `[n]` citations Two pipelines: **ingest** (load → chunk → embed → store) and **ask** (embed the question → top-4 search → drop matches below a similarity floor → prompt → answer with citations).

## The symptoms

Four things were off, and I wrote them all down before touching anything:

| Symptom | Example |
| --- | --- |
| A citation that didn't support the claim | "Implement shuffle-sharding **\[3\]**", where \[3\] was a talk title |
| Strange characters in the answer | "shu**ﬄ**e": one character where there should be three |
| A slow first request | `retrieval=7110ms first_token=8466ms total=13180ms` |
| Off-topic questions scoring high | "What's the weather today?" scored **0.578** against my docs |

## The method

Reproduce → look at what the model actually received → form hypotheses → test each one with a measurement → fix only what the evidence supports.

That middle step matters most. The model can only be as good as the chunks it's given, so the first question for any bad RAG answer is: **was the right text retrieved, and was it clean?** If not, no prompt will fix it.

All the measurements below ran directly in Postgres, against about 4,300 chunks.

---

## H1: Ligature characters are breaking matching. Confirmed

The answer contained "shuﬄe". That "ﬄ" is a single Unicode character (U+FB04), a typographic **ligature**. PDFs use ligatures to render "ffl", "fi" and "fl" nicely.

A quick test:

```sql
SELECT count(*) FROM chunks WHERE content ILIKE '%shuffle-sharding%';  -- 0
SELECT count(*) FROM chunks WHERE content LIKE '%Shuﬄe%';             -- 2
```

The text the model quoted didn't exist in the database in readable form. How widespread was it?

```sql
SELECT round(100.0 * count(*) FILTER (WHERE content ~ '[ﬀ-ﬆ]') / count(*), 1) AS pct
FROM chunks;   -- 88.5
```

**88.5% of all chunks** contained at least one ligature. Words like "configure", "efficient" and "workflow" were broken in a way that's invisible to the eye but very visible to keyword search, and noisy for embeddings.

The cause wasn't a damaged PDF. **PyMuPDF keeps ligatures by default**: its default text-extraction flags include `TEXT_PRESERVE_LIGATURES`. The fix is one flag, plus Unicode normalisation as a safety net:

```python
import unicodedata
import pymupdf
 
FLAGS = pymupdf.TEXTFLAGS_TEXT & ~pymupdf.TEXT_PRESERVE_LIGATURES
 
def page_text(page) -> str:
    # NFKC turns any remaining compatibility characters ("ﬁ") into plain letters ("fi")
    return unicodedata.normalize("NFKC", page.get_text(flags=FLAGS))
```

## H2: Reference lists are indexed as if they were guidance. Confirmed

I pulled up the exact chunk behind citation \[3\]. It began:

```plaintext
• Shuﬄe-sharding: AWS re:Invent 2019: Introducing The Amazon Builders' Library (DOP328)
```

Many sections in these documents end with a "Resources" block: related documents, related videos, related examples. Those lists are *about* the topic, so they score highly for topical questions. But they contain **titles, not advice**. The model then turns a title into a recommendation and cites it.

That's the real answer to "why did it cite the wrong source": the source was the most similar chunk, and it said nothing useful.

**Fix:** detect reference-list chunks at ingestion and drop them. A chunk counts as a reference list only if it has a marker phrase ("Related videos:", "Related documents:", "re:Invent") **and** most of its lines are bullets. Requiring both keeps ordinary bulleted guidance, which is plentiful in these documents.

## H3: Running page headers are polluting chunks. Confirmed

```sql
SELECT split_part(content, E'\n', 1) AS first_line, count(*)
FROM chunks GROUP BY 1 ORDER BY 2 DESC LIMIT 5;
```

The top result was the document's running page header, starting **at least 26.6%** of all chunks. That's a lower bound: headers in the middle of a chunk (a page break inside the chunk) weren't counted.

Why it matters: the same text inside a quarter of all vectors pulls every chunk's embedding towards every other's. That narrows the gap between relevant and irrelevant results, which is part of why "What's the weather today?" scored 0.578.

**Fix:** find lines that appear in the top or bottom three lines of at least half the pages, and drop them at extraction time.

## H4: Table-of-contents text is indexed. Confirmed

Looking for repeated chunk beginnings also surfaced lines like `Implementation guidance ........ 412`. Those are dot leaders from tables of contents. An off-topic question ("best pizza in Mumbai") had a **Table of Contents** chunk as its top match.

**Fix:** drop dot-leader lines, and skip sections titled Contents, Notices or Document revisions.

## H5: Two of the PDFs overlap heavily. Partly confirmed

I had indexed one large framework document plus three shorter documents that I suspected repeated parts of it. To measure the overlap I took 200 chunks from one of the shorter documents and, for each, found its nearest neighbour in the large one:

| Similarity to the closest chunk | Chunks |
| --- | --- |
| \> 0.95 | 11 (5.5%) |
| \> 0.90 | **85 (42.5%)** |

Few chunks were identical, because the two PDFs break pages and paragraphs at different points. But over two-fifths had a very close twin: **the same content, chunked differently**. In a top-4 search, near-duplicates crowd out other useful results.

**Fix:** index the comprehensive document only, and record the decision.

## H6: The vector index dropped results. Ruled out

This is the one I got wrong, and it's the most useful lesson.

My first duplicate query (H5) returned **nothing**. I had a plausible explanation ready: a known pitfall of approximate vector indexes. HNSW collects a fixed number of nearest candidates first (`hnsw.ef_search`, 40 by default in pgvector) and applies the `WHERE` filter *afterwards*. With a selective filter, all 40 candidates can be filtered out, leaving zero rows.

It's a real problem in production, especially with per-tenant filters. But instead of trusting the story, I ran a controlled comparison: the same 200 queries with the index, and again with exact search:

```sql
BEGIN;
SET LOCAL enable_indexscan = off;   -- exact (brute-force) search for this transaction only
-- ... same query ...
COMMIT;
```

Both returned **identical results**: 200 of 200 matched, and 11 near-duplicates in both. The index was fine. The filtered document held 64% of all chunks, so the filter was hardly selective.

The empty result had a boring cause: **I had pasted the SQL into an interactive terminal session, which silently stripped line breaks and spaces.** After saving the queries as files and running them from there, they worked.

The lesson: **a hypothesis needs a controlled comparison, not a convincing story.** I'd have "fixed" an index that wasn't broken.

## H7: Retrieval is slow. Ruled out, but two other causes found

The first request took 7 seconds in "retrieval". Timing each step separately:

|  | embed question | vector search |
| --- | --- | --- |
| First request | ~7,000 ms (all of "retrieval") | (included) |
| Second run | 173 ms | 228 ms |
| Third run | 26 ms | 47 ms |

- **Cold start:** Ollama unloads models after 5 minutes idle (`ollama ps` shows it). The 7 seconds were the embedding model loading, not the search. That's a local-development effect: managed model endpoints don't have it.
- **A new database connection per search:** around 30–40 ms of setup each time. A connection pool (`psycopg_pool`) removed it.

---

## The fixes, by layer

| # | Root cause | Layer | Fix |
| --- | --- | --- | --- |
| 1 | PDF library keeps ligatures by default | Extraction | Flag off + NFKC |
| 2 | "Resources" link lists embedded as content | Chunking | Detect and drop reference lists |
| 3 | Running headers kept | Extraction | Remove lines repeated at page edges |
| 4 | Table-of-contents text kept | Extraction | Drop dot leaders; skip ToC sections |
| 5 | Overlapping documents | Source selection | Index the comprehensive one only |
| 6 | Models unloaded after 5 min | Local runtime | Keep-alive in development |
| 7 | Connection per query | Storage | Connection pool |

**None of them were in the model or the prompt.** The misleading citation was a data problem that showed up as a generation problem.

## Before and after

I kept every diagnostic query in the repository, re-ingested, and ran them again:

| Measure | Before | After |
| --- | --- | --- |
| Chunks with ligatures | 88.5% | **0%** |
| Chunks starting with the page header | ≥ 26.6% | **0** (top first line is now a real heading, at 1.4%) |
| Chunks with table-of-contents dot leaders | present | **0** |
| Framework chunks | 2,717 | 2,499 (ToC, notices, link lists and fragments gone) |
| Top score, "What's the weather today?" | 0.578 | 0.571 |
| Top score, "Best pizza in Mumbai" | 0.460 | 0.447 |
| Top 5 scores, "How should I design for failure?" | top 0.738 | 0.730–0.746, all from the right chapter |
| Talk titles cited as advice | yes | no |
| Retrieval, warm (embed + search) | 7,110 ms cold | 90 ms |

One result surprised me: **cleaning barely moved the off-topic scores.** Similarity scores reflect meaning, not how much junk a chunk contains. What improved is *which* chunks win, and *what text* the model reads.

The gap between the weakest relevant result (0.730) and the strongest off-topic one (0.571) held at about 0.16. My similarity floor of 0.62 sits inside that gap. Below it, the pipeline returns "not found" **without calling the model at all**: zero tokens, zero cost, zero chance of a made-up answer.

## What still isn't fixed

Two honest loose ends:

1. **Mixed chunks.** About 10% of chunks contain real guidance *followed by* a short list of references. The filter keeps them, because they're mostly guidance. Cutting the "Resources" block off before chunking is the next step.
2. **The small model ignores citation rules.** llama3.2 (3B) sometimes cites document section IDs like `[REL11-BP01]` instead of source numbers. I added a rule to the prompt, and the model still does it. A prompt instruction is a request, not a guarantee, especially for small models. So my UI now checks every citation against the retrieved sources and flags the ones that don't match, and the next step is to *measure* citation accuracy on a test set.

## Lessons

1. **Look at the data before tuning the model.** Every root cause was visible in a handful of SQL queries over the chunks.
2. **Measure, then fix, then measure again.** Each fix is tied to a number, and the same saved queries re-measure it.
3. **Rule hypotheses out explicitly.** Two plausible theories were wrong. A controlled comparison and step-by-step timing showed it.
4. **Library defaults matter.** The biggest problem, 88.5% of chunks, came from one default flag.
5. **Absolute similarity scores mean little; gaps do.** Set thresholds in the gap between relevant and irrelevant scores, then calibrate them on a labelled test set.

---

*This is part of my* ***AI Journey*** *series, where I build a GenAI application on AWS step by step, with the trade-offs and costs included. Previously:* [*I built a private RAG API in one file*](https://cloudcompass.hashnode.dev/private-rag-api-fastapi-ollama-chromadb) *and* [*the AWS guardrails I set up before writing any GenAI code*](https://cloudcompass.hashnode.dev/aws-guardrails-genai-budgets-iam-bedrock)*.. Next: turning "it looks right" into numbers with a RAG evaluation set.*
