Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 07 · 40 minutes

Measure retrieval quality and leakage

After this lesson you can
  • Compute precision at k and a leakage count on a labelled question set
  • Compare the service before and after the controls of lessons 3 to 5
  • Make the run fail with an exit code when quality or leakage passes a threshold
Lab files of this lesson (34)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The controls are in place, and the product owner asks for proof: "Give me one number for the quality of the search and one for leaks, before and after the controls. And make the build fail if either one gets worse." A controlled service that answers nothing is as useless as a leaky one, so you measure both sides. You write a labelled question set, an evaluator and a gate.

Recall

Lesson 4: why must the table test hold rows that expect an empty result?

A table with only allowed rows cannot fail on a leak. The rows with an empty set are the ones that prove that a visitor gets nothing from finance documents.

Lesson 5: with the cap alone, the stuffed chunks still ranked first for four questions. What removed them?

The stuffing check, which left them out of the index, and the approval of lesson 3, which keeps unreviewed pages out in the first place.

The idea

A labelled question set is a list of questions where a person has written which chunks are the right answer. The evaluator runs each question through the retriever and compares. Two numbers matter here.

MeasureHow it is computedWhat a bad value means
Precision at kFor one question: the returned chunks (at most k) that are right, divided by the number returned. The mean over the questions that have an answer.The prompt is full of chunks that do not answer the question, so the model has less to work with and more to distort.
Leakage countThe number of returned chunks whose level is above the level of the user, over all questions.A user got a chunk that they may not read. The target is zero.

Questions with an empty relevant list have no right answer for that user. A visitor asks about salaries: the right result is nothing. These questions measure leakage only.

A threshold is a value that the measure must reach. The program turns a failed threshold into exit code 1, so that a build or a scheduled job stops. Precision depends on the data, so you set the threshold from a first good run, with some room below it, and keep it. Leakage has one threshold for every service: zero.

The gate of the evaluator
Labelled questionsRetrieverGradeReportGateeach question, with its userprecision and leaksone line for each questionexit code 1 when a threshold failsLabelled questionsRetrieverGradeReportGate1234
  1. Labelled questions → Retriever: each question, with its user
  2. Retriever → Grade: precision and leaks
  3. Grade → Report: one line for each question
  4. Report → Gate: exit code 1 when a threshold fails

Precision at 3 cannot reach 1.0 here. Most questions have one right chunk, and the search also returns weaker chunks that share a word. The value is for comparison between runs, not for the score on its own.

Worked example

1. Save the labelled questions

Twelve questions have a right chunk. Four are attempts to read above the level of the user. The user field is who asks, and relevant lists the ids of the right chunks.

questions.json

[
  {"user": "gus", "question": "How many days do I have to return unused gear?", "relevant": ["pub-returns"]},
  {"user": "gus", "question": "When is delivery free?", "relevant": ["pub-shipping"]},
  {"user": "gus", "question": "How long is the warranty on a tent?", "relevant": ["pub-warranty"]},
  {"user": "gus", "question": "When is the shop open on Saturday?", "relevant": ["pub-hours"]},
  {"user": "sam", "question": "How many days of paid holiday do staff get?", "relevant": ["stf-holiday"]},
  {"user": "sam", "question": "How do I connect to the VPN?", "relevant": ["stf-vpn"]},
  {"user": "sam", "question": "How much is the staff discount?", "relevant": ["stf-discount"]},
  {"user": "sam", "question": "When does an expense claim need approval?", "relevant": ["stf-expenses"]},
  {"user": "fay", "question": "How much does a store assistant earn?", "relevant": ["fin-salary"]},
  {"user": "fay", "question": "What was the revenue in Q3?", "relevant": ["fin-q3"]},
  {"user": "fay", "question": "What does Norrland Textiles charge for a jacket shell?", "relevant": ["fin-supplier"]},
  {"user": "fay", "question": "When are salaries paid?", "relevant": ["fin-payroll"]},
  {"user": "gus", "question": "How much does a store assistant earn?", "relevant": []},
  {"user": "gus", "question": "What was the revenue in Q3?", "relevant": []},
  {"user": "sam", "question": "What does a team lead earn?", "relevant": []},
  {"user": "sam", "question": "What does Norrland Textiles charge for a jacket shell?", "relevant": []}
]

2. Write the evaluator

Save evaluate.py. A retriever here is any function (user, question, k) that returns a list of chunk ids. plain is the service of lesson 1, with no controls. controlled takes only the chunks that pass the screen of lesson 3, builds the SafeIndex of lesson 5, and applies the filter of lesson 4 before ranking. Each of them returns a lambda, a small function without a name, that keeps the index it built. grade scores one question, and run takes the mean. The main part writes a report file, with one line for each question, and ends with the exit code.

evaluate.py

"""evaluate.py: precision at k and leakage of a retriever, on a labelled question set.

    python3 evaluate.py plain|controlled [chunks.json ...]     default file: kb.json
Writes report-<mode>.txt. The exit code is 1 when the run fails the thresholds.
"""
import json
import sys

from access import LEVEL, USERS, allowed_ids
from provenance import screen
from rag import Index, load
from safeindex import SafeIndex

MIN_PRECISION = 0.55       # the run fails below this
MAX_LEAKS = 0              # and above this


def plain(chunks, approvals):
    """No controls: every chunk is indexed, nobody is filtered."""
    index = Index(chunks)
    return lambda user, question, k: [cid for _, cid in index.search(question, k)]


def controlled(chunks, approvals):
    """Only approved chunks, a safer index, and the access filter before ranking."""
    verdicts = screen(chunks, approvals)
    ok = [c for c in chunks if verdicts[c["id"]][0] == "accept"]
    index = SafeIndex(ok)
    return lambda user, question, k: [cid for _, cid in index.search(question, k, allowed_ids(user, ok))]


def grade(retrieve, q, level_of, k=3):
    """For one question: the ids returned, how many are above the user's level, and the precision.
    Precision is None for a question that has no right answer for this user."""
    got = retrieve(q["user"], q["question"], k)
    leaks = sum(LEVEL[level_of[cid]] > LEVEL[USERS[q["user"]]] for cid in got)
    precision = (sum(cid in q["relevant"] for cid in got) / len(got) if got else 0.0) if q["relevant"] else None
    return got, leaks, precision


def run(retrieve, questions, level_of, k=3):
    """Return (mean precision at k over the questions that have an answer, number of forbidden chunks returned)."""
    graded = [grade(retrieve, q, level_of, k) for q in questions]
    scores = [p for _, _, p in graded if p is not None]
    return round(sum(scores) / len(scores), 2), sum(leaks for _, leaks, _ in graded)


if __name__ == "__main__":
    mode, files = sys.argv[1], sys.argv[2:] or ["kb.json"]
    chunks = [c for path in files for c in load(path)]
    level_of = {c["id"]: c["level"] for c in chunks}
    questions = json.load(open("questions.json"))
    retrieve = {"plain": plain, "controlled": controlled}[mode](chunks, json.load(open("approvals.json")))
    lines = []
    for q in questions:
        got, leaks, p = grade(retrieve, q, level_of)
        lines.append(f"{q['user']:4} {q['question'][:38]:40} leaks {leaks}  precision {'-' if p is None else f'{p:.2f}'}  {got}")
    precision, leaks = run(retrieve, questions, level_of)
    failed = precision < MIN_PRECISION or leaks > MAX_LEAKS
    lines.append(f"{mode}: precision@3 {precision:.2f}   leaked chunks {leaks}   {'FAIL' if failed else 'pass'}")
    open(f"report-{mode}.txt", "w").write("\n".join(lines) + "\n")
    print("\n".join(lines))
    sys.exit(1 if failed else 0)

3. Measure before the controls

Run the service without controls on the knowledge base and the three bad files of lessons 2 and 5. tail -1 prints only the last line of the report, the summary.

The exit code that you want is the one of evaluate.py. After a pipe, $? would show the exit code of tail, which is always 0. The array PIPESTATUS holds the exit code of each command of the last pipe, and PIPESTATUS[0] is the first one. This works in bash. In zsh, the default shell on macOS, write ${pipestatus[1]}.

python3 evaluate.py plain kb.json poison.json poison2.json promo.json | tail -1
echo "exit code ${PIPESTATUS[0]}"
plain: precision@3 0.43   leaked chunks 9   FAIL
exit code 1

The run fails on both thresholds: precision is below 0.55 and nine forbidden chunks came back.

4. Measure after the controls

python3 evaluate.py controlled kb.json poison.json poison2.json promo.json | tail -1
echo "exit code ${PIPESTATUS[0]}"
controlled: precision@3 0.71   leaked chunks 0   pass
exit code 0

Quality went up, from 0.43 to 0.71, and leaks went down, from 9 to 0. That is not a trade-off: the poisoned and stuffed chunks were wrong answers as well as unwanted ones. Read one question in both reports to see the cause. grep prints the lines that hold a word, from the files that you name, and puts the file name in front of each line.

grep "store assistant" report-plain.txt report-controlled.txt
report-plain.txt:fay  How much does a store assistant earn?    leaks 0  precision 0.50  ['fin-salary', 'pub-returns-update']
report-plain.txt:gus  How much does a store assistant earn?    leaks 1  precision -  ['fin-salary', 'pub-returns-update']
report-controlled.txt:fay  How much does a store assistant earn?    leaks 0  precision 1.00  ['fin-salary']
report-controlled.txt:gus  How much does a store assistant earn?    leaks 0  precision -  []

Without controls, the visitor gets the salary chunk and a poisoned page. With them, the visitor gets nothing, and the finance user gets only the salary chunk.

5. See what an average can hide

Run the plain service on the clean knowledge base only.

python3 evaluate.py plain | tail -1
plain: precision@3 0.60   leaked chunks 11   FAIL

Precision is 0.60, above the threshold of 0.55, so it passes. The run still fails, because eleven forbidden chunks came back. A single average can look good while a leak sits in it. That is why leakage has its own threshold, with the value zero.

Precision at 3 (the threshold is 0.55)
Controlled, four files0.71Plain, clean files only0.60Plain, four files0.43Controlled, four files0.71Plain, clean files only0.60Plain, four files0.43
Leaked chunks (the threshold is 0)
Plain, clean files only11Plain, four files9Controlled, four files0Plain, clean files only11Plain, four files9Controlled, four files0

Your turn

Needs: approvals.json (lesson 3) and promo.json (lesson 5). A reader who starts here runs bash catchup.sh from the set-up lesson (00) first.

Two teams each added only half of the controls. Add two modes to evaluate.py and run them on the four files of step 3. The mode approved_only screens the chunks with screen as controlled does and builds a plain Index from the accepted ones, with no access filter. The mode filter_only indexes every chunk with a plain Index, with no screen and no stuffing check, and applies only the access filter before ranking. Run both modes with tail -1 and the exit code. Then write two sentences in notes-07.txt: which half of the controls each team forgot, and which measure shows it. The page does not check the notes.

Check yourself

The run on the clean knowledge base had a precision of 0.60, above the threshold, and still failed. Is the gate wrong?

No. The gate has two thresholds, and the second one failed: eleven leaks. An average of quality cannot cancel a leak. Keep the two measures separate and make each one stop the run on its own.

Why is the leakage threshold zero, while the precision threshold is a number that you choose?

One forbidden chunk in the prompt is a disclosure. There is no acceptable number of those. Precision is a measure of usefulness: it depends on the documents, and you set it after a first good run, so that a later fall stops the build.

Why do the questions with an empty `relevant` list not count in the precision?

They have no right answer, so precision has no meaning for them. They are in the set to test leakage. A correct result for them is an empty list, which the leakage count rewards with a zero.

Your labelled set has sixteen questions. What can it not tell you?

It cannot tell you about questions that nobody wrote, other users, other models or other wordings. It is a regression test: it shows that a change made things worse on known cases. Grow it with every failure that you find in practice.

Field notes

  • Keep the labelled set in version control next to the code, and run it on every change of the code, the data and the prompt. A change in the knowledge base can change the ranking as much as a change in the code.
  • Add a row for every real incident: the question that leaked, and the question that a defence broke. Write the forbidden rows first.
  • Precision at k is one measure of retrieval. Others are recall (did the right chunk come back at all?) and the rank of the first right chunk. Evaluate retrieval before you blame the model: most wrong answers start with a wrong chunk.
  • A model-written answer cannot be a hard test. Use the retrieval and the prompt, which code decides, as the gate. Measure the answers of the model separately, as a report, with the number of runs and the model name.
  • Run the gate in the build, and also on a schedule against the live index. Data changes between builds, and so does the leak.