Measuring Chunking by Retrieval Recall
Label the evidence for 15 questions as spans of the source text, then compare fixed-size and structure-aware chunking with the same embedding retriever by recall@k and context tokens per question, and trace every miss to its cause.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Label the evidence as source spans
- Step 2: Two configurations and a coverage rule
- Step 3: Rank, score and count tokens
- Step 4: Read the misses
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Chunking
- Why Chunk Boundaries Matter Concept · 15 min
- Parsing Documents, Scans and Tables into Clean Text Worked example · 20 min
- Lab: Three Chunkers, One Corpus Lab · 25 min
- Stable IDs and Source Metadata Worked example · 15 min
- Measuring Chunking by Retrieval Recall Lab · 20 min
- Check: Choose a Chunking Strategy Knowledge check · 6 questions
What you will learn
- Evaluate two chunking configurations by their effect on retrieval recall for the same query set.
01. Goal and setup
The first lesson argued that boundaries decide what can be found. This lab measures it. You compare two configurations on the same corpus, the same 15 labelled questions and the same retriever:
- A: fixed windows of 96 tokens with 16 tokens of overlap, embedded as they are;
- B: structure-aware chunks of at most 96 tokens, embedded with their heading-path header.
Only the chunking differs, so differences in the results come from chunking. You report two numbers per configuration. Recall@k is the share of a question's evidence that appears in the top k retrieved chunks, averaged over the questions. Context tokens per question is what those k chunks would cost in the prompt. The retrieval-evaluation skill later adds precision, rank-aware metrics and how to build bigger query sets; to compare chunkings, recall and cost are enough.
You need: the chunk-lab folder from the lab, with the complete chunkers.py. The retriever is a small local embedding model, BAAI/bge-small-en-v1.5, run on the CPU through FastEmbed, so no API key is involved. Tested with fastembed 0.9.1 and numpy 2.5. The first run downloads about 67 MB of model files into your temporary folder; set FASTEMBED_CACHE_PATH to keep them somewhere else, and EMBED_MODEL to try another model that FastEmbed supports.
chunk-lab/
├── labels.py step 1: questions, evidence quotes, quote-to-span lookup
├── check_labels.py step 1
├── evaluate.py steps 2 and 3: configurations, coverage, recall, tokens
└── misses.py step 4cd chunk-lab
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install fastembed numpy02. Step 1: Label the evidence as source spans
Relevance labels must outlive any particular chunking. A label such as chunk 7 answers q08 means something only for the chunking that produced chunk 7; under configuration B there is no such chunk. So label the evidence in the source: the document and the exact words that answer the question. Any chunk, from any configuration, can then be checked against those words.
Quoting is quicker and safer than typing offsets. locate() turns each quote into character offsets, treating every run of whitespace as equal (the corpus is hard-wrapped, the quotes are not), and it refuses a quote that matches zero times or more than once, so a typo or an ambiguous label fails loudly instead of being scored as a miss.
import re
from pathlib import Path
# (query id, question, [(document, quote of the evidence), ...])
QUERIES = [
("q01", "Which Python version do I need to run Larkspur?",
[("install.md", "Larkspur needs Python 3.11 or later")]),
("q02", "Can I use Larkspur on Windows?",
[("install.md", "Windows is supported through WSL 2 only.")]),
("q03", "What do I have to run before starting version 3?",
[("install.md", "run `larkspur migrate` once before you start the new version")]),
("q04", "Why are my jobs stuck as queued after an upgrade?",
[("install.md", "Skipping the migration leaves jobs stuck in the queued state.")]),
("q05", "How many jobs run in parallel by default?",
[("configuration.md", "how many jobs run at the same time. The default is 4.")]),
("q06", "Which environment variable sets the time zone?",
[("configuration.md", "| timezone | UTC | LARKSPUR_TZ |")]),
("q07", "Why did a scheduled run happen twice during the night?",
[("configuration.md", "Daylight-saving changes can skip or repeat a run")]),
("q08", "How long does Larkspur wait between retries?",
[("retries.md", "the retries happen after 10, 20 and 40 seconds.")]),
("q09", "How long are failed jobs kept before they are deleted?",
[("retries.md", "It stays there for 14 days and is then deleted.")]),
("q10", "How do I rerun a job that ended up in the dead-letter queue?",
[("retries.md", "`larkspur dlq replay <job-id>` to run one again.")]),
("q11", "What is the default timeout for a job?",
[("retries.md", "The default timeout is 15 minutes.")]),
("q12", "How do I start the nightly report from Python?",
[("api.md", "response = httpx.post( "
'"http://localhost:8470/jobs/nightly-report/runs",')]),
("q13", "Which port does the API listen on, and how do I authenticate?",
[("api.md", "a small JSON API on port 8470."),
("api.md", "Every request needs an `Authorization: Bearer` header")]),
("q14", "What happens if I send too many API requests?",
[("api.md", "Further requests get `429 Too Many Requests`")]),
("q15", "How often is a failed job retried, and what happens after the last try?",
[("retries.md", "Failed jobs are retried up to 3 times by default."),
("retries.md", "After the last retry, the job moves to the dead-letter queue.")]),
]
def locate(text: str, quote: str) -> tuple[int, int]:
"""Find a quote in the text; any run of whitespace matches any other."""
pattern = r"\s+".join(re.escape(word) for word in quote.split())
matches = [m.span() for m in re.finditer(pattern, text)]
if len(matches) != 1:
raise ValueError(f"{quote!r} matches {len(matches)} times; quote more text")
return matches[0]
def load_docs(folder: str = "corpus") -> dict[str, str]:
paths = sorted(Path(folder).glob("*.md"))
return {p.name: p.read_text(encoding="utf-8") for p in paths}
def load_labels(docs: dict[str, str]) -> list[dict]:
labels = []
for qid, question, evidence in QUERIES:
spans = [(doc, *locate(docs[doc], quote)) for doc, quote in evidence]
labels.append({"qid": qid, "question": question, "spans": spans})
return labelsTwo habits make labels useful. Write questions the way users ask them, not by copying the page: several of these use other words (in parallel for at the same time, rerun for replay, happen twice for repeat). And keep evidence minimal, the words that answer and no more; if you label whole sections, every large chunk looks relevant. Restore the original pages (the IDs lesson edited one) and check that every quote resolves:
from labels import load_docs, load_labels
docs = load_docs()
labels = load_labels(docs)
print(len(labels), "questions,", sum(len(q["spans"]) for q in labels), "evidence spans")
for doc, start, end in labels[7]["spans"]:
print(labels[7]["qid"], doc, start, end, repr(docs[doc][start:end]))python make_corpus.py
python check_labels.pyinstall.md 207 tokens
configuration.md 187 tokens
retries.md 178 tokens
api.md 210 tokens
15 questions, 17 evidence spans
q08 retries.md 228 275 'the retries happen after 10, 20 and 40\nseconds.'The evidence for q08 crosses a line break in the source, and locate() found it anyway. Two questions, q13 and q15, need two spans each, so their recall can be 0, 0.5 or 1.
03. Step 2: Two configurations and a coverage rule
Create evaluate.py with the first part:
import os
from statistics import mean
from typing import NamedTuple
import numpy as np
from fastembed import TextEmbedding
from chunkers import fixed_chunks, ntokens, structure_chunks, with_header
from labels import load_docs, load_labels
class Entry(NamedTuple):
doc: str
start: int
end: int
text: str # what is embedded, and what the model would later read
CONFIGS = {
"A fixed 96/16": lambda doc, text: [
Entry(doc, c.start, c.end, text[c.start:c.end])
for c in fixed_chunks(text, size=96, overlap=16)],
"B structure+hdr": lambda doc, text: [
Entry(doc, c.start, c.end, with_header(text, c))
for c in structure_chunks(text, size=96)],
}
docs = load_docs()
labels = load_labels(docs)
model = TextEmbedding(os.environ.get("EMBED_MODEL", "BAAI/bge-small-en-v1.5"))
questions = np.array(list(model.query_embed([q["question"] for q in labels])))
def coverage(span: tuple[str, int, int], hits: list[Entry]) -> float:
"""The share of the evidence's characters that the retrieved chunks contain."""
doc, start, end = span
chars: set[int] = set()
for hit in hits:
if hit.doc == doc:
chars.update(range(max(start, hit.start), min(end, hit.end)))
return len(chars) / (end - start)An Entry holds a chunk's document, its offsets and the text that is embedded: the raw window in A, the output of with_header() in B. Scoring uses the offsets; the retriever and, later, the model see the text, and its token count is the context cost.
coverage() returns the share of an evidence span's characters that appear in any retrieved chunk of the same document. A span counts as found only at 1.0, meaning all of it was retrieved, possibly across two neighbouring chunks. The rule is strict on purpose: a chunk holding the retries happen after 10, 20 and does not answer the question. Some teams accept half of the span or more; whichever rule you choose, apply it to both configurations and write it down next to the results.
04. Step 3: Rank, score and count tokens
Append the second part to evaluate.py:
def rank(make) -> tuple[list[Entry], np.ndarray]:
"""Chunk and embed the corpus; return the entries and, per question, a ranking."""
entries = [e for doc, text in docs.items() for e in make(doc, text)]
vectors = np.array(list(model.embed([e.text for e in entries])))
return entries, np.argsort(-(questions @ vectors.T), axis=1, kind="stable")
if __name__ == "__main__":
for name, make in CONFIGS.items():
entries, rankings = rank(make)
for k in (1, 3):
recalls, tokens, misses = [], [], []
for q, ranking in zip(labels, rankings):
hits = [entries[i] for i in ranking[:k]]
found = [coverage(span, hits) == 1.0 for span in q["spans"]]
recalls.append(sum(found) / len(found))
tokens.append(sum(ntokens(h.text) for h in hits))
if not all(found):
misses.append(q["qid"])
print(f"{name:<15} chunks {len(entries):>2} recall@{k} "
f"{mean(recalls):.2f} tokens/query {mean(tokens):>3.0f} "
f"missed: {' '.join(misses)}")rank() chunks and embeds the corpus once per configuration and sorts the similarities for all questions in one call. The model returns normalised vectors, so the dot product is the cosine similarity, and kind="stable" keeps ties in a fixed order so that runs are reproducible. With only 12 to 17 chunks, k = 5 would return about a third of the corpus, so the lab reports k = 1 and k = 3; on a real documentation set, use k = 5 as the practice project asks.
python evaluate.pyA fixed 96/16 chunks 12 recall@1 0.77 tokens/query 84 missed: q03 q08 q09 q15
A fixed 96/16 chunks 12 recall@3 0.93 tokens/query 248 missed: q08
B structure+hdr chunks 17 recall@1 0.87 tokens/query 64 missed: q07 q13 q15
B structure+hdr chunks 17 recall@3 0.93 tokens/query 186 missed: q07What the numbers say:
- At k = 1, B finds more of the evidence than A (0.87 against 0.77) while sending fewer tokens per question (64 against 84).
- At k = 3, both reach 0.93, but B needs 186 tokens per question and A 248: the same recall for a quarter fewer tokens.
- With 15 questions, one question is worth about 0.07 of recall, so a gap of one or two questions is a hint, not proof. More and more varied questions are what make a difference trustworthy.
Never compare recall@k alone. A configuration with bigger chunks puts more text into the same k results, so it has more chances to contain the evidence and costs more per question. Keep the token column next to recall, or compare both configurations at the same token budget, which is one of the stretch tasks.
05. Step 4: Read the misses
Averages hide causes. List every question that k = 1 did not fully answer, with how much of each evidence span the top chunk held and where that chunk starts:
from evaluate import CONFIGS, coverage, docs, labels, rank
K = 1
for name, make in CONFIGS.items():
entries, rankings = rank(make)
print(name)
for q, ranking in zip(labels, rankings):
top = [entries[i] for i in ranking[:K]]
cover = [coverage(span, top) for span in q["spans"]]
if min(cover) < 1.0:
hit = top[0]
first_line = docs[hit.doc][hit.start:hit.end].strip().splitlines()[0]
shares = " ".join(f"{c:.0%}" for c in cover)
print(f" {q['qid']} evidence found: {shares:<8} top hit: "
f"{hit.doc} {first_line[:28]!r}")python misses.pyA fixed 96/16
q03 evidence found: 0% top hit: api.md 'runs` to start a job now. Th'
q08 evidence found: 0% top hit: retries.md 'job to turn retries off.'
q09 evidence found: 0% top hit: retries.md '# Retries and failures'
q15 evidence found: 100% 34% top hit: retries.md '# Retries and failures'
B structure+hdr
q07 evidence found: 0% top hit: retries.md '## Retry policy'
q13 evidence found: 100% 0% top hit: api.md '# HTTP API'
q15 evidence found: 100% 0% top hit: retries.md '## Retry policy'Each miss falls into one of four kinds, and only some are chunking problems:
- Cut by a boundary (chunking). For A's q15 the top window holds all of the first span but only 34% of the second: it ends right after After the last retry,. The next window holds the whole second span, so the evidence is split across two chunks rather than lost.
- Diluted chunk (chunking). A's q08 and q09 evidence each sits intact in one window that mixes several topics and ranks below another. q08's retry timings are in the first window, which mixes the introduction, the retry policy and the start of the dead-letter section; the top hit is the next window, which starts mid-sentence at job to turn retries off, and q08 is missed even at k = 3. For q09 it is the other way round: the top hit is the first window, and the sentence about the 14 days sits in the next one.
- More than one section needed (a property of small chunks). B's q13 and q15 each need spans from two sections. One chunk can hold only one of them, so recall@1 is at most 0.5; both are found at k = 3.
- Vocabulary gap (the retriever). B's q07 asks why a run happened twice during the night, while the evidence says a run can repeat between 01:00 and 03:00. A happened to rank first a window that begins with that very sentence, but the lasting fixes are on the retrieval side, such as query rewriting or hybrid search, which the RAG skills cover. A's q03 is a near miss of the same kind: its top hit, in
api.md, is about starting a job.
Now decide. On this corpus B gives equal or better recall for fewer tokens, its misses at k = 1 are mostly questions that span two sections, which a larger k handles, and each of its chunks cites cleanly to one section. A's misses come from boundaries and diluted windows, which a better retriever or a larger k can only partly offset. B is the better choice here; on your own documentation, run the same comparison before you decide.
06. Check your understanding
07. Apply it: stretch tasks
- Isolate the header. Add configuration C: structure-aware chunks embedded without the header. Is B's advantage over A due to the boundaries, the header, or both?
- Equal token budget. Instead of a fixed k, take chunks in rank order until the next one would push the total over 200 tokens, and compare recall at that budget.
- Swap the retriever. Score with BM25, for example your implementation from the Vector Search skill, and rerun. Does the order of A and B hold with a different retriever?
- The practice project. On your licensed documentation set, label 15 questions with evidence quotes, build two chunking configurations with deterministic IDs and source paths, and report recall@5 and context tokens per question for both, with a short analysis of every miss.
08. Review prompt
Without looking back:
- Why must relevance be labelled on source spans when you compare chunkings, and how does this lab turn a quote into a span?
- State the coverage rule used here and one alternative, with its risk.
- Why do you report context tokens next to recall@k?
- Name the four kinds of miss from step 4 and say which of them a change of chunking can fix.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.