RAG over code: chunking is the whole game
I’m building an assistant that answers questions about a distributed database I wrote in Go. Asked
from memory, a small hosted model scored 0.385 on my 50-question golden set. This week I let it read
the repo first. Most of the week went into one question: what counts as a “piece” of code?
What I built
A retrieval pipeline over the repo, in three parts:
Go source ──▶ gochunk (go/ast) ──▶ 216 chunks ──▶ BM25 ──▶ top 5 ──▶ prompt: "cite path:line"
func · method · type · const/var block · design comment · file header
The chunker is about 200 lines of Go on the standard library parser. Each declaration becomes one
chunk with its doc comment, file path and line range. That line range is what lets
the model cite storage/record.go:9-26 instead of waving at “the storage layer.” Retrieval is BM25 by
default, with mean-pooled GPT-2 vectors as the dense comparison, searched both exactly and with the
HNSW index from earlier in this series.
Retrieval on its own, with no model involved (20 questions, then the full 50):
| Retriever | recall@5 | MRR |
|---|---|---|
| BM25 | 0.95 (0.96 on 50) | 0.76 (0.80 on 50) |
| GPT-2 dense, brute force | 0.25 (0.22 on 50) | 0.21 (0.18 on 50) |
| GPT-2 dense, HNSW | 0.25 | 0.21 |
Then the real test: the same 50 questions to gemini-3.5-flash-lite, with retrieval off and on.
| Run | Mean key-fact score | Full marks | Zero | p50 latency | Cost |
|---|---|---|---|---|---|
| No retrieval | 0.385 | 6 | 17 | 1.27 s | $0.019 |
| BM25, top 5 | 0.727 | 28 | 5 | 1.17 s | $0.030 |
Retrieval nearly doubled the score, and 48 of 50 answers cited a retrieved file. Prompts got about 7x
bigger, yet the run cost only $0.011 more and latency didn’t rise.
The concepts that made it work
- Chunk by the language, not by size. A fixed-size window cuts a function in half and leaves
its doc comment in the chunk before. Go’s own parser knows where every declaration and its comment
start and end. Use it. - Index the path and the name too. Each chunk is indexed as
path nameplus the body, so a
question about “the storage engine” can findDB.loadIndexeven when the body never says
“storage.” - Code is unusually friendly to keyword search. Identifiers are exact and rare:
lastSeqmeans one
thing. My tokenizer keeps the whole identifier and its camelCase parts (lastseq last seq), so exact
and partial matches both score. BM25 then runs in 0.14 ms per query, with no model and no GPU. - The embedder is the lever, again. In my RAG-from-scratch note I found GPT-2 makes weak sentence
vectors. On code it’s worse than useless: picking five chunks at random would hit the right file 0.39
of the time on these questions, and GPT-2 managed 0.25. I wired up a real
embedding model too (nomic-embed-textvia Ollama), but I haven’t measured it yet.
The thing that bit me
My first chunker kept only functions, methods and types. BM25 hit 0.90 recall@5, and I started
thinking about tuning k1 and b. Then I read the misses one by one.
One question asked what a record looks like on disk. The best answer in the repo is a box diagram in
a comment: crc | tstamp | keyLen | valLen | key | value. It sits above a const block with a blank
line in between. Go doesn’t attach a comment like that to anything, and my chunker only indexed
declarations. So the diagram was never in the index. No ranking formula could have found it.
The fix was in the chunker: one chunk per const/var block, and every free-floating comment of three
or more lines. Recall@5 went from 0.90 to 0.95, and I never touched BM25. Now, when retrieval misses,
I first check that the answer is in the index at all.
The answer scores had the same lesson. Of the 5 zero-score answers, 4 were correct in different words
(“removes the temporary file” where my key fact was .merge). Only one was a real miss: retrieval
didn’t find the file, and the model said the context didn’t cover it instead of guessing.
Tradeoffs & the road not taken
- BM25 as the default, not embeddings. It beat my dense baseline by 0.70 recall at no cost. It has
a real limit, though. “How does the sharded KV map a key to a shard?” matches every chunk that says
key and shard, and the right file sinks. Hybrid retrieval (BM25 plus a good embedder, merged with
rank fusion) is built for that case. I haven’t built it yet. - Exact search, not HNSW. At 216 chunks, HNSW returned exactly what brute force did and saved
nothing, because exact search is already sub-millisecond. Approximate indexes pay off at hundreds
of thousands of vectors, not hundreds. - No incremental re-index, no tests in the index. The repo is re-chunked from scratch each run, and
_test.gofiles are left out. Both matter more once the code changes every day.
Where this sits in the system
Earlier in this series I built a vector index
and RAG over a toy corpus.
This week both ran on a real codebase with real questions, and the plain keyword index won. Next the
assistant stops waiting for one retrieval and starts calling tools itself: reading files and searching
the repo on its own.
Part of a series building a modern AI stack from scratch, told visually. (Earlier: RAG from scratch.)