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,65 @@
package com.ankurm.rageval;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Okapi BM25 with the usual k1 = 1.2, b = 0.75 and the non-negative idf variant. */
public final class Bm25Retriever implements Retriever {
private final String name;
private final Tokenizer tokenizer;
private final List<Passage> passages;
private final List<Map<String, Integer>> termCounts = new ArrayList<>();
private final Map<String, Integer> docFreq = new HashMap<>();
private final double avgLen;
private final int[] lengths;
private static final double K1 = 1.2, B = 0.75;
public Bm25Retriever(String name, Tokenizer tokenizer, List<Passage> passages) {
this.name = name;
this.tokenizer = tokenizer;
this.passages = passages;
this.lengths = new int[passages.size()];
long total = 0;
for (int i = 0; i < passages.size(); i++) {
List<String> toks = tokenizer.tokens(passages.get(i).text());
Map<String, Integer> tf = new HashMap<>();
toks.forEach(t -> tf.merge(t, 1, Integer::sum));
tf.keySet().forEach(t -> docFreq.merge(t, 1, Integer::sum));
termCounts.add(tf);
lengths[i] = toks.size();
total += toks.size();
}
this.avgLen = (double) total / passages.size();
}
@Override
public String name() {
return name;
}
@Override
public List<String> retrieve(String query, int k) {
List<String> q = tokenizer.tokens(query);
int n = passages.size();
record Scored(String id, double score) {}
List<Scored> scored = new ArrayList<>();
for (int i = 0; i < n; i++) {
double s = 0;
for (String term : q) {
Integer f = termCounts.get(i).get(term);
if (f == null) continue;
int df = docFreq.get(term);
double idf = Math.log(1 + (n - df + 0.5) / (df + 0.5));
s += idf * (f * (K1 + 1)) / (f + K1 * (1 - B + B * lengths[i] / avgLen));
}
scored.add(new Scored(passages.get(i).id(), s));
}
// Stable on ties: equal scores keep corpus order, so a rerun is byte-identical.
return scored.stream().sorted(Comparator.comparingDouble(Scored::score).reversed())
.limit(k).map(Scored::id).toList();
}
}
@@ -0,0 +1,40 @@
package com.ankurm.rageval;
import java.util.Arrays;
import java.util.Random;
/**
* Paired bootstrap over questions: resample the question set with replacement, recompute the mean
* difference between two retrievers each time, and read the 95% interval off the sorted differences.
* It answers "if I had written a different 30 questions, would B still beat A?".
*/
public final class Bootstrap {
public record Interval(double meanDifference, double low, double high) {
public boolean excludesZero() {
return low > 0 || high < 0;
}
}
private Bootstrap() {}
/** 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]);
}
}
@@ -0,0 +1,40 @@
package com.ankurm.rageval;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Loads {@code corpus.tsv} and {@code golden.tsv} from the classpath. Plain tab-separated text, so it diffs well in review. */
public record Dataset(List<Passage> passages, List<GoldenQuestion> questions) {
public static Dataset load() {
List<Passage> passages = new ArrayList<>();
for (String line : read("/corpus.tsv")) {
String[] f = line.split("\t", 2);
passages.add(new Passage(f[0], f[1]));
}
List<GoldenQuestion> questions = new ArrayList<>();
for (String line : read("/golden.tsv")) {
String[] f = line.split("\t", 4);
Map<String, Integer> grades = new LinkedHashMap<>();
for (String pair : f[3].split(",")) {
String[] g = pair.split(":");
grades.put(g[0], Integer.parseInt(g[1]));
}
questions.add(new GoldenQuestion(f[0], f[1], f[2], grades));
}
return new Dataset(List.copyOf(passages), List.copyOf(questions));
}
private static List<String> read(String resource) {
try (var in = Dataset.class.getResourceAsStream(resource)) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8).lines().filter(l -> !l.isBlank()).toList();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,29 @@
package com.ankurm.rageval;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Runs a retriever over a golden dataset and computes every metric for every question. */
public final class Evaluator {
public static final int DEPTH = 10;
private Evaluator() {}
public static Report evaluate(Retriever retriever, Dataset data) {
List<Report.QuestionResult> results = data.questions().stream().map(q -> {
List<String> ranked = retriever.retrieve(q.query(), DEPTH);
Map<String, Double> s = new LinkedHashMap<>();
for (int k : new int[] {1, 3, 5, 10}) {
s.put("hit@" + k, Metrics.hitAtK(ranked, q.relevantIds(), k));
s.put("recall@" + k, Metrics.recallAtK(ranked, q.relevantIds(), k));
}
s.put("precision@5", Metrics.precisionAtK(ranked, q.relevantIds(), 5));
s.put("mrr", Metrics.reciprocalRank(ranked, q.relevantIds()));
s.put("ndcg@10", Metrics.ndcgAtK(ranked, q.grades(), 10));
return new Report.QuestionResult(q.id(), q.category(), q.query(), ranked, s);
}).toList();
return new Report(retriever.name(), results);
}
}
@@ -0,0 +1,91 @@
package com.ankurm.rageval;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
/**
* The CI check. A baseline file holds the scores the current retriever earned; the gate fails when a
* score drops by more than the tolerance, and when any question starts missing in the top 5 that did
* not miss in the baseline.
*
* <p>The tolerance is not decoration: with 30 questions one question moving one rank changes MRR by
* up to 0.033, so a tolerance below that makes the gate flaky for reasons that are not regressions.
*/
public final class Gate {
public static final String[] TRACKED = {"hit@1", "hit@5", "recall@5", "recall@10", "mrr", "ndcg@10"};
private final Properties baseline;
public Gate(Properties baseline) {
this.baseline = baseline;
}
public static Gate fromClasspath() {
Properties p = new Properties();
try (InputStream in = Gate.class.getResourceAsStream("/baseline.properties")) {
p.load(in);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return new Gate(p);
}
public double tolerance() {
return Double.parseDouble(baseline.getProperty("tolerance"));
}
/** 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;
}
private void check(List<String> failures, String label, double actual, String key, double tol) {
double floor = Double.parseDouble(baseline.getProperty(key)) - tol;
if (actual < floor) {
failures.add(String.format("%s = %.3f, below baseline %s - %.2f = %.3f",
label, actual, baseline.getProperty(key), tol, floor));
}
}
/** Renders a baseline file for a report, with the given tolerance. */
public static String renderBaseline(Report report, double tolerance) {
TreeMap<String, String> lines = new TreeMap<>();
for (String metric : TRACKED) {
lines.put("overall." + metric, String.format("%.3f", report.mean(metric)));
for (String cat : report.categories()) {
lines.put(cat + "." + metric, String.format("%.3f", report.mean(metric, cat)));
}
}
StringBuilder sb = new StringBuilder("# Written by WriteBaseline for retriever '" + report.retriever() + "'. Review the diff like code.\n");
sb.append("tolerance=").append(tolerance).append('\n');
sb.append("knownMisses@5=").append(report.misses(5).stream().map(Report.QuestionResult::id)
.collect(Collectors.joining(","))).append('\n');
lines.forEach((k, v) -> sb.append(k).append('=').append(v).append('\n'));
return sb.toString();
}
}
@@ -0,0 +1,18 @@
package com.ankurm.rageval;
import java.util.Map;
import java.util.Set;
/**
* One row of the golden dataset: a question, the passages that answer it, and how well each one does.
*
* <p>{@code grades} maps passage id to a relevance grade: 2 = answers the question on its own,
* 1 = useful supporting context. Passages not listed are grade 0. Binary metrics (hit, recall,
* precision, MRR) treat every listed passage as relevant; nDCG uses the grades.
*/
public record GoldenQuestion(String id, String category, String query, Map<String, Integer> grades) {
public Set<String> relevantIds() {
return grades.keySet();
}
}
@@ -0,0 +1,62 @@
package com.ankurm.rageval;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* A dense-vector stand-in: every token becomes character trigrams, each trigram is hashed into one of
* 512 dimensions, and passages are ranked by cosine similarity.
*
* <p><strong>This is not a neural embedding model.</strong> It captures spelling overlap ("restore" and
* "restoring"), not meaning, so it cannot connect "died" to "fails". It exists so the evaluation code
* has a second, differently-behaved retriever to compare with BM25 without downloading a model. To
* evaluate a real embedding model, implement {@link Retriever} around it; nothing else changes.
*/
public final class HashedNgramRetriever implements Retriever {
private static final int DIMS = 512;
private final Tokenizer tokenizer = new Tokenizer(Tokenizer.Mode.WORDS);
private final List<Passage> passages;
private final List<double[]> vectors = new ArrayList<>();
public HashedNgramRetriever(List<Passage> passages) {
this.passages = passages;
passages.forEach(p -> vectors.add(embed(p.text())));
}
@Override
public String name() {
return "ngram";
}
double[] embed(String text) {
double[] v = new double[DIMS];
for (String t : tokenizer.tokens(text)) {
String padded = "#" + t + "#";
for (int i = 0; i + 3 <= padded.length(); i++) {
v[Math.floorMod(padded.substring(i, i + 3).hashCode(), DIMS)] += 1;
}
}
double norm = 0;
for (double x : v) norm += x * x;
norm = Math.sqrt(norm);
if (norm > 0) for (int i = 0; i < DIMS; i++) v[i] /= norm;
return v;
}
@Override
public List<String> retrieve(String query, int k) {
double[] q = embed(query);
record Scored(String id, double score) {}
List<Scored> scored = new ArrayList<>();
for (int i = 0; i < passages.size(); i++) {
double dot = 0;
double[] v = vectors.get(i);
for (int d = 0; d < DIMS; d++) dot += q[d] * v[d];
scored.add(new Scored(passages.get(i).id(), dot));
}
return scored.stream().sorted(Comparator.comparingDouble(Scored::score).reversed())
.limit(k).map(Scored::id).toList();
}
}
@@ -0,0 +1,82 @@
package com.ankurm.rageval;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Rank-based retrieval metrics. Every method takes the ranked list of passage ids a retriever returned
* (best first) and the ground truth, and is a pure function with no dependencies.
*
* <p>Conventions, all pinned by {@code MetricsTest}:
* <ul>
* <li>Rank is 1-based; {@code k} cuts the list to its first k entries.</li>
* <li>Duplicates are removed first (first occurrence wins), so two chunks of one document cannot
* count twice.</li>
* <li>A list shorter than k is not padded: precision still divides by k.</li>
* <li>With no relevant passages, recall and nDCG are undefined and return {@code NaN}.</li>
* </ul>
*/
public final class Metrics {
private Metrics() {}
/** 1 if any relevant passage is in the top k, else 0. */
public static double hitAtK(List<String> ranked, Set<String> relevant, int k) {
return top(ranked, k).stream().anyMatch(relevant::contains) ? 1 : 0;
}
/** 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();
}
/** Relevant passages in the top k, divided by k (not by the list length). */
public static double precisionAtK(List<String> ranked, Set<String> relevant, int k) {
long found = top(ranked, k).stream().filter(relevant::contains).count();
return (double) found / k;
}
/** 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;
}
/**
* nDCG@k with exponential gain: DCG = sum (2^grade - 1) / log2(rank + 1), divided by the DCG of the
* best possible ordering of the graded passages.
*/
public static double ndcgAtK(List<String> ranked, Map<String, Integer> grades, int k) {
if (grades.isEmpty()) return Double.NaN;
double dcg = 0;
List<String> list = top(ranked, k);
for (int i = 0; i < list.size(); i++) {
dcg += gain(grades.getOrDefault(list.get(i), 0), i + 1);
}
List<Integer> ideal = grades.values().stream().sorted(java.util.Comparator.reverseOrder()).toList();
double idcg = 0;
for (int i = 0; i < Math.min(k, ideal.size()); i++) idcg += gain(ideal.get(i), i + 1);
return dcg / idcg;
}
private static double gain(int grade, int rank) {
return (Math.pow(2, grade) - 1) / (Math.log(rank + 1) / Math.log(2));
}
static List<String> distinct(List<String> ranked) {
return new ArrayList<>(new LinkedHashSet<>(ranked));
}
static List<String> top(List<String> ranked, int k) {
List<String> list = distinct(ranked);
return list.subList(0, Math.min(k, list.size()));
}
}
@@ -0,0 +1,4 @@
package com.ankurm.rageval;
/** One retrievable unit of the corpus. In a real system this is a chunk; here it is a short passage. */
public record Passage(String id, String text) {}
@@ -0,0 +1,36 @@
package com.ankurm.rageval;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
/** The outcome of running one retriever over the whole golden set. */
public record Report(String retriever, List<QuestionResult> results) {
/** Per-question scores. Keys are {@code hit@1}, {@code recall@5}, {@code mrr}, {@code ndcg@10} and so on. */
public record QuestionResult(String id, String category, String query, List<String> ranked, Map<String, Double> scores) {}
/** Macro average: every question counts once, whatever number of relevant passages it has. */
public double mean(String metric) {
return results.stream().map(r -> r.scores().get(metric)).filter(v -> !Double.isNaN(v))
.mapToDouble(Double::doubleValue).average().orElse(Double.NaN);
}
public double mean(String metric, String category) {
return results.stream().filter(r -> r.category().equals(category)).map(r -> r.scores().get(metric))
.filter(v -> !Double.isNaN(v)).mapToDouble(Double::doubleValue).average().orElse(Double.NaN);
}
public double[] scores(String metric) {
return results.stream().mapToDouble(r -> r.scores().get(metric)).toArray();
}
public List<String> categories() {
return List.copyOf(new TreeSet<>(results.stream().map(QuestionResult::category).toList()));
}
/** Questions with no relevant passage in the top k. */
public List<QuestionResult> misses(int k) {
return results.stream().filter(r -> r.scores().get("hit@" + k) == 0).toList();
}
}
@@ -0,0 +1,11 @@
package com.ankurm.rageval;
import java.util.List;
/** The one seam the evaluation needs: a query in, passage ids out, best first. */
public interface Retriever {
String name();
List<String> retrieve(String query, int k);
}
@@ -0,0 +1,28 @@
package com.ankurm.rageval;
import java.util.List;
/** Builds the retrievers by name so a script or a CI job can pick one with {@code -Drageval.retriever=...}. */
public final class Retrievers {
public static final List<String> NAMES = List.of("bm25", "ngram", "hybrid", "bm25-lettersonly");
private Retrievers() {}
public static Retriever byName(String name, List<Passage> passages) {
Bm25Retriever bm25 = new Bm25Retriever("bm25", new Tokenizer(Tokenizer.Mode.WORDS), passages);
return switch (name) {
case "bm25" -> bm25;
case "ngram" -> new HashedNgramRetriever(passages);
case "hybrid" -> new RrfRetriever("hybrid", bm25, new HashedNgramRetriever(passages));
case "bm25-lettersonly" ->
new Bm25Retriever("bm25-lettersonly", new Tokenizer(Tokenizer.Mode.LETTERS_ONLY), passages);
default -> throw new IllegalArgumentException("unknown retriever '" + name + "', expected one of " + NAMES);
};
}
/** The retriever the build gate runs against: {@code -Drageval.retriever=...}, default {@code bm25}. */
public static String selected() {
return System.getProperty("rageval.retriever", "bm25");
}
}
@@ -0,0 +1,38 @@
package com.ankurm.rageval;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** Reciprocal Rank Fusion: score(d) = sum over retrievers of 1 / (60 + rank). Rank is 1-based. */
public final class RrfRetriever implements Retriever {
private static final int RRF_K = 60;
private static final int DEPTH = 50;
private final String name;
private final List<Retriever> parts;
public RrfRetriever(String name, Retriever... parts) {
this.name = name;
this.parts = List.of(parts);
}
@Override
public String name() {
return name;
}
@Override
public List<String> retrieve(String query, int k) {
Map<String, Double> fused = new LinkedHashMap<>();
for (Retriever r : parts) {
List<String> ranked = r.retrieve(query, DEPTH);
for (int i = 0; i < ranked.size(); i++) {
fused.merge(ranked.get(i), 1.0 / (RRF_K + i + 1), Double::sum);
}
}
return fused.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue().reversed())
.limit(k).map(Map.Entry::getKey).toList();
}
}
@@ -0,0 +1,50 @@
package com.ankurm.rageval;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Lower-cases, splits, drops stop words and applies a light suffix stemmer.
*
* <p>{@link Mode#LETTERS_ONLY} is the regression this module uses to demonstrate the build gate:
* it splits on anything that is not a letter, so "VPN-619" becomes "vpn" and "E-4012" disappears.
* It looks like a harmless tidy-up of a regex and silently removes every error code from the index.
*/
public final class Tokenizer {
public enum Mode { WORDS, LETTERS_ONLY }
private static final Pattern NON_ALNUM = Pattern.compile("[^a-z0-9]+");
private static final Pattern NON_LETTER = Pattern.compile("[^a-z]+");
private static final Set<String> STOP = Set.of(
"a", "an", "the", "is", "are", "was", "be", "to", "of", "in", "on", "at", "for", "and", "or", "it", "its",
"do", "does", "how", "what", "which", "when", "can", "i", "we", "my", "me", "you", "your", "with", "that",
"this", "from", "by", "as", "if", "not", "no", "has", "have", "had", "than", "then", "so");
private final Mode mode;
public Tokenizer(Mode mode) {
this.mode = mode;
}
public List<String> tokens(String text) {
Pattern splitter = mode == Mode.WORDS ? NON_ALNUM : NON_LETTER;
List<String> out = new ArrayList<>();
for (String raw : splitter.split(text.toLowerCase())) {
if (raw.length() < 2 || STOP.contains(raw)) continue;
out.add(stem(raw));
}
return out;
}
/** Deliberately small: enough to match "backups"/"backup" and "failed"/"fails", not a Porter stemmer. */
static String stem(String w) {
if (w.length() > 5 && w.endsWith("ing")) return w.substring(0, w.length() - 3);
if (w.length() > 4 && w.endsWith("ed")) return w.substring(0, w.length() - 2);
if (w.length() > 4 && w.endsWith("es")) return w.substring(0, w.length() - 2);
if (w.length() > 3 && w.endsWith("s") && !w.endsWith("ss")) return w.substring(0, w.length() - 1);
return w;
}
}
@@ -0,0 +1,15 @@
package com.ankurm.rageval;
import java.nio.file.Files;
import java.nio.file.Path;
/** {@code java -cp target/classes com.ankurm.rageval.WriteBaseline hybrid src/test/resources/baseline.properties 0.04} */
public final class WriteBaseline {
public static void main(String[] args) throws Exception {
Dataset data = Dataset.load();
Report report = Evaluator.evaluate(Retrievers.byName(args[0], data.passages()), data);
Files.writeString(Path.of(args[1]), Gate.renderBaseline(report, Double.parseDouble(args[2])));
System.out.println("wrote " + args[1]);
}
}