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
+1
View File
@@ -38,5 +38,6 @@ Runnable companion code for the Spring AI articles on [ankurm.com](https://ankur
| [`chat-ui-htmx/`](chat-ui-htmx) | A streaming chat page with no JavaScript of our own: htmx and its SSE extension (vendored) post the message and append each token from a `Flux<ServerSentEvent<String>>` over `ChatClient` with `MessageChatMemoryAdvisor` keyed by the HTTP session. Measured traps: EventSource strips one leading space per data line, model text must be HTML-escaped, a cancelled stream left the upstream connection open in 7 of 8 runs until an OkHttp interceptor made it `call.cancel()` (closed in 8 of 8 after), and the SDK's push source ignores back-pressure (`limitRate` changes nothing; a bounded buffer does). Checked in headless Chromium. **The model is a stub OpenAI-compatible SSE server I wrote, not a language model; no real provider was run.** Spring Boot 4.1.2, Spring AI 2.0.2, htmx 2.0.11, Java 25. | [Streaming AI Chat UI with Spring AI, SSE and htmx (No React Needed)](https://ankurm.com/spring-ai-streaming-chat-ui-sse-htmx/) |
| [`tool-confirmation/`](tool-confirmation) | Human-in-the-loop tool calls in Spring AI 2.1: `@Tool(requiresConfirmation = true)`, `ToolCallConfirmationPolicy` (by metadata, by name, by argument), the pause and resume with `ToolCallDecisions`, deny messages, and what the application must add itself: a server-side pause store, an approver check, a replay guard (one winner among 16 concurrent approvers), an audit log, and an approver page over SSE and htmx with model-chosen arguments HTML-escaped. Also measured: an open SSE stream holds up Spring Boot's graceful shutdown. **The model is a scripted `ChatModel`, not a language model; the htmx page was not opened in a browser.** Spring Boot 4.1.3, Spring AI 2.1.0, Java 25. | [Human-in-the-Loop Tool Calls in Spring AI 2.1](https://ankurm.com/spring-ai-2-1-human-in-the-loop-tool-call-confirmation/) |
| [`prompt-caching/`](prompt-caching) | Provider-side prompt caching on Spring AI 2.1: where each `AnthropicCacheStrategy` puts `cache_control` on the real request, what a hit, a miss and a write look like in `Usage` (`getPromptTokens()` now includes the cached tokens, which it did not on 2.0.1), what one changed word invalidates, 5-minute and 1-hour lifetimes, the 20-block lookback in a long chat, OpenAI's automatic caching with `prompt_cache_key`, and a cost table (a 5-minute entry that expires between requests makes caching cost more than none). **No vendor API called: the vendors are a local server that applies their documented rules; tokens are characters / 4 and prices are list prices read on 2026-11-24.** Spring Boot 4.2.0, Spring AI 2.1.0, Java 25. | [Prompt Caching in Spring AI](https://ankurm.com/spring-ai-prompt-caching-anthropic-openai-cost-table/) |
| [`rag-eval/`](rag-eval) | Retrieval metrics in plain Java: hit@k, recall@k, precision@k, MRR and nDCG@k with their edge cases (duplicate chunks, short lists, no relevant passage) pinned by tests, a 30-question golden dataset with graded judgements over a 40-passage runbook, a paired bootstrap (no difference between the four retrievers had an interval that excluded zero), and a JUnit gate with a baseline, a tolerance and a no-new-misses rule that fails a build on a tokenizer that drops digits. **The retrievers are BM25, a hashed-trigram vector that is not a neural embedding, and their fusion; the corpus and questions are synthetic. No model was used.** Java 25, JUnit 6.1.3, no Spring. | [Measuring RAG Retrieval Quality in Java: recall@k, MRR, nDCG and a Golden Dataset in JUnit](https://ankurm.com/rag-retrieval-evaluation-java-recall-mrr-ndcg-golden-dataset/) |
Upgrading from Spring AI 1.x: [migration guide](https://ankurm.com/spring-ai-1-to-2-migration-guide/).
+1
View File
@@ -0,0 +1 @@
target/
+58
View File
@@ -0,0 +1,58 @@
# rag-eval
Companion code for [Measuring RAG Retrieval Quality in Java: recall@k, MRR, nDCG and a Golden Dataset in JUnit](https://ankurm.com/rag-retrieval-evaluation-java-recall-mrr-ndcg-golden-dataset/), part of the [Spring AI series](../README.md) on ankurm.com.
Retrieval metrics in plain Java (recall@k, precision@k, hit@k, MRR, nDCG@k), a 30-question golden dataset over a 40-passage support runbook, a paired bootstrap for "is this change real?", and a JUnit gate that fails the build on a retrieval regression. Everything the article explains is in this module; the article carries the explanations in expandable sections, so there is no separate docs folder.
**No model and no network are used.** The retrievers are BM25, a hashed character-trigram vector (`HashedNgramRetriever`, a stand-in that captures spelling overlap and **not** meaning, not a neural embedding) and Reciprocal Rank Fusion of the two. The corpus and the questions are synthetic and were written for this module, so the scores say how the *code* behaves, not how any real embedding model or any real corpus would score. To evaluate a real retriever, implement `Retriever` around it; nothing else changes.
## Versions
| Component | Version |
|---|---|
| Java | 25 (LTS) |
| JUnit | 6.1.3 (latest GA on Maven Central on 2026-11-25) |
| Maven Surefire | 3.5.4 |
No Spring, no other dependency.
## Quickstart
```bash
scripts/run-all.sh # 10 tests; regenerates output/00 .. 08
mvn test # the gate on its own: passes
mvn test -Dtest=GoldenSetGateTest -Drageval.retriever=bm25-lettersonly # the gate failing, on purpose
scripts/write-baseline.sh bm25 0.04 # re-lock the baseline after an improvement you want to keep
```
Two consecutive runs produce byte-identical files.
## What's here
| File | What it is |
|---|---|
| [`Metrics.java`](src/main/java/com/ankurm/rageval/Metrics.java) | hit@k, recall@k, precision@k, reciprocal rank and nDCG@k as pure functions, with the edge-case rules in the Javadoc |
| [`Evaluator.java`](src/main/java/com/ankurm/rageval/Evaluator.java), [`Report.java`](src/main/java/com/ankurm/rageval/Report.java) | Run a `Retriever` over the golden set; per-question scores, macro means, per-category means, misses |
| [`Bootstrap.java`](src/main/java/com/ankurm/rageval/Bootstrap.java) | Paired bootstrap over questions: a 95% interval for the difference between two retrievers |
| [`Gate.java`](src/main/java/com/ankurm/rageval/Gate.java) | The CI check: a baseline with a tolerance, plus "no new question may miss in the top 5" |
| [`Bm25Retriever.java`](src/main/java/com/ankurm/rageval/Bm25Retriever.java), [`HashedNgramRetriever.java`](src/main/java/com/ankurm/rageval/HashedNgramRetriever.java), [`RrfRetriever.java`](src/main/java/com/ankurm/rageval/RrfRetriever.java), [`Tokenizer.java`](src/main/java/com/ankurm/rageval/Tokenizer.java) | The retrievers under test, and the tokenizer whose `LETTERS_ONLY` mode is the regression the gate is shown catching |
| [`corpus.tsv`](src/main/resources/corpus.tsv), [`golden.tsv`](src/main/resources/golden.tsv) | The passages and the judged questions (grade 2 answers it alone, grade 1 is supporting context) |
| [`baseline.properties`](src/test/resources/baseline.properties) | The scores the gate compares against, written by `WriteBaseline` |
## Output files
| File | Written by |
|---|---|
| [`00-dataset.txt`](output/00-dataset.txt) | `DatasetTest` (also validates every judgement points at a real passage) |
| [`01-metric-worked-examples.txt`](output/01-metric-worked-examples.txt) | `MetricsTest` |
| [`02-pitfalls.txt`](output/02-pitfalls.txt) | `PitfallsTest` |
| [`03-retriever-comparison.txt`](output/03-retriever-comparison.txt) | `RetrieverComparisonTest` |
| [`04-bootstrap.txt`](output/04-bootstrap.txt) | `BootstrapTest` |
| [`05-misses.txt`](output/05-misses.txt) | `MissAnalysisTest` |
| [`06-gate-pass.txt`](output/06-gate-pass.txt) | `GoldenSetGateTest` |
| [`07-gate-catches-regression.txt`](output/07-gate-catches-regression.txt) | `GateCatchesRegressionTest` |
| [`08-ci-failure.txt`](output/08-ci-failure.txt) | `scripts/ci-fail-demo.sh`, the recorded output of a failing gate |
## Limits
30 questions is small: one question moving one rank moves MRR by up to 0.033, and no difference between the retrievers here has a bootstrap interval that excludes zero. Treat the scores as a demonstration of the method, not a ranking of the retrievers.
+10
View File
@@ -0,0 +1,10 @@
# Golden dataset: what is in it
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]
@@ -0,0 +1,11 @@
# One ranked list, every metric, worked by hand
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)
+10
View File
@@ -0,0 +1,10 @@
# Edge cases that change the number
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
@@ -0,0 +1,20 @@
# Four retrievers, 30 questions, 40 passages
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]
+12
View File
@@ -0,0 +1,12 @@
# Paired bootstrap, 10,000 resamples of the 30 questions, seed 42
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
+14
View File
@@ -0,0 +1,14 @@
# bm25: every question with no relevant passage in the top 5
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.
+7
View File
@@ -0,0 +1,7 @@
# Gate run for retriever 'bm25'
tolerance : 0.04
overall MRR : 0.814
overall nDCG@10: 0.798
misses@5 : [q22, q24]
violations : 0
@@ -0,0 +1,16 @@
# The gate against bm25-lettersonly (a tokenizer that drops digits)
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
+47
View File
@@ -0,0 +1,47 @@
# mvn test -Dtest=GoldenSetGateTest -Drageval.retriever=bm25-lettersonly
# 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
org.opentest4j.AssertionFailedError:
retrieval regression against baseline.properties:
- overall hit@1 = 0.667, below baseline 0.733 - 0.04 = 0.693
- exact hit@1 = 0.818, below baseline 1.000 - 0.04 = 0.960
- overall hit@5 = 0.867, below baseline 0.933 - 0.04 = 0.893
- exact hit@5 = 0.818, below baseline 1.000 - 0.04 = 0.960
- overall recall@5 = 0.800, below baseline 0.867 - 0.04 = 0.827
- exact recall@5 = 0.818, below baseline 1.000 - 0.04 = 0.960
- exact recall@10 = 0.909, below baseline 1.000 - 0.04 = 0.960
- overall mrr = 0.751, below baseline 0.814 - 0.04 = 0.774
- exact mrr = 0.828, below baseline 1.000 - 0.04 = 0.960
- overall ndcg@10 = 0.741, below baseline 0.798 - 0.04 = 0.758
- exact ndcg@10 = 0.846, below baseline 1.000 - 0.04 = 0.960
- new miss@5: q02 "E-4012" (relevant not in top 5, got [p01, p02, p03, p04, p05])
- new miss@5: q03 "E-5003" (relevant not in top 5, got [p01, p02, p03, p04, p05]) ==> expected: <true> but was: <false>
[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR] GoldenSetGateTest.retrievalHasNotRegressed:31 retrieval regression against baseline.properties:
- overall hit@1 = 0.667, below baseline 0.733 - 0.04 = 0.693
- exact hit@1 = 0.818, below baseline 1.000 - 0.04 = 0.960
- overall hit@5 = 0.867, below baseline 0.933 - 0.04 = 0.893
- exact hit@5 = 0.818, below baseline 1.000 - 0.04 = 0.960
- overall recall@5 = 0.800, below baseline 0.867 - 0.04 = 0.827
- exact recall@5 = 0.818, below baseline 1.000 - 0.04 = 0.960
- exact recall@10 = 0.909, below baseline 1.000 - 0.04 = 0.960
- overall mrr = 0.751, below baseline 0.814 - 0.04 = 0.774
- exact mrr = 0.828, below baseline 1.000 - 0.04 = 0.960
- overall ndcg@10 = 0.741, below baseline 0.798 - 0.04 = 0.758
- exact ndcg@10 = 0.846, below baseline 1.000 - 0.04 = 0.960
- new miss@5: q02 "E-4012" (relevant not in top 5, got [p01, p02, p03, p04, p05])
- new miss@5: q03 "E-5003" (relevant not in top 5, got [p01, p02, p03, p04, p05]) ==> expected: <true> but was: <false>
[INFO]
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD FAILURE
exit status of mvn: non-zero (see BUILD FAILURE above)
+59
View File
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm</groupId>
<artifactId>rag-eval</artifactId>
<version>1.0.0</version>
<name>rag-eval</name>
<description>Measuring RAG retrieval quality in plain Java: recall@k, precision@k, MRR and nDCG@k over a golden dataset, a paired bootstrap for "is this change real?", and a JUnit gate that fails the build on a retrieval regression.</description>
<properties>
<java.version>25</java.version>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Latest GA on Maven Central on 2026-11-25. -->
<junit.version>6.1.3</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- No Spring, no model, no network: the metrics and the retrievers are plain Java. -->
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
<configuration>
<argLine>-Duser.timezone=UTC -Dstdout.encoding=UTF-8 -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
# Runs the gate against the broken tokenizer and records what a failing CI job prints.
set -uo pipefail
cd "$(dirname "$0")/.."
{
echo "# mvn test -Dtest=GoldenSetGateTest -Drageval.retriever=bm25-lettersonly"
echo
mvn -B test -Dtest=GoldenSetGateTest -Drageval.retriever=bm25-lettersonly 2>&1 \
| grep -v -E "Picked up|^WARNING|^\[INFO\] (Download|Copying|Using|---|Nothing|Changes|Compiling)|Progress|^$" \
| sed -n '/Gate run/,/BUILD FAILURE/p' | grep -v -E "^\s+at |Time elapsed|^\[ERROR\] *$|Help 1|re-run Maven|full stack|For more information|-e switch|-X switch|^\[ERROR\] *\[Help"
echo
echo "exit status of mvn: non-zero (see BUILD FAILURE above)"
} > output/08-ci-failure.txt
cat output/08-ci-failure.txt
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Regenerates every file under output/. 00-07 are written by the test suite itself through the Transcript
# helper; 08 is the recorded output of a deliberately failing gate. No Docker, database, model or API key.
set -euo pipefail
cd "$(dirname "$0")/.."
rm -rf target
mvn -q -B test 2>&1 | grep -E "Tests run:|BUILD|FAIL" || true
scripts/ci-fail-demo.sh > /dev/null
ls output
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# Rewrites src/test/resources/baseline.properties from the current retriever. Run it on purpose, after an
# improvement you want to lock in, and review the diff like code. Tolerance 0.04 is a little more than one
# question moving one rank on 30 questions.
set -euo pipefail
cd "$(dirname "$0")/.."
mvn -q -B compile 2>&1 | grep -E "ERROR" || true
java -cp target/classes com.ankurm.rageval.WriteBaseline "${1:-bm25}" src/test/resources/baseline.properties "${2:-0.04}" 2>&1 | grep -v Picked
@@ -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]);
}
}
+40
View File
@@ -0,0 +1,40 @@
p01 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.
p02 Resetting two-factor authentication requires a helpdesk ticket. An agent verifies your identity by video call before removing the registered authenticator.
p03 After five failed sign-in attempts the account is locked for 15 minutes. Locked accounts unlock automatically and no ticket is needed.
p04 On Windows, install the VPN client from the software portal, import the profile file and connect to the gateway vpn-eu.example.net. Error VPN-619 means the profile has expired.
p05 On macOS the VPN client needs its system extension approved in System Settings under Privacy and Security before the first connection. Without approval the tunnel never starts.
p06 Split tunnelling sends only corporate subnets through the VPN. Internet traffic uses your local connection, which keeps video calls fast.
p07 Production databases are backed up nightly at 02:00 UTC and retained for 35 days. Weekly full backups are kept for one year.
p08 To restore a database, open a restore request naming the backup timestamp and the target instance. A restore into the production instance needs approval from the data owner.
p09 Error E-4012 during a backup means the snapshot volume ran out of space. Expand the volume or delete expired snapshots, then rerun the job.
p10 Deployments to production run through the release pipeline. A change needs one approving review and a green build before the deploy button is enabled.
p11 To roll back a release, redeploy the previous tagged version from the pipeline. Database migrations are not reverted automatically.
p12 No production deployments happen during a change freeze, which is announced in the engineering channel. Emergency fixes need director approval.
p13 If the primary database fails, the replica is promoted automatically within about 60 seconds. Applications reconnect through the cluster endpoint, not the instance address.
p14 Error E-5003, too many connections, means the pool exceeds the server limit of 200. Reduce the pool size per instance or add a connection pooler.
p15 Replica lag above 30 seconds raises an alert. Long-running reports on the replica are the usual cause; move them to the analytics cluster.
p16 TLS certificates are issued for 90 days and renewed automatically 30 days before expiry. A renewal failure alert means the DNS challenge record is missing.
p17 Mobile apps pin the intermediate certificate. Changing the certificate authority requires an app release before the switch.
p18 The public API allows 600 requests per minute per key. Requests beyond that receive HTTP 429 with a Retry-After header.
p19 To raise a rate limit, file a request with the expected traffic and the business reason. Increases above 3000 requests per minute need architecture review.
p20 API keys should be rotated every 90 days. Rotation creates a second key so clients can switch without downtime, and the old key is revoked after 7 days.
p21 Invoices are generated on the first day of each month and emailed to the billing contact. Payment terms are 30 days.
p22 Refunds for annual plans are prorated by unused full months. Monthly plans are not refunded.
p23 Upgrading a plan takes effect immediately and the price difference is prorated for the rest of the billing period.
p24 The on-call engineer acknowledges a page within 5 minutes. With no acknowledgement the page escalates to the secondary and then to the engineering manager.
p25 Sev1 means a customer-facing outage or data loss, Sev2 is major degradation and Sev3 is minor impact with a workaround. Sev1 requires a status page update within 15 minutes.
p26 A blameless postmortem is written within five working days of a Sev1 or Sev2 incident and reviewed in the weekly operations meeting.
p27 Application logs are kept hot for 14 days and archived for one year. Audit logs are kept for seven years.
p28 Do not log email addresses, card numbers or access tokens. The log pipeline masks card numbers, but other personal data passes through unchanged.
p29 Customers can request an export of their personal data. The export is produced within 30 days and delivered as a zip of JSON files.
p30 Deleting an account removes personal data within 30 days. Backups age out on their normal schedule, so deleted data can persist in backups for up to 35 days.
p31 New laptops are ordered through the IT portal. Delivery takes five working days and developers can choose between a 14-inch and a 16-inch model.
p32 Report a lost or stolen laptop to security immediately. The device is wiped remotely and disk encryption makes the data unreadable.
p33 Expenses under 50 euros need no receipt. Larger expenses require a receipt uploaded within 30 days.
p34 Annual leave requests are submitted in the HR system and approved by your manager. Leave of more than ten consecutive days also needs approval from the department head.
p35 Feature flags are managed in the flag console. A flag must have an owner and an expiry date, and flags past their expiry are reported weekly.
p36 Canary releases send 5 percent of traffic to the new version for 30 minutes. If the error rate rises above 1 percent the pipeline aborts the rollout.
p37 Messages that fail processing five times go to the dead-letter queue. Inspect the dead-letter queue daily; messages are deleted after 14 days.
p38 The shared cache evicts keys with a least-recently-used policy once memory reaches 80 percent. Keys without a TTL are never expired on their own.
p39 DNS records have a TTL of 300 seconds. Lower the TTL to 60 seconds a day before a planned migration.
p40 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.
1 p01 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.
2 p02 Resetting two-factor authentication requires a helpdesk ticket. An agent verifies your identity by video call before removing the registered authenticator.
3 p03 After five failed sign-in attempts the account is locked for 15 minutes. Locked accounts unlock automatically and no ticket is needed.
4 p04 On Windows, install the VPN client from the software portal, import the profile file and connect to the gateway vpn-eu.example.net. Error VPN-619 means the profile has expired.
5 p05 On macOS the VPN client needs its system extension approved in System Settings under Privacy and Security before the first connection. Without approval the tunnel never starts.
6 p06 Split tunnelling sends only corporate subnets through the VPN. Internet traffic uses your local connection, which keeps video calls fast.
7 p07 Production databases are backed up nightly at 02:00 UTC and retained for 35 days. Weekly full backups are kept for one year.
8 p08 To restore a database, open a restore request naming the backup timestamp and the target instance. A restore into the production instance needs approval from the data owner.
9 p09 Error E-4012 during a backup means the snapshot volume ran out of space. Expand the volume or delete expired snapshots, then rerun the job.
10 p10 Deployments to production run through the release pipeline. A change needs one approving review and a green build before the deploy button is enabled.
11 p11 To roll back a release, redeploy the previous tagged version from the pipeline. Database migrations are not reverted automatically.
12 p12 No production deployments happen during a change freeze, which is announced in the engineering channel. Emergency fixes need director approval.
13 p13 If the primary database fails, the replica is promoted automatically within about 60 seconds. Applications reconnect through the cluster endpoint, not the instance address.
14 p14 Error E-5003, too many connections, means the pool exceeds the server limit of 200. Reduce the pool size per instance or add a connection pooler.
15 p15 Replica lag above 30 seconds raises an alert. Long-running reports on the replica are the usual cause; move them to the analytics cluster.
16 p16 TLS certificates are issued for 90 days and renewed automatically 30 days before expiry. A renewal failure alert means the DNS challenge record is missing.
17 p17 Mobile apps pin the intermediate certificate. Changing the certificate authority requires an app release before the switch.
18 p18 The public API allows 600 requests per minute per key. Requests beyond that receive HTTP 429 with a Retry-After header.
19 p19 To raise a rate limit, file a request with the expected traffic and the business reason. Increases above 3000 requests per minute need architecture review.
20 p20 API keys should be rotated every 90 days. Rotation creates a second key so clients can switch without downtime, and the old key is revoked after 7 days.
21 p21 Invoices are generated on the first day of each month and emailed to the billing contact. Payment terms are 30 days.
22 p22 Refunds for annual plans are prorated by unused full months. Monthly plans are not refunded.
23 p23 Upgrading a plan takes effect immediately and the price difference is prorated for the rest of the billing period.
24 p24 The on-call engineer acknowledges a page within 5 minutes. With no acknowledgement the page escalates to the secondary and then to the engineering manager.
25 p25 Sev1 means a customer-facing outage or data loss, Sev2 is major degradation and Sev3 is minor impact with a workaround. Sev1 requires a status page update within 15 minutes.
26 p26 A blameless postmortem is written within five working days of a Sev1 or Sev2 incident and reviewed in the weekly operations meeting.
27 p27 Application logs are kept hot for 14 days and archived for one year. Audit logs are kept for seven years.
28 p28 Do not log email addresses, card numbers or access tokens. The log pipeline masks card numbers, but other personal data passes through unchanged.
29 p29 Customers can request an export of their personal data. The export is produced within 30 days and delivered as a zip of JSON files.
30 p30 Deleting an account removes personal data within 30 days. Backups age out on their normal schedule, so deleted data can persist in backups for up to 35 days.
31 p31 New laptops are ordered through the IT portal. Delivery takes five working days and developers can choose between a 14-inch and a 16-inch model.
32 p32 Report a lost or stolen laptop to security immediately. The device is wiped remotely and disk encryption makes the data unreadable.
33 p33 Expenses under 50 euros need no receipt. Larger expenses require a receipt uploaded within 30 days.
34 p34 Annual leave requests are submitted in the HR system and approved by your manager. Leave of more than ten consecutive days also needs approval from the department head.
35 p35 Feature flags are managed in the flag console. A flag must have an owner and an expiry date, and flags past their expiry are reported weekly.
36 p36 Canary releases send 5 percent of traffic to the new version for 30 minutes. If the error rate rises above 1 percent the pipeline aborts the rollout.
37 p37 Messages that fail processing five times go to the dead-letter queue. Inspect the dead-letter queue daily; messages are deleted after 14 days.
38 p38 The shared cache evicts keys with a least-recently-used policy once memory reaches 80 percent. Keys without a TTL are never expired on their own.
39 p39 DNS records have a TTL of 300 seconds. Lower the TTL to 60 seconds a day before a planned migration.
40 p40 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.
+30
View File
@@ -0,0 +1,30 @@
q01 exact VPN-619 p04:2
q02 exact E-4012 p09:2
q03 exact E-5003 p14:2
q04 exact What does HTTP 429 with Retry-After mean for the API? p18:2
q05 exact How fast must the status page be updated for a Sev1? p25:2
q06 exact How long do dead-letter queue messages live? p37:2
q07 exact What is the TTL of DNS records? p39:2
q08 exact How long is the password reset link valid? p01:2
q09 exact At what time UTC do nightly backups run? p07:2
q10 exact What share of traffic does a canary release get? p36:2
q11 exact How many days are archived logs kept? p27:2
q12 paraphrase I can't remember my login credentials, how do I get back in? p01:2
q13 paraphrase my authenticator phone broke p02:2
q14 paraphrase I typed the wrong password too many times p03:2,p01:1
q15 paraphrase the tunnel will not start on my Mac p05:2
q16 paraphrase can I put the database back to the state it had yesterday p08:2,p07:1
q17 paraphrase how do I ship a change to live systems p10:2,p12:1
q18 paraphrase undo a bad release p11:2,p36:1
q19 paraphrase the main database server died, what happens next p13:2
q20 paraphrase we need more API calls per minute than we are allowed p19:2,p18:1
q21 paraphrase swap credentials for a service without downtime p20:2,p40:1
q22 paraphrase someone pushed a password to git p40:2
q23 paraphrase my work machine was stolen p32:2
q24 paraphrase money back after cancelling a yearly subscription p22:2
q25 multi how long do deleted customer records stay around p30:2,p07:1
q26 multi what happens when a page goes unanswered during an outage p24:2,p25:1
q27 multi what must I do after a Sev1 p26:2,p25:1
q28 multi which data must not appear in logs and how long are logs kept p28:2,p27:2
q29 multi is changing certificate provider safe for the mobile apps p17:2,p16:1
q30 multi what slows reports and raises replica alerts p15:2,p13:1
1 q01 exact VPN-619 p04:2
2 q02 exact E-4012 p09:2
3 q03 exact E-5003 p14:2
4 q04 exact What does HTTP 429 with Retry-After mean for the API? p18:2
5 q05 exact How fast must the status page be updated for a Sev1? p25:2
6 q06 exact How long do dead-letter queue messages live? p37:2
7 q07 exact What is the TTL of DNS records? p39:2
8 q08 exact How long is the password reset link valid? p01:2
9 q09 exact At what time UTC do nightly backups run? p07:2
10 q10 exact What share of traffic does a canary release get? p36:2
11 q11 exact How many days are archived logs kept? p27:2
12 q12 paraphrase I can't remember my login credentials, how do I get back in? p01:2
13 q13 paraphrase my authenticator phone broke p02:2
14 q14 paraphrase I typed the wrong password too many times p03:2,p01:1
15 q15 paraphrase the tunnel will not start on my Mac p05:2
16 q16 paraphrase can I put the database back to the state it had yesterday p08:2,p07:1
17 q17 paraphrase how do I ship a change to live systems p10:2,p12:1
18 q18 paraphrase undo a bad release p11:2,p36:1
19 q19 paraphrase the main database server died, what happens next p13:2
20 q20 paraphrase we need more API calls per minute than we are allowed p19:2,p18:1
21 q21 paraphrase swap credentials for a service without downtime p20:2,p40:1
22 q22 paraphrase someone pushed a password to git p40:2
23 q23 paraphrase my work machine was stolen p32:2
24 q24 paraphrase money back after cancelling a yearly subscription p22:2
25 q25 multi how long do deleted customer records stay around p30:2,p07:1
26 q26 multi what happens when a page goes unanswered during an outage p24:2,p25:1
27 q27 multi what must I do after a Sev1 p26:2,p25:1
28 q28 multi which data must not appear in logs and how long are logs kept p28:2,p27:2
29 q29 multi is changing certificate provider safe for the mobile apps p17:2,p16:1
30 q30 multi what slows reports and raises replica alerts p15:2,p13:1
@@ -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);
}
}
@@ -0,0 +1,27 @@
# 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
multi.hit@1=0.833
multi.hit@5=1.000
multi.mrr=0.917
multi.ndcg@10=0.839
multi.recall@10=0.833
multi.recall@5=0.833
overall.hit@1=0.733
overall.hit@5=0.933
overall.mrr=0.814
overall.ndcg@10=0.798
overall.recall@10=0.867
overall.recall@5=0.867
paraphrase.hit@1=0.462
paraphrase.hit@5=0.846
paraphrase.mrr=0.609
paraphrase.ndcg@10=0.607
paraphrase.recall@10=0.769
paraphrase.recall@5=0.769