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

    RAG Retrieval Optimization and Reranking

    Hybrid search on TechLearningPro returned two billing chunks for "what is the refund window for annual plans." Rank 1 was the glossary: "A refund returns money to the original payment method." Rank…

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

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

    Lesson Overview

    Hybrid search on TechLearningPro returned two billing chunks for "what is the refund window for annual plans." Rank 1 was the glossary: "A refund returns money to the original payment method." Rank 2 was the policy: annual plans may be refunded within 14 days. Both chunks are about refunds. Only one states a window. The generator's context budget had room for about twenty words. Packed in hybrid order, the glossary filled the budget and the 14-day sentence never reached the model. The answer that shipped was a definition, presented as if it were the policy.

    Retrieval optimization is the set of choices that decide which recalled chunks a generator is allowed to see, in which order, under a token budget and a latency budget. Reranking is the second-stage score. A fast first stage (BM25, cosine, or the hybrid list from Semantic, Keyword and Hybrid Search) optimizes recall: get the useful chunk onto a short list. A reranker optimizes precision on that short list: read the query and the chunk together and put the chunk that answers the question first.

    The lab reranker is an overlap scorer with an explicit heading weight. It is not a cross-encoder. A cross-encoder is a model that scores the pair (query, chunk) in one forward pass and can notice that "window" plus "14 days" answers a question the word "refund" alone does not. You will wrap that future model in a Reranker port, fall back to hybrid order when the port times out, and pack chunks until a documented token estimate is spent. The fallback is a successful response with degraded: "reranker_unavailable". It is not a reason to widen the search to another tenant.

    Planning assumptions:

    • Candidates are already filtered by tenant, audience, and document version. The reranker does not fetch more rows.
    • The overlap weights are lab constants so the Monday pair sorts correctly. They are not a claim about natural language.
    • Token estimates use whitespace-separated words. They are not the tokenizer of any provider. Replace the estimator when you pick a model, and keep the budget check.
    • No reranker API key. The port is a function the test can timeout.

    Learning Objectives

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

    1. Separate recall (the candidate pool) from precision (the order inside that pool).
    2. Explain why a bi-encoder cannot see query terms and chunk terms in one interaction, and why a cross-encoder can.
    3. State the cost reason you rerank tens of chunks and not the whole corpus.
    4. Implement a heading-aware overlap scorer and label it as a stand-in.
    5. Define a Reranker port whose failure preserves the incoming order and sets a degraded flag.
    6. Reject a candidate list that mixes tenants instead of silently dropping rows.
    7. Pack chunks in reranked order until a word budget is exhausted.
    8. Show that a timeout packs the hybrid leader, which on this query is the worse glossary chunk.
    9. Keep a reranker from inventing a chunk the first stage never recalled.
    10. Name query rewriting and MMR as later optimizations that need an evaluation set.
    11. Cap candidate count, timeout, and context size so a slow model cannot own the request thread.
    12. Hand the packed passages, and only those passages, to the citation lesson.

    Prerequisites

    Detailed Core Concepts

    Recall, then precision

    The first stage is allowed to be redundant. A pool of twenty chunks that includes the 14-day policy is a success even if the glossary is rank 1. A pool of twenty that never includes the policy is a failure no reranker can repair. The reranker only reorders, and the packer only truncates. If you "optimize" retrieval by deleting the first stage's extra hits before they are reranked, you have optimized away the chunk you needed.

    Call the first-stage width N and the packed width M. This lab uses the order hybrid already computed as N, then packs to a word budget that yields M. Production often retrieves N = 50 and keeps M = 5 to 8. Those integers are capacity choices. Raise N when the relevant chunk is missing from the pool. Raise the quality of the reranker when the relevant chunk is in the pool but loses the budget to a distractor. Lesson 31's reports split those two failures. A single "the answer was wrong" ticket does not.

    Bi-encoder and cross-encoder

    Lesson 28's cosine leg is a bi-encoder pattern, even when the encoder is a lexicon. The query becomes one vector. The chunk became a vector earlier. The score is a comparison of two independent encodings. That is why it is cheap: you do not touch the chunk text at query time except to load a vector. It is also why "refund" in the query and "14 days" in the chunk never meet inside the score. They meet only if the embedder happened to place those strings near each other.

    A cross-encoder takes the query and the chunk as one input and emits one relevance score. It can represent the interaction. It costs a forward pass per candidate, so you run it on N rows, not on millions. Latency grows with N and with chunk length. A timeout is a normal dependency failure. The product still has the first-stage order.

    The lab overlap reranker counts query terms in the heading and in the body:

    text
    score = (HEADING_WEIGHT * headingHits + bodyHits) / queryTermCount

    HEADING_WEIGHT is 2 in this lab. Query terms in a documented stop list do not count. refunded does not count as refund, because this tokenizer does not stem. The annual heading still contains the exact token refund, and the body contains annual, plans, and window. The glossary heading contains refund and the body contains refund again. On the Monday query the policy scores higher. That is a fixture you can audit. It is not evidence that overlap will beat a glossary on the next question. The port exists so a real cross-encoder can replace overlapScore without a change to packing or to the degraded flag.

    What the reranker is forbidden to do

    It does not search. A high score on a chunk that was not a candidate is unreachable, because that chunk is not in the input. It does not apply a new tenant filter by fetching "similar" rows from a shared cache. If the caller passes two tenants in one array, rerank returns mixed_tenant and the handler fails closed. Silently dropping the foreign row would hide a broken caller and might still have sent that row's text to a remote cross-encoder.

    It does not see chunks the user cannot see. The text you send to a hosted reranker leaves your network. Send only rows that already passed visibleChunks. A reranker credential that can read the corpus directly is the wrong credential. It should score the pairs you post, and nothing else.

    Packing is a budget, not a sort

    After order is chosen, packChunks walks from the front and keeps a chunk when words(chunk) + used <= budget. The estimate is text.trim().split(/\s+/).length. The annual article in this lab is 17 words. The glossary is 9. A budget of 20 keeps whichever chunk is first and stops. With a healthy reranker, that is the policy. With a timeout, the hybrid order is unchanged, the glossary is first, and the policy stays on the floor. The response must say degraded: "reranker_unavailable" so the UI can avoid sounding certain, and so lesson 31 can alert on the rate.

    Do not stuff the budget by splitting a chunk in the packer. Chunk boundaries were chosen in Chunking Strategies and Metadata Design. A packer that slices the 14-day sentence in half will cite a fragment later. If a single chunk is larger than the budget, skip it and try the next. If none fit, return an empty pack with reason over_budget. The generator abstains. It does not receive a truncated sentence.

    Optimizations this lesson names and does not ship

    Query rewriting asks a model to expand "money back" into "refund window" before retrieval. It can raise recall. It can also retrieve a document the user did not ask about, and it can copy an injected instruction from a previous turn into the new query. This lab searches the user's text. Add a rewriter only with the golden set from lesson 31, and keep the original query as one of the searches so a bad rewrite cannot erase an exact code.

    Maximal marginal relevance (MMR) penalizes a candidate that is near a chunk you already picked, so the context is not five copies of the same sentence. The usual shape is λ * relevance - (1 - λ) * max similarity to selected. λ is another uncalibrated weight. On a two-chunk billing corpus, diversity is not the Monday bug. The Monday bug is relevance order. Ship MMR when the packed set is redundant and the eval says users needed a second fact.

    Lost in the middle is a reported tendency of some generators to use the start and end of a long context more than the center. Reordering to "best, worst, second best" is a response to that tendency. This lab keeps score order. Change the order when you measure your model, not because a diagram looked clever.

    Metadata boosts (newer document, title match) belong in the first stage or in a feature vector the reranker owns. Do not add a silent +0.1 in the packer. A boost is a rank change and needs a test that names the feature.

    Architecture and Request Flow

    flowchart TB
      subgraph api [TechLearningPro API]
        Hybrid[Hybrid hits from lesson 28]
        Gate[Same-tenant check]
        Rank[Reranker port]
        Pack[Word budget packer]
      end
    
      subgraph remote [Optional reranker]
        Cross[Cross-encoder]
      end
    
      Hybrid --> Gate
      Gate --> Rank
      Rank -->|scores or timeout| Pack
      Rank -.->|pairs of visible text| Cross
      Pack -->|passages or degraded flag| Gen[Generator in the next lesson]
    text
    hybrid order (already filtered)
    |
    v
    one tenant? ----no----> mixed_tenant, fail closed
    |
    yes
    |
    +--> reranker scores each pair
    | |
    | +--> timeout or error --> keep hybrid order, degraded
    |
    v
    sort by score, drop zeros
    |
    v
    pack until word budget
    |
    v
    passages the citation step may quote
    flowchart LR
      Pool[Candidate pool N] --> Score[Score query with chunk]
      Score --> Order[Precision order]
      Order --> Budget[Pack to budget M]
      Budget --> Cite[Allowed passages]

    Trust boundary: chunk text may cross to Cross only after Gate. The browser never sends the candidate list. A client that posts its own chunk ids is asking for a different feature, one that must run the same visibility check server-side. This route does not accept that list.

    Step-by-step Implementation

    Package path: packages/rerank/. "strict": true. No network in the unit tests.

    Step 1: Overlap stand-in and the port

    packages/rerank/src/score.ts

    typescript
    export const RERANKER_ID = "overlap-heading-v1";
    export const HEADING_WEIGHT = 2;
    /** Documented lab list. Adding a word is a test change, not a drive-by. */
    export const STOP = new Set(["the", "is", "a", "an", "for", "of", "to", "on", "my", "what", "how", "do", "i"]);
    export function tokenize(text: string): string[] {
    return text.toLowerCase().split(/[^a-z0-9]+/).filter((word) => word.length > 0);
    }
    export function contentTerms(text: string): string[] {
    return tokenize(text).filter((word) => !STOP.has(word));
    }
    /**
    * Heading hits count twice. This is not a cross-encoder.
    * refunded does not match refund.
    */
    export function overlapScore(query: string, heading: string, body: string): number {
    const terms = [...new Set(contentTerms(query))];
    if (terms.length === 0) return 0;
    const headingSet = new Set(tokenize(heading));
    const bodySet = new Set(tokenize(body));
    let headingHits = 0;
    let bodyHits = 0;
    for (const term of terms) {
    if (headingSet.has(term)) headingHits += 1;
    if (bodySet.has(term)) bodyHits += 1;
    }
    return (HEADING_WEIGHT * headingHits + bodyHits) / terms.length;
    }
    export interface RerankScore {
    ok: true;
    score: number;
    }
    export interface Reranker {
    readonly id: string;
    score(query: string, heading: string, body: string): Promise<RerankScore | { ok: false; error: "timeout" | "unavailable" }>;
    }
    export function overlapReranker(): Reranker {
    return {
    id: RERANKER_ID,
    score(query, heading, body) {
    return Promise.resolve({ ok: true, score: overlapScore(query, heading, body) });
    },
    };
    }

    Step 2: Order, degrade, reject mixed tenants

    packages/rerank/src/rerank.ts

    typescript
    import type { Reranker } from "./score.js";
    export interface Candidate {
    tenantId: string;
    chunkId: string;
    title: string;
    heading: string;
    text: string;
    }
    export type RerankResult =
    | { ok: true; rerankerId: string; ordered: Candidate[]; degraded: null | "reranker_unavailable" }
    | { ok: false; error: "empty_query" | "mixed_tenant" };
    export async function rerank(input: {
    tenantId: string;
    query: string;
    candidates: readonly Candidate[];
    reranker: Reranker;
    }): Promise<RerankResult> {
    const query = input.query.trim();
    if (query.length === 0 || query.length > 200) return { ok: false, error: "empty_query" };
    if (input.candidates.some((candidate) => candidate.tenantId !== input.tenantId)) {
    return { ok: false, error: "mixed_tenant" };
    }
    if (input.candidates.length === 0) {
    return { ok: true, rerankerId: input.reranker.id, ordered: [], degraded: null };
    }
    const scored: { candidate: Candidate; score: number }[] = [];
    for (const candidate of input.candidates) {
    let result: Awaited<ReturnType<Reranker["score"]>>;
    try {
    result = await input.reranker.score(query, candidate.heading, candidate.text);
    } catch {
    return { ok: true, rerankerId: input.reranker.id, ordered: [...input.candidates], degraded: "reranker_unavailable" };
    }
    if (!result.ok) {
    return { ok: true, rerankerId: input.reranker.id, ordered: [...input.candidates], degraded: "reranker_unavailable" };
    }
    if (result.score > 0) scored.push({ candidate, score: result.score });
    }
    scored.sort((left, right) => right.score - left.score || (left.candidate.chunkId < right.candidate.chunkId ? -1 : 1));
    return {
    ok: true,
    rerankerId: input.reranker.id,
    ordered: scored.map((row) => row.candidate),
    degraded: null,
    };
    }

    A failure on the third candidate aborts the rest and restores the full incoming order. Partial scores from a model that then timed out are not a ranking. You would be sorting on a mixture of new scores and missing rows.

    Zero overlap drops out of the healthy path so a packed budget is not spent on an error-code article for a billing question. The degraded path does not drop zeros: it preserves hybrid order, including weak chunks, because "we could not rerank" is different from "we scored you at zero."

    Step 3: Word budget

    packages/rerank/src/pack.ts

    typescript
    import type { Candidate } from "./rerank.js";
    /** Lab estimate. Not a provider tokenizer. Swap this function when the model is chosen. */
    export function estimateWords(text: string): number {
    const trimmed = text.trim();
    if (trimmed.length === 0) return 0;
    return trimmed.split(/\s+/).length;
    }
    export function packChunks(
    ordered: readonly Candidate[],
    budgetWords: number,
    ): { ok: true; packed: Candidate[]; reason: null | "over_budget" } | { ok: false; error: "bad_budget" } {
    if (!Number.isInteger(budgetWords) || budgetWords < 8 || budgetWords > 2000) {
    return { ok: false, error: "bad_budget" };
    }
    const packed: Candidate[] = [];
    let used = 0;
    for (const candidate of ordered) {
    const words = estimateWords(`${candidate.heading}\n${candidate.text}`);
    if (words > budgetWords) continue;
    if (used + words > budgetWords) continue;
    packed.push(candidate);
    used += words;
    }
    return { ok: true, packed, reason: packed.length === 0 ? "over_budget" : null };
    }

    Heading words count toward the budget because the citation UI will show the heading. Skipping a too-large chunk instead of trimming it is the grounding constraint: the next lesson quotes whole chunks.

    Step 4: Request path

    1. Run lesson 28's hybridSearch. If it errors, do not call the reranker. If it returns no hits, return no_neighbor and skip the port. You do not pay a cross-encoder to score nothing.
    2. Map hits to Candidate rows from the same visible set. If any id is missing, fail closed. Do not "look it up" without the filter.
    3. rerank with the session tenant. mixed_tenant is a 500: the server built a bad list. The user sees the abstain sentence from the next lesson, not another tenant's text.
    4. packChunks with the route's budget. The help route in this lab uses 20 so the Monday fixture has a forced choice. A long-form route uses a larger budget that still sits under the model profile's input ceiling.
    5. Return ordered ids, packed ids, rerankerId, degraded, and reason. Log the flag and the counts. Do not log chunk bodies in the shared log.
    6. Bound the port with AbortSignal.timeout. The fake in the test returns { ok: false, error: "timeout" } directly. A real adapter converts abort into that same result. One attempt. A retry doubles the tail latency and may still have been billed.

    Step 5: Run

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

    The overlap reranker reads no environment variables. An adapter that posts pairs to a vendor must fail the unit run if a key is required. Contract-test that adapter with a recorded score, in a file that is not this lesson's default test.

    Security

    • Authentication is unchanged from lesson 28. Rerank is not a second entry point that trusts a client-supplied tenant.
    • Authorization is "score only the filtered candidates." A hosted reranker is a data processor. The request body is tenant content. The vendor's retention terms belong in the adapter review before you enable it. Responsible AI, Safety and Human-in-the-Loop Design covers that review.
    • Least privilege: the rerank credential cannot query your database. If the vendor offers "upload your corpus," that is a different product and a different threat model. This port posts pairs.
    • Input validation: query length stays capped. Candidate count is the hybrid limit you already capped. Do not let a client pass N = 10000.
    • Prompt injection inside a chunk does not get a tool from this lesson, because this lesson does not follow instructions in the chunk. It scores overlap or it calls a scorer. The generator in the next lesson must still treat packed text as untrusted. Filtering the string "ignore previous instructions" is not the control.
    • Mixed tenant fails the request. It must not degrade to "rank whatever arrived."

    Error Handling

    CaseCaller getsOperator sees
    Hybrid no_neighbor200 empty, reranker not calledEmpty retrieval count
    mixed_tenant500, no passagesError log with chunk ids, no body text
    Reranker timeout or throw200, hybrid order, degradedDegraded counter and latency
    All scores zero200, empty packed listA recall problem, not a timeout
    Single chunk larger than budgetThat chunk skippedover_budget if nothing else fits
    budgetWords outside 8..2000400 bad_budgetConfig fault if the server chose it
    Port returns a score that is not finiteTreat as unavailableSame degraded path

    Degraded is still 200 because you have a first-stage order that passed authorization. Do not present it as the reranked order in the trace. The flag is part of the contract the UI and the evaluator both read.

    A timeout that you retry once will look healthier in a demo and worse on a busy afternoon. This lab does not retry. Add a single retry only when the vendor documents that the first request was not billed, or when you accept the bill in the cost review.

    Testing

    packages/rerank/src/rerank.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { packChunks } from "./pack.js";
    import { rerank, type Candidate } from "./rerank.js";
    import { overlapReranker, overlapScore, type Reranker } from "./score.js";
    const WINDOW =
    "Annual plans may be refunded within 14 days of purchase. A yearly subscription follows the same window.";
    const GLOSSARY = "A refund returns money to the original payment method.";
    const glossary: Candidate = {
    tenantId: "ten_a",
    chunkId: "chk_glossary",
    title: "Billing",
    heading: "Refund",
    text: GLOSSARY,
    };
    const windowChunk: Candidate = {
    tenantId: "ten_a",
    chunkId: "chk_window",
    title: "Billing",
    heading: "Annual refund window",
    text: WINDOW,
    };
    const QUERY = "what is the refund window for annual plans";
    test("overlap prefers the policy heading over the glossary", () => {
    const policy = overlapScore(QUERY, windowChunk.heading, windowChunk.text);
    const gloss = overlapScore(QUERY, glossary.heading, glossary.text);
    assert.equal(policy > gloss, true);
    });
    test("rerank puts the window first for a learner's visible pair", async () => {
    const result = await rerank({
    tenantId: "ten_a",
    query: QUERY,
    candidates: [glossary, windowChunk],
    reranker: overlapReranker(),
    });
    assert.equal(result.ok, true);
    if (!result.ok) return;
    assert.equal(result.degraded, null);
    assert.deepEqual(result.ordered.map((row) => row.chunkId), ["chk_window", "chk_glossary"]);
    const packed = packChunks(result.ordered, 20);
    assert.equal(packed.ok, true);
    if (!packed.ok) return;
    assert.deepEqual(packed.packed.map((row) => row.chunkId), ["chk_window"]);
    });
    test("timeout keeps hybrid order and the packer then keeps the glossary", async () => {
    const timingOut: Reranker = {
    id: "cross-encoder-lab",
    async score() {
    return { ok: false, error: "timeout" };
    },
    };
    const result = await rerank({
    tenantId: "ten_a",
    query: QUERY,
    candidates: [glossary, windowChunk],
    reranker: timingOut,
    });
    assert.equal(result.ok, true);
    if (!result.ok) return;
    assert.equal(result.degraded, "reranker_unavailable");
    assert.deepEqual(result.ordered.map((row) => row.chunkId), ["chk_glossary", "chk_window"]);
    const packed = packChunks(result.ordered, 20);
    assert.equal(packed.ok, true);
    if (!packed.ok) return;
    assert.deepEqual(packed.packed.map((row) => row.chunkId), ["chk_glossary"]);
    });
    test("a second tenant fails closed", async () => {
    const foreign: Candidate = { ...windowChunk, tenantId: "ten_b", chunkId: "chk_window_b" };
    const result = await rerank({
    tenantId: "ten_a",
    query: QUERY,
    candidates: [glossary, foreign],
    reranker: overlapReranker(),
    });
    assert.deepEqual(result, { ok: false, error: "mixed_tenant" });
    });
    test("a chunk bigger than the budget is skipped, not sliced", () => {
    const huge: Candidate = { ...windowChunk, chunkId: "chk_huge", text: "word ".repeat(30) };
    const packed = packChunks([huge, glossary], 20);
    assert.equal(packed.ok, true);
    if (!packed.ok) return;
    assert.deepEqual(packed.packed.map((row) => row.chunkId), ["chk_glossary"]);
    });

    The timeout test is the production story in miniature: degradation is allowed, silent confidence is not. Assert degraded in the API response fixture before you celebrate a green path that only uses overlapReranker.

    Performance and Cost

    A cross-encoder's bill is roughly N forward passes, each proportional to query length plus chunk length. Overlap scoring is a local loop and is not the line item. The line item starts when the port stops being local.

    • Keep N at the hybrid limit. Reranking the whole table "for quality" is how a 40-millisecond search becomes a 4-second search.
    • Batch the vendor call if the API allows a list of pairs in one request, and still enforce one timeout for the batch. N serial round trips will blow the help-route budget even when each call is fast.
    • Cache a score only for a public, non-personalized query, and include rerankerId plus chunk version in the key. A personalized question is not a shared cache entry.
    • Set the timeout from the route budget, not from the vendor's maximum. A help box that waits ten seconds has already failed the product even if the score would have been better.
    • Count degraded requests. A 2% timeout rate on a paid reranker is a cost and a quality issue: you are billed for failures and you are serving hybrid order.
    • The word estimator is cheap. Do not call the provider's tokenizer service once per chunk on the hot path if a local approximation is close enough to enforce the ceiling. Do calibrate the approximation so you do not overrun the model limit by a wide margin. A budget of 20 words in this lab is a teaching constraint, not the production ceiling.

    CPU on the overlap path is negligible next to a remote model. Memory stays flat because you do not copy the corpus into the reranker process. If a future process does, you have changed the trust boundary. Say so in the design review.

    Knowledge Check

    1. What problem does reranking solve?

    The first stage recalled both the glossary and the 14-day policy because both look like refunds to hybrid search. The context budget can hold one of them. Reranking reads the query and each chunk together so the policy, which matches window, annual, and plans, is packed first. The overlap scorer demonstrates the slot. A cross-encoder is the production occupant of that slot.

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

    Hybrid order alone, when N is already the context size and a second stage would add latency you cannot spend. Overlap or a linear feature model, when you need a deterministic baseline and an audit trail. A cross-encoder, when the relevant chunk is stuck behind a distractor and the golden set says the hosted scorer fixes it often enough to pay for N passes. MMR, when the packed set is redundant. Query rewriting, when recall is the failure and you have evaluated the rewriter. A larger context window, when packing is dropping a second fact you measured as necessary. Buying a larger window does not fix a wrong rank 1.

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

    The candidate list is server-built from the session's visible chunks. The reranker port receives that text and no database credential. mixed_tenant is a hard error. A hosted model provider sees the query and the passages, so those passages must already be allowed to leave the trust zone. The degraded flag is part of the user-visible contract, not an internal comment.

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

    Timeout, throw, and unavailable keep hybrid order and set degraded. An empty hybrid list does not call the port. A mixed-tenant list returns no passages. A chunk larger than the budget is skipped whole. If nothing fits, the generator receives no passage and abstains. A zero from the overlap scorer drops that chunk on the healthy path only.

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

    The unit tests lock the Monday order, the timeout pack, the foreign tenant, and the unsliced chunk. Offline quality is: relevant chunk recalled in N, and relevant chunk packed in M, as two rates. Security review checks that the adapter posts pairs and cannot list the corpus. Performance review is latency at the chosen N and timeout. Cost review is passes per query times price, plus the degraded rate you still pay for. Lesson 31 stores those rates.

    Hands-on Assignment

    Lab note. Use overlapReranker in the default test. A remote cross-encoder is a port implementation, not a requirement.

    Problem. Given hybrid order [chk_glossary, chk_window], pack a 20-word budget so the healthy path returns only the annual window, and the timeout path returns only the glossary plus degraded.

    Tasks.

    1. Implement overlapScore, rerank, and packChunks.
    2. Explain in four lines why raising the word budget to 40 changes the product: both chunks fit, so rank matters less and cost of generation goes up.
    3. Add a reranker double whose id is cross-encoder-lab and whose score function returns timeout. Keep it in the test, not behind an API key.
    4. Write the rule for query rewriting you are not shipping: original query still runs, rewriter output is evaluated, injected text in a chunk is not a query.
    5. Name the metric that tells you to widen N versus the metric that tells you to fix the reranker.

    Deliverable. Diagram of recall then precision, source with no secrets, test output, and the note on N versus M.

    Challenge. A second policy chunk says the same 14-day rule in different words and arrives in the pool. Describe MMR in terms of this pair, pick a lab λ, and say why you would not turn it on until a case in the golden set needs both chunks. Do not implement a second ranker in the default path.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation 25%. Security and tenant failure behavior 20%. Tests, timeout, and budget behavior 20%. Documentation of what was not shipped 15%.

    Common Mistakes

    1. Reranking the corpus. Symptom: help search takes seconds and the bill tracks catalog size. Cause: the cross-encoder replaced the first stage. Fix: rerank N hybrid hits.
    2. Treating overlap as understanding. Symptom: a paraphrase with no shared content terms abstains after a "smart" rerank. Cause: the stand-in was described as a cross-encoder. Fix: keep RERANKER_ID honest, and accept empty overlap as a miss.
    3. Dropping foreign chunks and continuing. Symptom: a test never catches a broken join, and a vendor still saw the text. Cause: filter-after-score. Fix: mixed_tenant before any score call.
    4. Slicing a chunk to fill the budget. Symptom: a citation shows "refunded within" and drops "14 days." Cause: the packer trimmed strings. Fix: skip the whole chunk.
    5. Timeout with no flag. Symptom: the glossary ships as if it won a cross-encoder. Cause: the catch block returned ordered candidates and omitted degraded. Fix: the timeout test.
    6. Retrying a slow reranker on the user path. Symptom: p95 latency is double the timeout. Cause: a retry policy copied from an idempotent read of your own database. Fix: one attempt, then hybrid order.
    7. Shared cache without reranker id. Symptom: scores from the overlap stand-in serve after you deploy a cross-encoder. Cause: the cache key was the query string. Fix: include rerankerId and document version.
    8. Query rewriting by default. Symptom: PGV-2041 gets rewritten into a sentence about errors and the keyword leg misses. Cause: the original string was replaced. Fix: keep the raw query as a leg until the eval says otherwise.
    9. MMR before relevance. Symptom: a diverse pack of loosely related chunks and no policy. Cause: λ was tuned by taste. Fix: win the Monday ordering first.
    10. Sending staff chunks because they were "already in memory." Symptom: a learner trace contains a runbook id. Cause: the reranker input was the unfiltered array. Fix: build candidates from the hybrid hits, which were already visible.

    Summary

    The first stage is there to recall. The reranker is there to spend a small context budget on the chunk that matches the question, not merely the topic. A heading-weighted overlap score makes that order testable on the refund window, and a port keeps a future cross-encoder in the same timeout and tenant contract. When the port fails, hybrid order stands, the degraded flag is visible, and the packer still refuses to slice a passage. Nothing in this stage invents a chunk the retriever never returned. The passages that survive are the only ones the next lesson is allowed to quote.

    Next Lesson Preview

    Grounded Answers, Citations and Source Attribution takes the packed passages and refuses to let a model replace "14 days" with "90 days." You will render quotes from the server, ignore model-written URLs, and abstain when the selected chunk ids are not in the packed set.

    Further Reading

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