AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 31

    RAG Evaluation and Observability

    A fusion change on TechLearningPro "looked better" on one engineer's query about refunds.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 31 · RAG, Search and Knowledge Systems

    Lesson Overview

    A fusion change on TechLearningPro "looked better" on one engineer's query about refunds. The glossary moved under the 14-day article in a local demo. The same change buried PGV-2041 under a vague paragraph about model versions, and nobody had a stored case for the error code. The deploy went out. The shared debug dashboard also stored the raw question, including a learner who had pasted a billing email subject into the box. Retrieval quality and logging were the same kind of gap: a story instead of a measurement, and a log that forgot who is allowed to read a question.

    RAG evaluation is a fixed set of cases scored by checks you can explain, compared to a baseline, with a gate that can block a release. This lesson splits the set in two. Retrieval cases ask whether the right chunk is in the top k, and how high. Answer cases ask whether attribution abstained or quoted the expected ids. A grounded quote of the wrong article fails the answer case even though Grounded Answers, Citations and Source Attribution did its job. Observability is how you see the same split in production without copying the question into a global log: a tenant-scoped trace with counts and ids, plus aggregate counters that page on empty retrieval, reranker degradation, and grounding rejections.

    You will implement hit rate at k, recall at k, reciprocal rank, a mean, a gate that refuses a missing baseline, and a safe trace builder. A judge model may comment. It may not flip a missed chunk into a pass. The lab cases use the public help sentences from the last three lessons. They do not contain learner mail, names, or provider keys.

    Planning assumptions:

    • The golden set is owned by the team, versioned next to the code, and small enough that every row has a reason to exist.
    • k = 5 for retrieval reporting in this lab. Say the k in the report. A hit at 5 is not a hit at 1.
    • The gate copies lesson 18's spirit: a critical failure blocks, and mean reciprocal rank may not drop at all versus the stored baseline. Loosen that only with a written reason.
    • Thresholds on the alert rules are illustrative. They are not an SLO you can paste into a contract.
    • No log vendor and no judge API. The judge port returns a note the gate ignores.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Separate a demo transcript from a retrieval case with relevant chunk ids and a ranked list.
    2. Compute hit@k, recall@k, and reciprocal rank, and average reciprocal rank into MRR.
    3. Keep abstain cases out of MRR so an empty relevant set does not pretend to be a perfect rank.
    4. Score answer cases against the attribution decision: expected ids versus expected abstain.
    5. Fail a case that quotes the glossary when the window was required, without calling that a grounding bug.
    6. Gate a candidate report on critical misses and on an MRR drop, and reject a missing baseline.
    7. Build a trace that stores query length and chunk ids, not the question text.
    8. Explain why a hash of a short support code is not anonymity.
    9. Count empty retrieval, reranker degradation, and grounding rejections without using tenant id as a metric label.
    10. Keep a judge advisory so it cannot erase a critical miss.
    11. Page on rates only after a minimum sample count, and treat correct abstains as a review metric.
    12. Run the gate as a unit test that fails the build when the critical refund case regresses.

    Prerequisites

    • Lessons 28 through 30: hybrid lists, packed order, and attribute's decision codes. This lesson scores those outputs. It does not re-implement BM25.
    • AI Application Evaluation and Quality Measurement for golden cases, critical flags, and a judge that cannot overturn a deterministic check. The checks here are retrieval and citation checks. The tutor checks from lesson 18 stay on the tutor.
    • You can hash nothing and still be safe: the trace omits the string. TypeScript for Production Full-Stack Development covers the result types.
    • Node.js 20 or newer, node:test, no provider key.

    Detailed Core Concepts

    Two scores, because there are two products

    Retrieval quality asks: did the system surface the chunk a person marked relevant? Answer quality asks: did the system show that chunk, a different allowed chunk, or a correct abstain? If you only score the final paragraph, a reranker regression and a selector regression look the same. If you only score retrieval, you will ship a model that packs the window and then quotes the glossary.

    FailureRetrieval caseAnswer case
    chk_window missing from the top 5FailOften an abstain or a wrong quote
    chk_window at rank 1, model quotes the glossaryPassFail
    Question has no article, model abstainsNot an MRR casePass
    Question has no article, model quotes a chunkNot an MRR caseFail
    Quote text differs from the passageShould be unreachable if lesson 30 is the rendererFail closed in attribute, counted as grounding_rejected if a bad id was involved

    Write cases from incidents. The Monday error-code miss is a retrieval case whose relevant id is chk_error. The Monday 90-day sentence is not an answer case against a live model in this lab, because the renderer cannot emit it. The case you can regress is: selection ["chk_glossary"] when the expected id is chk_window. Keep the hostile 90-day unit test in lesson 30. Do not delete it because the eval set "covers grounding."

    Hit, recall, reciprocal rank

    For one case, relevant is the set of chunk ids a reviewer marked, and ranked is the system's order.

    • hit@k is true when at least one relevant id appears in the first k ranks. It answers "did we surface anything useful?"
    • recall@k is the fraction of relevant ids that appear in the first k. It answers "did we surface all of the marked chunks?" Use it when more than one chunk is required. A single-id case makes recall@k the same bit as hit@k.
    • Reciprocal rank is 1 / rank of the first relevant id, or 0 if it never appears. Rank is 1-based. A hit at rank 1 scores 1. A hit at rank 5 scores 0.2.
    • MRR is the mean of reciprocal ranks across retrieval cases.

    k must be on the report. A team that celebrates hit@20 while the product packs two chunks is measuring a system the user does not have. Report hit@k at the pack width and at the retrieval width if they differ. This lab uses k = 5 in the helper tests and expects the assignment to also compute the pack-width number you actually show the model.

    Do not compute MRR on cases with an empty relevant set. Those are answer cases: the correct behavior is abstain, and there is no rank to reward. A function that returns 1 for "nothing relevant and nothing retrieved" will paint a red release green.

    The golden set

    A retrieval row:

    FieldRole
    idStable. Critical rows use a crit_ prefix so a reviewer can see them in a diff.
    criticalOne failure blocks the gate even if MRR holds.
    questionWhat you would type. Stored in the case file, not copied into the production trace.
    relevantChunkIdsNon-empty.
    rankedChunkIdsThe system output you are scoring. In the lab this is a fixture. In CI it is the hybrid-plus-rerank output.

    An answer row:

    FieldRole
    idStable.
    criticalSame gate rule.
    expectAbstainWhen true, expectChunkIds is empty.
    expectChunkIdsExact set the quoter should have used, order-insensitive in this lab.
    actualAbstainFrom attribute.
    actualChunkIdsFrom the sources.

    Twelve cases beat a thousand clones of "hello." Start with: the error code, the money-back paraphrase, the window-versus-glossary selection, a staff chunk that must not appear, a stale version that must not appear, and a weather question that must abstain. Add a case when production finds a new miss. Deleting a failing case is how the gate goes green. If a case is wrong because the article changed, update the relevant ids in the same change as the article and say so in the commit message.

    The case file lives in the repo only if the text is public help text. A case that needs a learner's private note belongs in a restricted store with the same access control as that note, or it gets rewritten as a synthetic pattern. The lab file is synthetic and public.

    The gate

    text
    missing baseline -> do not promote
    any critical retrieval or answer miss -> do not promote
    candidate MRR < baseline MRR -> do not promote
    otherwise -> promote

    "Promote" means the candidate retrieverVersion and rerankerId may become the ones the help route calls. It does not mean the model may skip attribute. The comparison uses a small epsilon so binary floating noise does not fail a tie. It does not allow a "small" drop. A 0.01 drop can be the critical code sliding from rank 1 to rank 2, which hit@5 would hide. That is why MRR is in the gate and hit@5 alone is not.

    A missing baseline fails closed. The first release writes a baseline on purpose, in a reviewed change, after a human has read the report. An empty file is not a baseline. Lesson 18 made the same choice for prompt versions. Do not special-case "first run" inside the gate function. The tool that creates the baseline is a separate command a person runs.

    Traces and metrics

    A trace is one request, stored where staff of that tenant (and your on-call, under your access policy) can read it. A metric is an aggregate with low cardinality. This lab's trace:

    FieldWhy it is here
    traceIdCorrelation from the HTTP request through rerank and attribution
    tenantIdSo the trace store can authorize reads
    queryCharCountLength, for "did we hit the cap?" without the text
    retrieverVersion, rerankerIdWhich pair the gate promoted
    degradedNull or reranker_unavailable
    retrievedChunkIds, packedChunkIds, sourceChunkIdsThe split you need in an incident
    decisionquoted or a rejection / abstain code
    latencyMsThe route, not a guess

    The question string is not a field. A SHA-256 of PGV-2041 is still reversible by anyone who can guess support codes. Treat a hash of a short query as a fingerprint, not as a redaction. If support must see the question to debug a tenant's ticket, store it in that tenant's trace under the same authorization as the conversation, as an explicit field you add later. The default builder in this lesson does not have that field, so a shared exporter cannot leak it by accident.

    Metrics in this lab are global counters:

    • retrieval_requests
    • retrieval_empty
    • reranker_degraded
    • grounding_rejected
    • answers_abstain
    • answers_quoted

    tenantId is not a label. A label per tenant will hit cardinality limits and can leak "this tenant is the one with traffic." Per-tenant investigation uses traces, sampled or complete, in the tenant-scoped store.

    Alerts fire on a rate only after minSamples, so two empty searches at midnight do not page. Illustrative rules, not SLOs:

    • retrieval_empty / retrieval_requests > 0.30 after 20 requests
    • reranker_degraded / retrieval_requests > 0.05 after 20 requests
    • grounding_rejected / retrieval_requests > 0.02 after 20 requests

    answers_abstain is a weekly quality chart. A correct "we do not have that article" increases it. Paging on abstain rate pages you for a healthy product on a day of unanswerable questions. Page on grounding_rejected, which is unknown ids, cross-tenant rows, and the other fail-closed reasons. Those should be rare if the prompt and the allowed set are aligned.

    Do not log passage bodies at info level. The trace already has ids. The body is in the CMS. Logging both doubles the chance a staff article lands in a logging vendor.

    The judge

    A judge port takes a case id and returns { advisory: string }. The report may store the string. gate does not read it. The same model family that selected the chunk is weak evidence that the selection was good. Lesson 18's rule stands: a judge does not flip a failed check. If you have no judge, the port returns a fixed note "not_run". The unit test uses that. Paying a judge on every CI case is a cost decision you record, not a default.

    Architecture and Request Flow

    flowchart TB
      subgraph ci [CI]
        Cases[Golden cases]
        Score[hit, recall, MRR, answer match]
        Gate[Release gate]
      end
    
      subgraph prod [Help route]
        Req[Search request]
        Trace[Tenant-scoped trace]
        Metrics[Global counters]
      end
    
      Cases --> Score
      Score --> Gate
      Gate -->|promoted versions| Req
      Req --> Trace
      Req --> Metrics
    text
    ranked ids + relevant ids --> reciprocal rank --> MRR
    actual sources + expected ids --> answer pass or fail
    |
    v
    critical miss or MRR drop or no baseline --> block
    |
    v
    production request --> safe trace (no question text)
    --> counters --> rate alert after minSamples
    flowchart LR
      Q[Question stays in the case file or the tenant store] --> Rank[Ranked chunk ids]
      Rank --> Report[Eval report]
      Report --> Gate[Gate]
      Live[Live request] --> Safe[Safe trace]
      Safe --> Page[Counters and alerts]

    Trust boundary: CI fixtures are public text. Production traces with chunk ids still reveal which articles were touched. That is why they are tenant-scoped. Metrics are the only stream that is globally readable, and they have no ids and no query text.

    Step-by-step Implementation

    Package path: packages/rag-eval/. "strict": true. No network. No process.env.

    Step 1: Retrieval metrics

    packages/rag-eval/src/metrics.ts

    typescript
    export function recallAtK(relevant: readonly string[], ranked: readonly string[], k: number): number {
    if (relevant.length === 0) throw new Error("empty_relevant");
    if (!Number.isInteger(k) || k < 1) throw new Error("bad_k");
    const top = new Set(ranked.slice(0, k));
    let hits = 0;
    for (const id of relevant) if (top.has(id)) hits += 1;
    return hits / relevant.length;
    }
    export function hitAtK(relevant: readonly string[], ranked: readonly string[], k: number): boolean {
    return recallAtK(relevant, ranked, k) > 0;
    }
    /** 1-based rank of the first relevant id. Zero when the list never hits. */
    export function reciprocalRank(relevant: readonly string[], ranked: readonly string[]): number {
    if (relevant.length === 0) throw new Error("empty_relevant");
    const wanted = new Set(relevant);
    for (let i = 0; i < ranked.length; i++) {
    const id = ranked[i];
    if (id !== undefined && wanted.has(id)) return 1 / (i + 1);
    }
    return 0;
    }
    export function mean(values: readonly number[]): number {
    if (values.length === 0) throw new Error("empty_mean");
    return values.reduce((sum, value) => sum + value, 0) / values.length;
    }

    Throwing on an empty relevant set forces the caller to keep abstain cases on the other path. A quiet 0 would look like a miss. A quiet 1 would look like a success. Neither belongs inside MRR.

    Step 2: Reports and the gate

    packages/rag-eval/src/gate.ts

    typescript
    export interface RetrievalCaseResult {
    id: string;
    critical: boolean;
    reciprocalRank: number;
    hitAt5: boolean;
    }
    export interface AnswerCaseResult {
    id: string;
    critical: boolean;
    passed: boolean;
    }
    export interface EvalReport {
    retrieverVersion: string;
    rerankerId: string;
    retrievalMrr: number;
    retrieval: readonly RetrievalCaseResult[];
    answers: readonly AnswerCaseResult[];
    }
    export type GateResult = { ok: true } | { ok: false; reason: "missing_baseline" | "critical" | "mrr_drop" };
    export function criticalMisses(report: EvalReport): string[] {
    const ids: string[] = [];
    for (const row of report.retrieval) {
    if (row.critical && !row.hitAt5) ids.push(row.id);
    }
    for (const row of report.answers) {
    if (row.critical && !row.passed) ids.push(row.id);
    }
    return ids;
    }
    /**
    * Lab policy: MRR may not drop. Epsilon covers binary noise, not a real regression.
    * The judge is intentionally absent from this function.
    */
    export function gate(candidate: EvalReport, baseline: EvalReport | null): GateResult {
    if (!baseline) return { ok: false, reason: "missing_baseline" };
    if (criticalMisses(candidate).length > 0) return { ok: false, reason: "critical" };
    if (candidate.retrievalMrr + 1e-12 < baseline.retrievalMrr) return { ok: false, reason: "mrr_drop" };
    return { ok: true };
    }

    hitAt5 on a critical row is necessary and not sufficient. The MRR check still runs when every critical hit@5 passes, so a critical row that slides from rank 1 to rank 5 can fail mrr_drop if that slide moves the mean. If you have a single critical row and it stays inside the top 5 while falling from 1 to 5, MRR falls and the gate blocks. Good. If you add dozens of easy rows, they can dilute MRR. That is a reason to keep the set honest, and a reason critical hit@5 exists beside the mean. Do not "fix" dilution by deleting hard rows.

    Step 3: Answer matching

    packages/rag-eval/src/answer.ts

    typescript
    export function sameIdSet(expected: readonly string[], actual: readonly string[]): boolean {
    if (expected.length !== actual.length) return false;
    const got = new Set(actual);
    return expected.every((id) => got.has(id));
    }
    export function answerPassed(input: {
    expectAbstain: boolean;
    expectChunkIds: readonly string[];
    actualAbstain: boolean;
    actualChunkIds: readonly string[];
    }): boolean {
    if (input.expectAbstain) return input.actualAbstain && input.actualChunkIds.length === 0;
    if (input.actualAbstain) return false;
    return sameIdSet(input.expectChunkIds, input.actualChunkIds);
    }

    Order does not matter here. Lesson 30 still renders in model order. If order becomes a product requirement ("policy before glossary"), add an order-sensitive case instead of overloading this helper.

    Step 4: Safe trace and alerts

    packages/rag-eval/src/trace.ts

    typescript
    export interface SafeTrace {
    traceId: string;
    tenantId: string;
    queryCharCount: number;
    retrieverVersion: string;
    rerankerId: string;
    degraded: null | "reranker_unavailable";
    retrievedChunkIds: readonly string[];
    packedChunkIds: readonly string[];
    sourceChunkIds: readonly string[];
    decision: string;
    latencyMs: number;
    }
    export function toSafeTrace(input: {
    traceId: string;
    tenantId: string;
    question: string;
    retrieverVersion: string;
    rerankerId: string;
    degraded: null | "reranker_unavailable";
    retrievedChunkIds: readonly string[];
    packedChunkIds: readonly string[];
    sourceChunkIds: readonly string[];
    decision: string;
    latencyMs: number;
    }): SafeTrace {
    return {
    traceId: input.traceId,
    tenantId: input.tenantId,
    queryCharCount: input.question.length,
    retrieverVersion: input.retrieverVersion,
    rerankerId: input.rerankerId,
    degraded: input.degraded,
    retrievedChunkIds: input.retrievedChunkIds,
    packedChunkIds: input.packedChunkIds,
    sourceChunkIds: input.sourceChunkIds,
    decision: input.decision,
    latencyMs: input.latencyMs,
    };
    }
    export interface AlertRule {
    name: string;
    numerator: "retrieval_empty" | "reranker_degraded" | "grounding_rejected";
    denominator: "retrieval_requests";
    minSamples: number;
    maxRate: number;
    }
    export function rateAlert(counts: Readonly<Record<string, number>>, rule: AlertRule): boolean {
    const denominator = counts[rule.denominator] ?? 0;
    if (denominator < rule.minSamples) return false;
    const numerator = counts[rule.numerator] ?? 0;
    return numerator / denominator > rule.maxRate;
    }

    question.length counts UTF-16 code units, which is what JavaScript strings report. It is a size check, not a linguistic word count. The function closes over the question only long enough to read the length. It does not place the string on the returned object. Callers that log input instead of the return value will still leak. The handler should log toSafeTrace(...) and then drop question from scope. A lint that forbids logging the raw request body is the production version of that sentence.

    Illustrative rules to put next to the route, not inside a vendor-specific file:

    typescript
    export const LAB_ALERTS: readonly AlertRule[] = [
    { name: "empty_retrieval", numerator: "retrieval_empty", denominator: "retrieval_requests", minSamples: 20, maxRate: 0.3 },
    { name: "reranker_degraded", numerator: "reranker_degraded", denominator: "retrieval_requests", minSamples: 20, maxRate: 0.05 },
    { name: "grounding_rejected", numerator: "grounding_rejected", denominator: "retrieval_requests", minSamples: 20, maxRate: 0.02 },
    ];

    Step 5: Request path and CI path

    CI:

    1. For each retrieval case, run hybrid search and rerank on the fixture corpus, or read a recorded ranking produced by that code. Record rankedChunkIds.
    2. Compute reciprocalRank and hitAt5. Mean the ranks into retrievalMrr.
    3. For each answer case, run attribute on the scripted selection and compare with answerPassed.
    4. Load the baseline report committed in the repo. gate. Non-ok fails the process.
    5. Print the report with ids and rates. Do not print a question that you later copy from a production export into CI.

    Request:

    1. Generate a traceId per request. Pass it through hybrid, rerank, and attribute.
    2. On the way out, toSafeTrace. Write it to the tenant-scoped store.
    3. Increment retrieval_requests. Increment retrieval_empty when the hybrid list is empty. Increment reranker_degraded when the flag is set. Increment grounding_rejected when the decision is unknown_chunk, cross_tenant, duplicate_id, too_many, or bad_selection. Increment answers_abstain or answers_quoted from the public answer.
    4. Evaluate LAB_ALERTS on a schedule, on the counter store, not inside the user request. Alerting inside the request path pages from one process's memory and misses the other replicas.

    Step 6: Run

    bash
    npx tsc --noEmit
    node --experimental-strip-types --test src/eval.test.ts

    No keys. A judge double returns { advisory: "not_run" }. If a future job calls a judge, that job is not gate and it is not required for this test.

    Security

    • Authentication on the trace store matches the tenant. A global "search debugger" role is a privileged role, reviewed like a database admin, not like a dashboard everyone on the company VPN can open.
    • Authorization for metrics is broader because the fields are counts. Do not attach a query or a chunk id to a metric to "make debugging easier."
    • Least privilege for the CI job: it can read the fixture corpus and write a test result. It cannot read production traces.
    • Input validation on cases: non-empty relevant ids for retrieval rows, k a positive integer. A poisoned case file that sets critical: false on the refund window is a code review failure. Protect the file like you protect the gate.
    • Privacy: the default trace has no question. Support tooling that adds the question must show an access reason and a retention limit. Responsible AI, Safety and Human-in-the-Loop Design is the policy. The omitted field is the control in toSafeTrace.
    • Secrets: fixtures stay free of keys. A test that needs to prove redaction uses a fake token string such as provider-key-sample and asserts the trace JSON does not contain it. Do not use a real key to prove the point.

    Chunk ids in a trace are still sensitive if the id scheme is guessable and the chunk is private. Learner-visible help ids in this lab are not secret. Staff chunk ids should not appear in a learner trace at all. If they do, that is the audience bug from lesson 28, and the trace is how you notice.

    Error Handling

    CaseWhat happens
    Empty relevant passed to MRR helpersThrow empty_relevant so the suite splits the case
    k < 1Throw bad_k
    No baseline fileGate missing_baseline, release job fails
    Critical missGate critical, release job fails
    MRR dropGate mrr_drop, release job fails
    Judge unavailableAdvisory not_run or a skipped comment. Gate result unchanged
    Alert denominator below minSamplesNo page
    Logger handed the raw questionBug. Review the call site. toSafeTrace cannot redact a different object you also logged

    A failed gate does not hot-patch production back by itself in this lesson. The job refuses to promote. Rollback is your deploy tool, using the previous retrieverVersion. Keep that version serving until the gate is green. Do not "temporarily" point production at an unevaluated reranker because the vendor released a new model name this morning.

    Testing

    packages/rag-eval/src/eval.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { answerPassed } from "./answer.js";
    import { criticalMisses, gate, type EvalReport } from "./gate.js";
    import { hitAtK, mean, reciprocalRank } from "./metrics.js";
    import { rateAlert, toSafeTrace, type AlertRule } from "./trace.js";
    const baseline: EvalReport = {
    retrieverVersion: "hybrid-rrf-v1",
    rerankerId: "overlap-heading-v1",
    retrievalMrr: 1,
    retrieval: [
    { id: "crit_error_code", critical: true, reciprocalRank: 1, hitAt5: true },
    { id: "money_back", critical: false, reciprocalRank: 1, hitAt5: true },
    ],
    answers: [{ id: "crit_window_selected", critical: true, passed: true }],
    };
    test("rank 1 scores 1 and a miss scores 0", () => {
    assert.equal(reciprocalRank(["chk_error"], ["chk_error", "chk_other"]), 1);
    assert.equal(reciprocalRank(["chk_window"], ["chk_glossary", "chk_window"]), 0.5);
    assert.equal(hitAtK(["chk_window"], ["chk_glossary"], 5), false);
    assert.equal(mean([1, 0.5]), 0.75);
    });
    test("glossary quoted for a window question fails the answer case", () => {
    const passed = answerPassed({
    expectAbstain: false,
    expectChunkIds: ["chk_window"],
    actualAbstain: false,
    actualChunkIds: ["chk_glossary"],
    });
    assert.equal(passed, false);
    });
    test("a critical retrieval miss blocks even if a judge would approve", () => {
    const candidate: EvalReport = {
    ...baseline,
    retrievalMrr: 0.5,
    retrieval: [
    { id: "crit_error_code", critical: true, reciprocalRank: 0, hitAt5: false },
    { id: "money_back", critical: false, reciprocalRank: 1, hitAt5: true },
    ],
    };
    const advisory = { advisory: "looks fine in the demo" };
    assert.equal(advisory.advisory.length > 0, true);
    assert.deepEqual(gate(candidate, baseline), { ok: false, reason: "critical" });
    assert.deepEqual(criticalMisses(candidate), ["crit_error_code"]);
    });
    test("missing baseline does not promote", () => {
    assert.deepEqual(gate(baseline, null), { ok: false, reason: "missing_baseline" });
    });
    test("an MRR drop blocks when critical hits still pass", () => {
    const candidate: EvalReport = {
    ...baseline,
    retrievalMrr: 0.75,
    retrieval: [
    { id: "crit_error_code", critical: true, reciprocalRank: 0.5, hitAt5: true },
    { id: "money_back", critical: false, reciprocalRank: 1, hitAt5: true },
    ],
    };
    assert.deepEqual(gate(candidate, baseline), { ok: false, reason: "mrr_drop" });
    });
    test("the safe trace omits the question and a sample secret", () => {
    const question = "PGV-2041 showed up next to provider-key-sample in the email subject";
    const trace = toSafeTrace({
    traceId: "trc_1",
    tenantId: "ten_a",
    question,
    retrieverVersion: "hybrid-rrf-v1",
    rerankerId: "overlap-heading-v1",
    degraded: null,
    retrievedChunkIds: ["chk_error"],
    packedChunkIds: ["chk_error"],
    sourceChunkIds: ["chk_error"],
    decision: "quoted",
    latencyMs: 12,
    });
    const encoded = JSON.stringify(trace);
    assert.equal(encoded.includes("PGV-2041"), false);
    assert.equal(encoded.includes("provider-key-sample"), false);
    assert.equal(trace.queryCharCount, question.length);
    });
    test("alerts wait for enough samples", () => {
    const rule: AlertRule = {
    name: "empty_retrieval",
    numerator: "retrieval_empty",
    denominator: "retrieval_requests",
    minSamples: 20,
    maxRate: 0.3,
    };
    assert.equal(rateAlert({ retrieval_requests: 4, retrieval_empty: 4 }, rule), false);
    assert.equal(rateAlert({ retrieval_requests: 20, retrieval_empty: 8 }, rule), true);
    });

    The judge string is built and then ignored by gate. That is the test. If someone "helpfully" passes advisory into gate and treats "looks fine" as a pass, this test's assertion on reason: "critical" fails.

    reciprocalRank throws on an empty relevant list. Add that test beside the others so a future helper does not swallow it.

    Performance and Cost

    The golden set is small and runs on fixtures. It should finish in CI in seconds. It becomes expensive when every case calls a hosted reranker and a judge. Prefer the local overlap reranker and a scripted selection in the default job. Run a nightly sample against the hosted reranker if you pay for one, and keep that job from blocking the merge until you trust it. A flaky vendor timeout should show up as degraded in the nightly report, not as a red merge on main with no code change.

    • Do not embed the corpus inside the eval loop if vectors are already on the fixtures.
    • Cap case count growth with a review: a new case needs an incident or a policy, not a generated paraphrase of the same chunk five hundred times. Near-duplicates inflate MRR.
    • Traces: sample at 100% while volume is low. When the help route is busy, keep 100% of grounding_rejected and reranker_degraded, and sample the quiet successes. Failing open by sampling away the errors is the wrong sample.
    • Metrics are counters. They are cheaper than storing every passage. Resist a trace that embeds the packed text "just once."
    • The gate is a pure function. It does not call the network, so it cannot time out and accidentally promote.

    Latency budgets for the live route stay in lesson 29. This lesson records latencyMs so you can see that a "smarter" reranker ate the budget. A quality win that pushes p95 over the product limit is not a promotion until the product limit moves in a reviewed change.

    Knowledge Check

    1. What problem does RAG evaluation and observability solve?

    It replaces "the refund demo looked better" with a report: the error-code chunk's rank, the window chunk's selection, and a baseline those numbers may not fall below. In production it shows whether a bad day was empty retrieval, a degraded reranker, or a grounding rejection, without placing the learner's question in a global log.

    2. What alternatives exist, and when would you choose each?

    Offline gate, before a retrieverVersion or rerankerId is promoted. Online counters and traces, after promotion, to see traffic the golden set missed. Human review of a sample, when the failure is a contradiction with no integer, the gap lesson 30 named. A model judge, as a comment on that sample, never as the gate. Click-through rate, as a weak product signal that is not a substitute for a marked relevant chunk: users click confident wrong answers.

    3. Which data, identity, and trust boundaries matter?

    Case files in the repo are public text. Production questions are tenant data. The default trace stores length and ids for a tenant-scoped reader. Metrics store counts for a wider audience and therefore store less. The judge is outside the gate. CI credentials cannot read production traces.

    4. What can fail, and how should the system respond?

    A critical miss or an MRR drop fails the release job. A missing baseline fails the job. A judge outage leaves the gate on the deterministic report. An alert with too few samples stays quiet. An empty relevant set thrown into MRR is a programmer error, not a zero score. A logger that prints the raw body is a review defect the safe-trace type cannot fix after the fact.

    5. How would you test quality, security, performance, and cost?

    The unit tests lock rank math, the glossary-versus-window miss, the critical gate, the MRR drop, the missing baseline, redaction, and the sample threshold. Security review reads toSafeTrace and the trace-store ACL. Performance review checks CI still uses fixtures. Cost review checks the hosted reranker and the judge are off the default job. Quality review adds a case when a real miss shows up, and does not delete the old one to recover a number.

    Hands-on Assignment

    Lab note. Fixtures only. No judge endpoint.

    Problem. Promote hybrid-rrf-v1 with overlap-heading-v1 only when the critical error-code case hits at 5, the critical window selection matches chk_window, and MRR is not below the committed baseline. A trace for a question that contains PGV-2041 must not contain that string.

    Tasks.

    1. Implement the metric helpers, answerPassed, gate, toSafeTrace, and rateAlert.
    2. Add the empty-relevant throw test.
    3. Write a baseline JSON by hand for the two retrieval cases at reciprocal rank 1, and show that moving the error code to rank 2 fails the gate.
    4. Document the three lab alert rates as illustrative, with the sentence that correct abstains are not a page.
    5. Describe where a support engineer would be allowed to read the raw question, and which store that is.

    Deliverable. Diagram of the gate and the trace, source with no secrets, test output, and the baseline note.

    Challenge. Add ten easy cases that always rank the relevant chunk first, drop the error code to rank 5, and show MRR can stay high while hitAt5 on the critical row still passes. Then show a further drop to rank 6 fails critical. Explain why a large easy set is a way to smuggle a regression past an MRR-only gate. Keep the critical flag.

    Rubric. Conceptual accuracy and architecture 20%. Working metrics and gate 25%. Privacy of traces 20%. Tests including the judge non-effect 20%. Documentation of alert and baseline policy 15%.

    Common Mistakes

    1. One demo as a release. Symptom: PGV-2041 regresses after a refund tweak. Cause: no case for the code. Fix: a retrieval case with critical: true.
    2. A single blended score. Symptom: you cannot tell recall from selection. Cause: one "RAG score" on the final paragraph. Fix: retrieval cases and answer cases.
    3. MRR on abstain rows. Symptom: unanswerable questions inflate the mean. Cause: empty relevant was treated as rank 1. Fix: throw, and score them in answerPassed.
    4. Hit@20 on a product that packs two chunks. Symptom: the dashboard is green and the model never sees the chunk. Fix: choose k from the pack width and report it.
    5. Deleting a red case. Symptom: the gate recovered in one commit with no retrieval change. Cause: the case file shrank. Fix: change the article and the case together, in review.
    6. Judge as a veto over a miss. Symptom: "looks fine" promotes a build the metric failed. Cause: gate started reading advisory. Fix: the unit test that keeps the critical reason.
    7. Hashing the query and calling it redaction. Symptom: PGV-2041 is recoverable from the log with a dictionary. Cause: a short string was hashed. Fix: omit the string. Store it only in the tenant store if support needs it.
    8. Tenant id as a metric label. Symptom: the metrics vendor bills you and a chart lists customers. Cause: high-cardinality labels. Fix: counts globally, traces per tenant.
    9. Paging on abstain. Symptom: on-call fires every time learners ask out-of-corpus questions. Cause: abstain was treated as a defect. Fix: page on grounding_rejected and empty-retrieval rate, and chart abstain weekly.
    10. Logging packed text. Symptom: a staff runbook body appears in the logging vendor. Cause: the trace included passage.text for convenience. Fix: ids only, bodies from the CMS under ACL.
    11. Auto-promoting when the baseline file is absent. Symptom: the first broken report becomes the baseline. Cause: missing_baseline returned ok. Fix: fail closed, and write the baseline in a separate reviewed command.
    12. Hosting the reranker inside the merge gate. Symptom: CI fails when the vendor blips, or the bill tracks every pull request. Cause: the default job was not local. Fix: fixtures on the merge path, hosted sample on a schedule.

    Summary

    Evaluation tells you whether the chunk was retrieved and whether the quoter selected it, on cases you can rerun. The gate blocks a missing baseline, a critical miss, and any drop in MRR, and it does not read a judge's opinion. Observability uses the same split in production: traces carry versions, ranks' ids, the degraded flag, and the decision code, scoped to the tenant, while global counters are only counts. A short query is omitted rather than hashed into a false sense of safety. Together, the report and the trace are how a hybrid weight, a reranker, or a selector earns the help route.

    Next Lesson Preview

    Conversational Memory and Context Management puts a second turn next to this request. You will decide what from the previous question may enter retrieval, what must stay out of the shared log, and how a follow-up such as "what about monthly?" does not silently drop the tenant filter or the citation rule you just measured.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.