By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The retrieval lesson said quality depends on chunking, the embedding model and top-k, not on the prompt. That statement is only useful if you can measure it. In this lab you build a tiny labelled query set, score it with two metrics, and use the scores to choose a chunking strategy and a value of k instead of arguing about them.
The retriever here is a bag-of-words ranker so the fixture stays keyless and deterministic. The measurement loop is the lesson: the same labels and the same metrics transfer to a vector store or a managed retriever, where you cannot eyeball an embedding.
A retrieval eval starts with labels, not with a retriever. The set is small on purpose - nine questions is enough to catch a broken ranker and cheap enough to keep in CI - but every row must be defensible.
The fixture below has seven policy articles and nine labelled questions. Each article is indexed twice: once as a coarse chunk (the whole article) and once as fine chunks (one chunk per sentence). The ranker is identical, so the comparison isolates chunking and k.
Three numbers answer three different questions, and a retriever decision needs all three.
"""Score a tiny labelled retrieval set before changing chunking or k."""
import re
DOCS = {
"shipping": (
"Standard shipping takes 3-5 business days. Express shipping takes "
"1-2 business days. Orders over 50 dollars ship free."
),
"returns": (
"Returns are accepted within 30 days of delivery. Items must be "
"unworn and have their tags."
),
"refunds": (
"Refunds go back to the original payment method within 5 business "
"days. We receive the return before the refund starts."
),
"damaged": (
"Report damaged items within 48 hours with a photo. A replacement "
"ships as soon as the report is approved."
),
"address": (
"Change the delivery address only before the order ships. Address "
"changes after dispatch need a carrier request."
),
"approval": (
"Refunds and replacements are queued for human approval. The "
"executor performs the write after the decision."
),
"warranty": (
"Electronics carry a 12-month warranty. Contact support with the "
"order id."
),
}
# question, labelled article, phrase a correct answer must contain
CASES = [
("How long does standard shipping take?", "shipping", "3-5 business days"),
("Can I return an item after 40 days?", "returns", "30 days"),
("When will my refund arrive?", "refunds", "5 business days"),
("A lamp arrived damaged - what now?", "damaged", "48 hours"),
("Can I change my delivery address?", "address", "before the order ships"),
("Does a refund need approval?", "approval", "human approval"),
("What happens after my return is received?", "refunds", "5 business days"),
(
"What do I do with an item I want to return?",
"returns",
"have their tags",
),
("Is there a warranty on electronics?", "warranty", "12-month warranty"),
]
STOP = {
"a", "an", "the", "is", "are", "i", "my", "can", "what", "when", "how",
"long", "does", "do", "it", "on", "for", "there", "after", "will", "to",
"and", "of", "now", "with", "app",
}
def stem(word):
return word[:-1] if len(word) > 4 and word.endswith("s") else word
def terms(text):
return {
stem(word)
for word in re.findall(r"[a-z0-9-]+", text.lower())
if word not in STOP
}
def rank(chunks, query):
query_terms = terms(query)
scored = []
for chunk in chunks:
overlap = len(terms(chunk["text"]) & query_terms)
scored.append((-overlap, chunk["id"], chunk))
return [chunk for _, _, chunk in sorted(scored)]
def hit_at_k(chunks, k):
hits = sum(
any(chunk["doc"] == expected for chunk in rank(chunks, query)[:k])
for query, expected, _ in CASES
)
return hits / len(CASES)
def answer_at_k(chunks, k):
hits = sum(
any(phrase in chunk["text"] for chunk in rank(chunks, query)[:k])
for query, _, phrase in CASES
)
return hits / len(CASES)
def context_tokens(chunks, k):
total = 0
for query, _, _ in CASES:
text = " ".join(chunk["text"] for chunk in rank(chunks, query)[:k])
total += len(text) // 4
return total / len(CASES)
coarse = [
{"id": doc_id, "doc": doc_id, "text": text}
for doc_id, text in DOCS.items()
]
fine = []
for doc_id, text in DOCS.items():
for index, part in enumerate(re.split(r"(?<=\.)\s+", text)):
if part.strip():
fine.append(
{
"id": f"{doc_id}:{index}",
"doc": doc_id,
"text": part.strip(),
}
)
print("chunks: coarse", len(coarse), "fine", len(fine))
print(f"{'chunks':>7} {'k':>2} {'hit@k':>6} {'answer@k':>9} {'ctx_tokens':>11}")
for label, chunks in (("coarse", coarse), ("fine", fine)):
for k in (1, 2, 3, 5):
print(
f"{label:>7} {k:>2} {hit_at_k(chunks, k):>6.2f} "
f"{answer_at_k(chunks, k):>9.2f} "
f"{context_tokens(chunks, k):>11.0f}"
)Read the table as a trade-off, not a leaderboard. At k=1 the coarse index is already at 0.89, but each hit costs 25 context tokens because a whole article arrives with its irrelevant sentences. Fine chunks are cheaper and worse at k=1 (0.78 hit, 0.67 answer) because the ranker has less text to match against. Raising fine chunks to k=3 reaches 1.00 hit@3 at 40 tokens - matching the coarse index's 1.00 hit@2 while sending 12 fewer context tokens per question.
The honest part is answer@3 = 0.78. Two questions retrieve the right article without the sentence that answers them: the ranker scored a different sentence higher. Going to k=5 only lifts answer to 0.89 while raising context from 40 to 66 tokens. That is the point of measuring: more k is not the fix for a ranking problem, and a metric that stops at hit@k would have hidden it.
Each metric points at a different lever. Use the table to decide which change to try next, then make exactly one change.
| Metric | Question it answers | A low value means | First lever to try |
|---|---|---|---|
| hit@k | Is the right article in the context at all? | Chunking or ranker missed; the corpus may not contain the answer | Smaller chunks, reranked results, or a larger k |
| answer@k | Did the generator get the exact fact? | Right article retrieved, wrong sentence ranked | Sentence-level chunks, heading and metadata in the chunk, a better ranker |
| context tokens | What does one answer cost? | Too much irrelevant text per question | Smaller k, smaller chunks, deduplicate near-duplicates |
| missing labels | Is the corpus or the label wrong? | A source is absent or the label is stale | Add the document or relabel the case with the domain owner |
The tuning protocol is deliberately boring: freeze the labelled set and record a baseline, change one lever (chunk size or k), re-run, and compare hit@k, answer@k and context tokens together. A change that wins on hit@k and doubles cost is a decision to state out loud, not a silent improvement.
For Harbor Helper's policy lookup the fixture picks sentence-level chunks with k=3: it is the cheapest configuration that always retrieves the right article, and it leaves the two answer@3 misses as explicit follow-up work for metadata or a better ranker. The decision is written down with its numbers, which means the next engineer can re-run it instead of re-litigating it.
Key takeaways
Retrieval quality is a measurement, not an opinion: build a small labelled set from real tickets first.
hit@k asks whether the source was found; answer@k asks whether the fact reached the context; context tokens track the cost.
Fine chunks with k=3 won here because they matched coarse hit@k at a lower context cost; answer@k stayed low because ranking, not k, was the remaining problem.
Tune one lever at a time and compare all three metrics; state the trade-off when a win in one metric costs another.
Keep the fixture in CI, hold out cases from tuning, and add a labelled case every time retrieval misses in production.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.