Add rag-eval module: retrieval metrics, golden dataset and a JUnit regression gate

hit@k, recall@k, precision@k, MRR and nDCG@k in plain Java with their edge
cases pinned by tests, a 30-question graded golden dataset over a 40-passage
runbook, a paired bootstrap, and a gate (baseline + tolerance + no new misses)
shown failing on a tokenizer that drops digits. BM25, a hashed-trigram vector
(not a neural embedding) and RRF; no model, no network. Java 25, JUnit 6.1.3.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7F47n8shUHpexxavn
This commit is contained in:
Ankur
2026-11-25 13:20:18 +05:30
co-authored by Claude Sonnet 5.5
parent 0bb301d361
commit 98ed878675
43 changed files with 1385 additions and 0 deletions
@@ -0,0 +1,34 @@
package com.ankurm.rageval;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.rageval.support.Transcript;
import org.junit.jupiter.api.Test;
class BootstrapTest {
private final Dataset data = Dataset.load();
@Test
void whichDifferencesAreReal() {
Report bm25 = Evaluator.evaluate(Retrievers.byName("bm25", data.passages()), data);
try (Transcript t = new Transcript("04-bootstrap.txt", "Paired bootstrap, 10,000 resamples of the 30 questions, seed 42")) {
t.line("%-28s %-9s %10s %-17s %s", "candidate vs bm25", "metric", "mean diff", "95% interval", "interval excludes 0?");
for (String name : new String[] {"ngram", "hybrid", "bm25-lettersonly"}) {
Report other = Evaluator.evaluate(Retrievers.byName(name, data.passages()), data);
for (String metric : new String[] {"mrr", "recall@5"}) {
var ci = Bootstrap.pairedDifference(bm25.scores(metric), other.scores(metric), 10_000, 42);
t.line("%-28s %-9s %+10.3f [%+.3f, %+.3f] %s", name, metric, ci.meanDifference(), ci.low(), ci.high(),
ci.excludesZero() ? "yes" : "no");
}
}
t.blank();
// How far can ONE question move the mean? That is the floor under any "improvement".
double[] mrr = bm25.scores("mrr");
t.line("one question can move MRR by at most 1/%d = %.3f (a miss becoming a rank-1 hit)", mrr.length, 1.0 / mrr.length);
t.line("one question moving from rank 2 to rank 1 moves it by 0.5/%d = %.3f", mrr.length, 0.5 / mrr.length);
}
var self = Bootstrap.pairedDifference(bm25.scores("mrr"), bm25.scores("mrr"), 1000, 1);
assertTrue(self.low() == 0 && self.high() == 0, "a retriever compared with itself has a zero-width interval at zero");
}
}
@@ -0,0 +1,50 @@
package com.ankurm.rageval;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.rageval.support.Transcript;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
/** The golden set is code too: a typo in a passage id makes a question unanswerable and silently lowers every score. */
class DatasetTest {
private final Dataset data = Dataset.load();
@Test
void everyJudgementPointsAtARealPassage() {
Set<String> ids = data.passages().stream().map(Passage::id).collect(Collectors.toSet());
assertEquals(data.passages().size(), ids.size(), "passage ids must be unique");
for (GoldenQuestion q : data.questions()) {
assertTrue(!q.grades().isEmpty(), q.id() + " has no relevant passage");
assertTrue(ids.containsAll(q.relevantIds()), q.id() + " names a passage that does not exist: " + q.relevantIds());
assertTrue(q.grades().containsValue(2), q.id() + " has no grade-2 passage, so nothing answers it on its own");
}
assertEquals(30, new HashSet<>(data.questions().stream().map(GoldenQuestion::id).toList()).size());
}
@Test
void describeTheGoldenSet() {
Map<String, Long> byCategory = new TreeMap<>(data.questions().stream()
.collect(Collectors.groupingBy(GoldenQuestion::category, Collectors.counting())));
long judgements = data.questions().stream().mapToLong(q -> q.grades().size()).sum();
long grade2 = data.questions().stream().flatMap(q -> q.grades().values().stream()).filter(g -> g == 2).count();
Set<String> judged = data.questions().stream().flatMap(q -> q.relevantIds().stream()).collect(Collectors.toSet());
List<String> never = data.passages().stream().map(Passage::id).filter(id -> !judged.contains(id)).toList();
try (Transcript t = new Transcript("00-dataset.txt", "Golden dataset: what is in it")) {
t.line("passages : %d", data.passages().size());
t.line("questions : %d", data.questions().size());
byCategory.forEach((c, n) -> t.line(" %-12s : %d", c, n));
t.line("judgements : %d (%d grade 2, %d grade 1)", judgements, grade2, judgements - grade2);
t.line("passages judged : %d of %d", judged.size(), data.passages().size());
t.line("never relevant : %s", never);
}
assertEquals(Map.of("exact", 11L, "multi", 6L, "paraphrase", 13L), byCategory);
}
}
@@ -0,0 +1,33 @@
package com.ankurm.rageval;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.rageval.support.Transcript;
import java.util.List;
import org.junit.jupiter.api.Test;
/** The gate is only useful if it fails for the right reasons. This test runs it against a known-bad retriever and expects a failure. */
class GateCatchesRegressionTest {
private final Dataset data = Dataset.load();
private final Gate gate = Gate.fromClasspath();
@Test
void lettersOnlyTokenizerIsRejected() {
Report bad = Evaluator.evaluate(Retrievers.byName("bm25-lettersonly", data.passages()), data);
List<String> failures = gate.check(bad);
try (Transcript t = new Transcript("07-gate-catches-regression.txt", "The gate against bm25-lettersonly (a tokenizer that drops digits)")) {
failures.forEach(f -> t.line("FAIL %s", f));
t.line("%d violations", failures.size());
}
assertFalse(failures.isEmpty());
assertTrue(failures.stream().anyMatch(f -> f.startsWith("new miss@5: q02")), "the E-4012 question must be reported by name");
}
@Test
void goodRetrieverPasses() {
Report good = Evaluator.evaluate(Retrievers.byName("bm25", data.passages()), data);
assertTrue(gate.check(good).isEmpty());
}
}
@@ -0,0 +1,33 @@
package com.ankurm.rageval;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.rageval.support.Transcript;
import java.util.List;
import org.junit.jupiter.api.Test;
/**
* The build gate. Run it against another retriever to see it fail:
* {@code mvn test -Dtest=GoldenSetGateTest -Drageval.retriever=bm25-lettersonly}.
*/
class GoldenSetGateTest {
@Test
void retrievalHasNotRegressed() {
Dataset data = Dataset.load();
String name = Retrievers.selected();
Report report = Evaluator.evaluate(Retrievers.byName(name, data.passages()), data);
Gate gate = Gate.fromClasspath();
List<String> failures = gate.check(report);
// Only the default retriever writes the committed transcript; the failing demo is captured by scripts/ci-fail-demo.sh.
try (Transcript t = new Transcript(name.equals("bm25") ? "06-gate-pass.txt" : null, "Gate run for retriever '" + name + "'")) {
t.line("tolerance : %.2f", gate.tolerance());
t.line("overall MRR : %.3f", report.mean("mrr"));
t.line("overall nDCG@10: %.3f", report.mean("ndcg@10"));
t.line("misses@5 : %s", report.misses(5).stream().map(Report.QuestionResult::id).toList());
t.line("violations : %d", failures.size());
}
assertTrue(failures.isEmpty(), () -> "retrieval regression against baseline.properties:\n - " + String.join("\n - ", failures));
}
}
@@ -0,0 +1,46 @@
package com.ankurm.rageval;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.ankurm.rageval.support.Transcript;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
/** One ranked list worked by hand, then checked against the code. The arithmetic in the comments is the specification. */
class MetricsTest {
// The retriever returned these five, best first. Passages p01, p02 and p08 answer the question.
private final List<String> ranked = List.of("p03", "p01", "p07", "p02", "p09");
private final Map<String, Integer> grades = Map.of("p01", 2, "p02", 1, "p08", 1);
private final Set<String> relevant = grades.keySet();
@Test
void workedExample() {
// hit@1: p03 is not relevant -> 0. hit@2: p01 is in the top 2 -> 1.
assertEquals(0.0, Metrics.hitAtK(ranked, relevant, 1));
assertEquals(1.0, Metrics.hitAtK(ranked, relevant, 2));
// recall@5: p01 and p02 found, p08 not -> 2/3.
assertEquals(2.0 / 3, Metrics.recallAtK(ranked, relevant, 5), 1e-9);
// precision@5: 2 relevant of 5 retrieved -> 0.4.
assertEquals(0.4, Metrics.precisionAtK(ranked, relevant, 5), 1e-9);
// reciprocal rank: first relevant (p01) is at rank 2 -> 1/2.
assertEquals(0.5, Metrics.reciprocalRank(ranked, relevant), 1e-9);
// DCG@5 = (2^2-1)/log2(3) at rank 2 + (2^1-1)/log2(5) at rank 4 = 1.8928 + 0.4307 = 2.3235
// ideal = 3/log2(2) + 1/log2(3) + 1/log2(4) = 3 + 0.6309 + 0.5 = 4.1309 ; nDCG = 0.5625
assertEquals(0.5625, Metrics.ndcgAtK(ranked, grades, 5), 1e-3);
try (Transcript t = new Transcript("01-metric-worked-examples.txt", "One ranked list, every metric, worked by hand")) {
t.line("retrieved (best first) : %s", ranked);
t.line("relevant with grade : p01=2, p02=1, p08=1");
t.blank();
t.line("hit@1 = %.4f", Metrics.hitAtK(ranked, relevant, 1));
t.line("hit@2 = %.4f", Metrics.hitAtK(ranked, relevant, 2));
t.line("recall@5 = %.4f (2 of 3 relevant found)", Metrics.recallAtK(ranked, relevant, 5));
t.line("precision@5 = %.4f (2 relevant of 5 returned)", Metrics.precisionAtK(ranked, relevant, 5));
t.line("MRR = %.4f (first relevant at rank 2)", Metrics.reciprocalRank(ranked, relevant));
t.line("nDCG@5 = %.4f (DCG 2.3235 / ideal 4.1309)", Metrics.ndcgAtK(ranked, grades, 5));
}
}
}
@@ -0,0 +1,32 @@
package com.ankurm.rageval;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.ankurm.rageval.support.Transcript;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
/** An aggregate says the retriever is at 0.93 hit@5. This says which questions are in the other 7%, and why. */
class MissAnalysisTest {
private final Dataset data = Dataset.load();
@Test
void whereBm25Misses() {
Report report = Evaluator.evaluate(Retrievers.byName("bm25", data.passages()), data);
Map<String, String> text = data.passages().stream().collect(Collectors.toMap(Passage::id, Passage::text));
Map<String, GoldenQuestion> byId = data.questions().stream().collect(Collectors.toMap(GoldenQuestion::id, q -> q));
assertFalse(report.misses(5).isEmpty());
try (Transcript t = new Transcript("05-misses.txt", "bm25: every question with no relevant passage in the top 5")) {
for (Report.QuestionResult q : report.misses(5)) {
t.line("%s [%s] \"%s\"", q.id(), q.category(), q.query());
t.line(" returned : %s", q.ranked().subList(0, 5));
t.line(" wanted : %s", byId.get(q.id()).grades());
for (String id : byId.get(q.id()).relevantIds()) t.line(" %s says : %s", id, text.get(id));
t.line(" first returned says : %s", text.get(q.ranked().get(0)));
t.blank();
}
}
}
}
@@ -0,0 +1,61 @@
package com.ankurm.rageval;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.rageval.support.Transcript;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
/** The edge cases that make two correct-looking implementations disagree. Each one is pinned here. */
class PitfallsTest {
@Test
void edgeCases() {
Set<String> one = Set.of("p01");
Map<String, Integer> oneGrade = Map.of("p01", 2);
// 1. Two chunks of the same document in the top 5 must not count twice.
List<String> dupes = List.of("p01", "p01", "p01", "p02", "p03");
double precisionWithDupes = Metrics.precisionAtK(dupes, one, 5);
assertEquals(0.2, precisionWithDupes, 1e-9);
// 2. Precision@5 with one relevant passage can never exceed 0.2, however good the retriever is.
double perfectPrecision = Metrics.precisionAtK(List.of("p01", "p02", "p03", "p04", "p05"), one, 5);
assertEquals(0.2, perfectPrecision, 1e-9);
// 3. A list shorter than k is not padded and not an error; precision still divides by k.
double shortList = Metrics.precisionAtK(List.of("p01", "p02"), one, 5);
assertEquals(0.2, shortList, 1e-9);
// 4. No relevant passage: recall and nDCG are undefined, not zero. Averaging a 0 in would punish the retriever for the dataset.
assertTrue(Double.isNaN(Metrics.recallAtK(List.of("p01"), Set.of(), 5)));
assertTrue(Double.isNaN(Metrics.ndcgAtK(List.of("p01"), Map.of(), 5)));
// 5. MRR only looks at the first relevant passage: finding the second one earlier changes nothing.
Set<String> two = Set.of("p01", "p02");
double rrLate = Metrics.reciprocalRank(List.of("p09", "p01", "p02"), two);
double rrEarlier = Metrics.reciprocalRank(List.of("p09", "p01", "p08"), two);
assertEquals(rrLate, rrEarlier, 1e-9);
// 6. Order inside the top k matters to MRR and nDCG, not to recall@k.
Map<String, Integer> graded = Map.of("p07", 1, "p01", 2);
List<String> supportFirst = List.of("p07", "p01");
List<String> answerFirst = List.of("p01", "p07");
assertEquals(Metrics.recallAtK(supportFirst, graded.keySet(), 2), Metrics.recallAtK(answerFirst, graded.keySet(), 2));
assertTrue(Metrics.ndcgAtK(answerFirst, graded, 2) > Metrics.ndcgAtK(supportFirst, graded, 2));
try (Transcript t = new Transcript("02-pitfalls.txt", "Edge cases that change the number")) {
t.line("1 duplicates [p01 p01 p01 p02 p03], p01 relevant, precision@5 = %.2f (naive count would give 0.60)", precisionWithDupes);
t.line("2 precision cap perfect list, one relevant passage, precision@5 = %.2f", perfectPrecision);
t.line("3 short list 2 results, precision@5 = %.2f", shortList);
t.line("4 no relevant recall@5 = %s, nDCG@5 = %s", Metrics.recallAtK(List.of("p01"), Set.of(), 5), Metrics.ndcgAtK(List.of("p01"), Map.of(), 5));
t.line("5 MRR blind to the second hit: %.2f vs %.2f", rrLate, rrEarlier);
t.line("6 order, same recall@2 = %.2f:", Metrics.recallAtK(answerFirst, graded.keySet(), 2));
t.line(" support first nDCG@2 = %.4f, MRR = %.2f", Metrics.ndcgAtK(supportFirst, graded, 2), Metrics.reciprocalRank(supportFirst, graded.keySet()));
t.line(" answer first nDCG@2 = %.4f, MRR = %.2f", Metrics.ndcgAtK(answerFirst, graded, 2), Metrics.reciprocalRank(answerFirst, graded.keySet()));
}
}
}
@@ -0,0 +1,44 @@
package com.ankurm.rageval;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.rageval.support.Transcript;
import java.util.List;
import org.junit.jupiter.api.Test;
class RetrieverComparisonTest {
private final Dataset data = Dataset.load();
@Test
void compareAllRetrievers() {
List<Report> reports = Retrievers.NAMES.stream()
.map(n -> Evaluator.evaluate(Retrievers.byName(n, data.passages()), data)).toList();
Report bm25 = reports.get(0);
Report lettersOnly = reports.get(3);
try (Transcript t = new Transcript("03-retriever-comparison.txt", "Four retrievers, 30 questions, 40 passages")) {
t.line("%-18s %6s %6s %9s %10s %6s %8s", "retriever", "hit@1", "hit@5", "recall@5", "recall@10", "MRR", "nDCG@10");
for (Report r : reports) {
t.line("%-18s %6.3f %6.3f %9.3f %10.3f %6.3f %8.3f", r.retriever(), r.mean("hit@1"), r.mean("hit@5"),
r.mean("recall@5"), r.mean("recall@10"), r.mean("mrr"), r.mean("ndcg@10"));
}
t.blank();
t.line("MRR by question category");
t.line("%-18s %7s %11s %7s", "retriever", "exact", "paraphrase", "multi");
for (Report r : reports) {
t.line("%-18s %7.3f %11.3f %7.3f", r.retriever(), r.mean("mrr", "exact"), r.mean("mrr", "paraphrase"), r.mean("mrr", "multi"));
}
t.blank();
t.line("Questions with no relevant passage in the top 5");
for (Report r : reports) {
t.line("%-18s %s", r.retriever(), r.misses(5).stream().map(Report.QuestionResult::id).toList());
}
}
// Plain BM25 finds every question that is just a code or a number; the letters-only tokenizer does not.
assertEquals(1.0, bm25.mean("mrr", "exact"), 1e-9);
assertTrue(lettersOnly.mean("mrr", "exact") < bm25.mean("mrr", "exact"));
assertTrue(lettersOnly.mean("mrr") < bm25.mean("mrr"));
}
}
@@ -0,0 +1,49 @@
package com.ankurm.rageval.support;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Writes a numbered transcript under {@code output/} and echoes it to the console. Every console
* block quoted in the article comes out of one of these files verbatim. A null file name means
* "console only", which the gate test uses when it is run against a retriever other than the default.
*/
public final class Transcript implements AutoCloseable {
private final Path path;
private final StringWriter buffer = new StringWriter();
private final PrintWriter out = new PrintWriter(buffer);
public Transcript(String fileName, String title) {
this.path = fileName == null ? null : Path.of("output", fileName);
out.println("# " + title);
out.println();
}
public Transcript line(String format, Object... args) {
out.println(args.length == 0 ? format : String.format(format, args));
return this;
}
public Transcript blank() {
out.println();
return this;
}
@Override
public void close() {
out.flush();
try {
if (path != null) {
Files.createDirectories(path.getParent());
Files.writeString(path, buffer.toString());
}
} catch (IOException e) {
throw new IllegalStateException("could not write " + path, e);
}
System.out.print(buffer);
}
}