Versions and honesty up front. Java 25.0.5.1 (Temurin, LTS), JUnit 6.1.3 (on Maven Central since 2026-08-07, the latest GA on 2026-11-25), Maven Surefire 3.5.4. No Spring and no model. The corpus (40 passages) and the 30 questions are synthetic, written for this post. The retrievers are BM25, a hashed character-trigram vector that is not a neural embedding, and their fusion. So the scores show how the method behaves, not how any real model or corpus would score. All code is in the rag-eval module of the spring-ai repository.
Grade the retriever on its own, before a model ever sees a passage
When a RAG answer is wrong, there are two suspects. Either the retriever never fetched the passage that holds the answer, or it did and the model misused it. They need different fixes, and a score on the final answer cannot tell them apart. Grading the retriever alone separates them.public interface Retriever {
String name();
List<String> retrieve(String query, int k);
}
Anything you can wrap in those two methods can be graded: a vector store, a keyword index, a hybrid, a reranked list. The evaluation code never learns which.
Going deeper: why not just judge the final answer?
An answer-level judge (an LLM scoring the reply) is useful, but it mixes the two stages, costs a model call per question, and its verdicts wobble between runs. A retrieval score is deterministic and cheap enough to run on every commit. The two complement each other: retrieval metrics guard stage one in CI, answer judges guard the whole pipeline less often. The earlier post on testing LLM apps with evaluators and LLM-as-judge in JUnit 6 covers the answer side.- Companion module for that post: the evaluation module
- Real retrievers worth grading with this harness: hybrid search with RRF and cross-encoder reranking
- What happens before retrieval, chunking included: the ingestion pipeline post
A golden dataset is questions plus the passages that answer them
The ground truth is a plain text file: one line per question, with its category and the ids of the passages that answer it. Each passage carries a grade — 2 means it answers the question by itself, 1 means it is useful supporting context. Here are four lines (golden.tsv; the columns are tab-separated):q02 exact E-4012 p09:2
q12 paraphrase I can't remember my login credentials, how do I get back in? p01:2
q14 paraphrase I typed the wrong password too many times p03:2,p01:1
q25 multi how long do deleted customer records stay around p30:2,p07:1
The passages live in corpus.tsv: 40 short runbook entries about password resets, VPNs, backups, deployments and so on. The first test is not about retrieval at all; it checks that the golden set itself is sound, because a typo in a passage id makes a question unanswerable and quietly lowers every score (DatasetTest.java):
passages : 40
questions : 30
exact : 11
multi : 6
paraphrase : 13
judgements : 42 (31 grade 2, 11 grade 1)
passages judged : 31 of 40
never relevant : [p06, p21, p23, p29, p31, p33, p34, p35, p38]
Output from 00-dataset.txt.
Use the queries people actually type. My first version of questions 1 to 3 were full sentences such as “What does error VPN-619 mean?”. With those, a tokenizer that deletes digits scored exactly the same as the good one, because “error” and “mean” were enough to find the passage. I rewrote them as the bare codes a user would paste (VPN-619,E-4012,E-5003), and only then did the regression later in this post become visible. A golden set made of tidy sentences will not catch the failures your users trigger with messy input.
Going deeper: building and keeping a golden set
Three habits matter more than the size of the set. Label by hand, never from the retriever’s own output: if the current system picks the passages you then call correct, the dataset can only ever agree with it. Mix the kinds of question your users ask. This set has exact lookups (codes, numbers), paraphrases that share no words with the answer, and questions that need two passages. Reporting per category, as the later tables do, is what shows where a change helped or hurt. Treat the file as code: review changes, keep it in the repository, and validate it in a test. A set you tune against stops being a fair test of the thing you tuned. If you adjust a parameter until the scores rise, keep some questions aside that you never look at while tuning.- Where questions come from in practice: support tickets, search logs and chat transcripts, then rewritten into the query a user would type. That sourcing advice is general practice, not something this module measures.
- The loader: Dataset.java
- Grades and the records behind them: GoldenQuestion.java
Four counting questions, and one that cares about order
Each metric answers a different plain question about the list the retriever returned. Take one list and score it by hand:| Metric | The question it answers | Reach for it when |
|---|---|---|
| hit@k | Is anything relevant in the top k? | One passage is enough to answer |
| recall@k | What share of the relevant passages came back? | The answer needs several passages |
| precision@k | What share of the k slots were useful? | The prompt budget is tight and noise hurts |
| MRR | How far down is the first relevant passage? | Users or the model mostly use the top result |
| nDCG@k | Are the best passages near the top, using grades? | You have graded judgements and order matters |
/** Distinct relevant passages found in the top k, divided by all relevant passages. */
public static double recallAtK(List<String> ranked, Set<String> relevant, int k) {
if (relevant.isEmpty()) return Double.NaN;
long found = top(ranked, k).stream().filter(relevant::contains).count();
return (double) found / relevant.size();
}
/** 1 / rank of the first relevant passage, or 0 if none is in the list. */
public static double reciprocalRank(List<String> ranked, Set<String> relevant) {
List<String> list = distinct(ranked);
for (int i = 0; i < list.size(); i++) {
if (relevant.contains(list.get(i))) return 1.0 / (i + 1);
}
return 0;
}
Then the test that pins the hand-worked list above, and its transcript (MetricsTest.java, output in 01-metric-worked-examples.txt):
retrieved (best first) : [p03, p01, p07, p02, p09]
relevant with grade : p01=2, p02=1, p08=1
hit@1 = 0.0000
hit@2 = 1.0000
recall@5 = 0.6667 (2 of 3 relevant found)
precision@5 = 0.4000 (2 relevant of 5 returned)
MRR = 0.5000 (first relevant at rank 2)
nDCG@5 = 0.5625 (DCG 2.3235 / ideal 4.1309)
Download: if you only want the metrics, RagMetricsDemo.java is the same functions in one dependency-free file. Run it with java RagMetricsDemo.java on JDK 25; it prints the six numbers above.
Going deeper: nDCG, step by step
nDCG compares the list you got with the best list you could have got. Each passage contributes a gain that depends on its grade, discounted by how far down it sits. This module uses exponential gain,(2^grade − 1) / log2(rank + 1), so a grade-2 passage is worth 3 and a grade-1 passage is worth 1 before the discount. For the list in the figure, p01 at rank 2 contributes 3 / log2(3) = 1.8928 and p02 at rank 4 contributes 1 / log2(5) = 0.4307, so DCG = 2.3235. The best possible order puts p01, p02 and p08 in ranks 1 to 3 and is worth 3 + 0.6309 + 0.5 = 4.1309. Dividing gives 0.5625. These intermediate figures were worked by hand and appear in the test’s comments; the test asserts only the final ratio, to three decimals.
Some libraries use the linear gain (the grade itself) instead. Both are legitimate, they give different numbers, and nDCG values from different tools are only comparable if the gain function matches. Pick one and keep it.- The full method with the tests that pin it: Metrics.java
- Background reading on the family of measures: Evaluation measures (information retrieval) and Discounted cumulative gain
Edge cases that quietly change the number
Two implementations of “recall@5” can disagree by a lot without either being wrong, because the definition leaves cases open. The module fixes each one and a test pins it (PitfallsTest.java):1 duplicates [p01 p01 p01 p02 p03], p01 relevant, precision@5 = 0.20 (naive count would give 0.60)
2 precision cap perfect list, one relevant passage, precision@5 = 0.20
3 short list 2 results, precision@5 = 0.20
4 no relevant recall@5 = NaN, nDCG@5 = NaN
5 MRR blind to the second hit: 0.50 vs 0.50
6 order, same recall@2 = 1.00:
support first nDCG@2 = 0.7967, MRR = 1.00
answer first nDCG@2 = 1.0000, MRR = 1.00
Output from 02-pitfalls.txt.
Chunks inflate counts. Line 1 is the one that bites RAG specifically. If a long document was split into chunks and three of them come back, a naive count calls precision 0.60. The module removes duplicates first and scores 0.20. If your chunks carry a document id, decide whether a hit means the chunk or the document, and make the golden set use the same unit.
Going deeper: the six cases, one line each
- Duplicates are removed, first occurrence wins, before any metric is computed.
- Precision has a ceiling. With one relevant passage, precision@5 can never exceed 0.2, so low precision@k is normal for single-answer questions and is not a defect. Use hit@k or MRR for those.
- A short list is not padded, and precision still divides by k, so returning fewer results cannot raise it.
- No relevant passage gives NaN for recall and nDCG, not 0, and the means skip it. Counting a 0 would punish the retriever for a gap in the dataset.
- MRR ignores the second hit. Finding another relevant passage earlier does not move it, which is why recall or nDCG sit beside it.
- Order matters to nDCG and MRR but not to recall@k. Same set, different order, same recall, different nDCG.
- The metrics and their Javadoc rules: Metrics.java
- Where per-question scores are averaged: Report.java
Compare retrievers on the same questions
Three retrievers are built from the same 40 passages so the metrics have something to measure. bm25 is Okapi BM25, a keyword scorer (Bm25Retriever.java). ngram turns each word into character trigrams, hashes them into 512 dimensions and ranks by cosine similarity (HashedNgramRetriever.java). hybrid fuses the two lists with Reciprocal Rank Fusion (RrfRetriever.java). A fourth, bm25-lettersonly, is BM25 with one deliberate bug that appears in a later section.The ngram retriever is not an embedding model. It sees spelling overlap, not meaning, so it cannot connect “died” to “fails”. It is here so the harness has two differently-behaved retrievers without a model download. To grade a real embedding model, implement Retriever around its search call; nothing in the evaluation changes.
One test runs all four and prints the table you will look at most (RetrieverComparisonTest.java, output in 03-retriever-comparison.txt):
retriever hit@1 hit@5 recall@5 recall@10 MRR nDCG@10
bm25 0.733 0.933 0.867 0.867 0.814 0.798
ngram 0.833 0.933 0.883 0.883 0.875 0.818
hybrid 0.833 0.900 0.850 0.883 0.871 0.818
bm25-lettersonly 0.667 0.867 0.800 0.833 0.751 0.741
MRR by question category
retriever exact paraphrase multi
bm25 1.000 0.609 0.917
ngram 1.000 0.827 0.750
hybrid 1.000 0.769 0.854
bm25-lettersonly 0.828 0.609 0.917
Questions with no relevant passage in the top 5
bm25 [q22, q24]
ngram [q24, q25]
hybrid [q22, q24, q25]
bm25-lettersonly [q02, q03, q22, q24]
Going deeper: grading a real retriever with this harness
The evaluator callsretrieve(query, k) and reads ids. To grade a vector store, wrap its similarity search, map each returned document back to the passage id you stored in its metadata, and return the ids best first. Keep the id scheme identical to the one in the golden file. Two cautions that apply to any real system: pin the embedding model and its version, because a silent model change is exactly the kind of regression this harness exists to catch, and say how many candidates the search fetches before you compare, because approximate indexes can return different lists for the same query.
The hybrid search post and the reranking post each measure real retrievers over their own labelled questions; their companion modules are good candidates to wrap.- The factory that selects a retriever by name: Retrievers.java
- How every metric is computed per question: Evaluator.java
- Keyword scoring background: Okapi BM25
Is the difference real? A paired bootstrap
The trigram vector scored a higher MRR than BM25 (0.875 against 0.814). Is it better? With 30 questions, one question moving one rank can account for a lot of that. A paired bootstrap asks the question directly: resample the 30 questions with replacement, recompute the difference between the two retrievers each time, and see how much it swings. If the middle 95% of those differences includes zero, the data cannot separate the retrievers. The core is short (Bootstrap.java): /** Mean of (b - a) with a 95% percentile interval. Both arrays hold one score per question, same order. */
public static Interval pairedDifference(double[] a, double[] b, int resamples, long seed) {
if (a.length != b.length) throw new IllegalArgumentException("arrays must be paired");
Random rnd = new Random(seed);
int n = a.length;
double[] diffs = new double[resamples];
for (int r = 0; r < resamples; r++) {
double sum = 0;
for (int i = 0; i < n; i++) {
int j = rnd.nextInt(n);
sum += b[j] - a[j];
}
diffs[r] = sum / n;
}
Arrays.sort(diffs);
double observed = 0;
for (int i = 0; i < n; i++) observed += b[i] - a[i];
return new Interval(observed / n, diffs[(int) (resamples * 0.025)], diffs[(int) (resamples * 0.975) - 1]);
}
Run on the four retrievers with 10,000 resamples and a fixed seed (BootstrapTest.java, output in 04-bootstrap.txt):
candidate vs bm25 metric mean diff 95% interval interval excludes 0?
ngram mrr +0.061 [-0.067, +0.183] no
ngram recall@5 +0.017 [-0.067, +0.117] no
hybrid mrr +0.057 [-0.038, +0.147] no
hybrid recall@5 -0.017 [-0.050, +0.000] no
bm25-lettersonly mrr -0.063 [-0.159, +0.000] no
bm25-lettersonly recall@5 -0.067 [-0.167, +0.000] no
one question can move MRR by at most 1/30 = 0.033 (a miss becoming a rank-1 hit)
one question moving from rank 2 to rank 1 moves it by 0.5/30 = 0.017
Not one interval excludes zero. The trigram vector’s +0.061 MRR has an interval from −0.067 to +0.183, so the honest reading is “no evidence either way”, not “better”. Even the broken tokenizer, which really is worse, only just fails to clear it: its interval runs from −0.159 up to +0.000. And the last two lines are the floor under every claim: one question moves MRR by at most 0.033.
A bootstrap on 30 questions is a smoke alarm, not a verdict. It tells you when a difference is too small to believe. It cannot tell you a difference is large when the sample is this small. If you want to detect gains of a few points, you need more questions, not a cleverer statistic.
Going deeper: how the bootstrap is set up, and its limits
It is paired: both retrievers are scored on the same resampled questions, so a hard question that hurts both does not add noise to the difference. It resamples questions, not individual scores, because a question is the unit you would have drawn differently. The 95% interval is read off the sorted differences (the 2.5th and 97.5th percentiles), and the seed is fixed so a rerun prints the same interval. The output file is byte-identical on a second run. Its limits are the dataset’s limits. It cannot repair a golden set that is unrepresentative, and the results here describe a synthetic corpus. If you compare many retrievers or many metrics, some intervals will exclude zero by chance; decide what you are comparing before you look.- The class and its fixed-seed test: Bootstrap.java
- General background: Bootstrapping (statistics)
Read the misses, not the average
BM25 puts a relevant passage in its top 5 for 28 of 30 questions (hit@5 = 0.933). An average cannot tell you what the other two have in common, so a test prints them (MissAnalysisTest.java, output in 05-misses.txt):q22 [paraphrase] "someone pushed a password to git"
returned : [p01, p02, p03, p04, p05]
wanted : {p40=2}
p40 says : Secrets live in the vault, never in source control. A secret found in a repository must be rotated immediately, even if the commit is removed.
first returned says : To reset a forgotten password, open the sign-in page, choose Forgot password and enter your work email. A reset link is emailed and stays valid for 30 minutes.
q24 [paraphrase] "money back after cancelling a yearly subscription"
returned : [p11, p07, p03, p18, p37]
wanted : {p22=2}
p22 says : Refunds for annual plans are prorated by unused full months. Monthly plans are not refunded.
first returned says : To roll back a release, redeploy the previous tagged version from the pipeline. Database migrations are not reverted automatically.
Both are vocabulary mismatches. Nobody wrote “pushed to git” in the passage about secrets in source control, and nobody wrote “money back” in the one about refunds. A keyword retriever has nothing to match, which is the case embeddings are meant to cover, and the ngram line in the comparison table shows its limits too, since it still misses q24. There is also a quieter trap in the first block: the query shares only the word “password” with the corpus, so one passage scores above zero and the other four slots are filled by zero-score ties in corpus order (p02, p03, p04, p05). A retriever with no signal does not return nothing, it returns something arbitrary.
Going deeper: turning misses into work
Group the misses by cause before fixing anything. Vocabulary mismatch points to embeddings, query rewriting or synonyms. A relevant passage that exists but ranks 6 to 10 points to reranking, which the earlier reranking post measures. A passage that was never indexed points at ingestion and chunking. The recall@10 column in the comparison table is the quick test for the second case: if recall@10 is far above recall@5, a reranker has room to help.- The miss report test: MissAnalysisTest.java
- Chunk boundaries as a cause: RAG ingestion and chunking strategies compared
Make the build fail when retrieval gets worse
Metrics only protect you if something stops a bad change. The gate keeps a baseline of the scores the current retriever earns and compares every build with it (Gate.java). The baseline is a small properties file, an overall block and one block per question category, plus the questions that already miss (baseline.properties, first lines):# Written by WriteBaseline for retriever 'bm25'. Review the diff like code.
tolerance=0.04
knownMisses@5=q22,q24
exact.hit@1=1.000
exact.hit@5=1.000
exact.mrr=1.000
exact.ndcg@10=1.000
exact.recall@10=1.000
exact.recall@5=1.000
/** Returns one message per violation; an empty list means the build may pass. */
public List<String> check(Report report) {
List<String> failures = new ArrayList<>();
double tol = tolerance();
for (String metric : TRACKED) {
check(failures, "overall " + metric, report.mean(metric), "overall." + metric, tol);
for (String cat : report.categories()) {
check(failures, cat + " " + metric, report.mean(metric, cat), cat + "." + metric, tol);
}
}
Set<String> known = Arrays.stream(baseline.getProperty("knownMisses@5", "").split(","))
.map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toSet());
for (Report.QuestionResult q : report.misses(5)) {
if (!known.contains(q.id())) {
failures.add("new miss@5: " + q.id() + " \"" + q.query() + "\" (relevant not in top 5, got "
+ q.ranked().subList(0, 5) + ")");
}
}
return failures;
}
The JUnit test is only a few lines, because the gate does the work (GoldenSetGateTest.java), and on a healthy build it prints this (06-gate-pass.txt):
tolerance : 0.04
overall MRR : 0.814
overall nDCG@10: 0.798
misses@5 : [q22, q24]
violations : 0
Now the regression. A well-meaning change tightens the tokenizer so it splits on anything that is not a letter (the two patterns are in Tokenizer.java):
private static final Pattern NON_ALNUM = Pattern.compile("[^a-z0-9]+");
private static final Pattern NON_LETTER = Pattern.compile("[^a-z]+");
Digits vanish from the index, so “VPN-619” becomes “vpn” and “E-4012” becomes nothing at all. An empty query matches no passage and returns the first five in corpus order. The gate catches it (GateCatchesRegressionTest.java, output in 07-gate-catches-regression.txt):
FAIL overall hit@1 = 0.667, below baseline 0.733 - 0.04 = 0.693
FAIL exact hit@1 = 0.818, below baseline 1.000 - 0.04 = 0.960
FAIL overall hit@5 = 0.867, below baseline 0.933 - 0.04 = 0.893
FAIL exact hit@5 = 0.818, below baseline 1.000 - 0.04 = 0.960
FAIL overall recall@5 = 0.800, below baseline 0.867 - 0.04 = 0.827
FAIL exact recall@5 = 0.818, below baseline 1.000 - 0.04 = 0.960
FAIL exact recall@10 = 0.909, below baseline 1.000 - 0.04 = 0.960
FAIL overall mrr = 0.751, below baseline 0.814 - 0.04 = 0.774
FAIL exact mrr = 0.828, below baseline 1.000 - 0.04 = 0.960
FAIL overall ndcg@10 = 0.741, below baseline 0.798 - 0.04 = 0.758
FAIL exact ndcg@10 = 0.846, below baseline 1.000 - 0.04 = 0.960
FAIL new miss@5: q02 "E-4012" (relevant not in top 5, got [p01, p02, p03, p04, p05])
FAIL new miss@5: q03 "E-5003" (relevant not in top 5, got [p01, p02, p03, p04, p05])
13 violations
Eleven score floors fail, and two questions are named: q02 (E-4012) and q03 (E-5003). That second rule is the more useful one in practice, because it reads like a bug report. Running the same test against the broken retriever (mvn test -Dtest=GoldenSetGateTest -Drageval.retriever=bm25-lettersonly, recorded by ci-fail-demo.sh) ends the way a failing CI job should (08-ci-failure.txt, trimmed to the key lines):
# Gate run for retriever 'bm25-lettersonly'
tolerance : 0.04
overall MRR : 0.751
overall nDCG@10: 0.741
misses@5 : [q02, q03, q22, q24]
violations : 13
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] BUILD FAILURE
Why the tolerance is 0.04. One question moving from a miss to a rank-1 hit changes overall MRR by 1/30 = 0.033, so a tolerance below that would fail builds for noise. 0.04 is a little more than one question. The per-category floors are touchier: the exact category has 11 questions, so one question moves its mean by 0.091 and any single drop there trips the gate. That is deliberate for exact lookups and something to relax for noisier categories.
Going deeper: baselines, tolerance and running this in CI
Updating the baseline is a decision, not a chore. After an improvement you want to keep, run write-baseline.sh and review the diff like code: raised floors are the point, and a shrinkingknownMisses@5 list is the best diff you can get. Never regenerate it to make a red build green.
Run it where tests already run. It is an ordinary JUnit test, so mvn -B test in any CI job gates it. The retriever is chosen with -Drageval.retriever=, which is how the failing demo works. Determinism matters: the transcripts here are byte-identical on a second run because BM25, the trigram vector and the fusion are deterministic. A real embedding model behind an approximate index may not be, and I did not test one, so measure the run-to-run spread before you pick a tolerance.
Small gates, not one big one. Rule 2 works because it names the question. If you add more rules, keep that property: a failure message that says which question and what came back.- The gate and baseline writer: Gate.java and WriteBaseline.java
- JUnit’s own reference for test structure: JUnit User Guide
- All scripts: run-all.sh
Should you build this?
Usually yes, but small. Thirty hand-labelled questions take an afternoon and catch the failures that matter most: a tokenizer, a model swap or a chunking change that breaks a whole class of query. They will not detect a gain of a few points, they say nothing about whether the model uses the passages well, and a golden set nobody updates drifts away from what users ask. If your corpus is tiny and changes rarely, reading the top five for a dozen queries by hand may be all you need. Build the gate when more than one person changes the retrieval path, or when it changes often.
Everything here was run on synthetic data with stand-in retrievers, so treat the scores as a demonstration of the method and measure your own.
Further reading
- Companion code: rag-eval in the spring-ai repository, and the standalone RagMetricsDemo.java
- On ankurm.com: Production-grade RAG with Spring AI, Testing LLM apps with evaluators and LLM-as-judge, Hybrid search with RRF, Reranking RAG results, RAG ingestion and chunking
- Evaluation measures (information retrieval), Discounted cumulative gain, Okapi BM25, Bootstrapping (statistics)
No Comments yet!