Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 7: Embeddings and RAG

Week 07 / Lesson 2

Combining retrieval methods

Improve candidate selection without allowing unauthorized evidence into context.

Section 2.1 1 of 7

Overview

Focus

Improve candidate selection without allowing unauthorized evidence into context.

Your route through the lesson

  • 2.2 Keyword search and dense search
  • 2.3 Hybrid ranking and reranking
  • 2.4 Permission filters and retrieval limits
  • 2.5 Put it into practice
  • 2.6 Guided comparison
  • 2.7 A private document ranked as most similar

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 7

Keyword search and dense search

Focus

Compare exact-term matching with similarity in an embedding space.

Lexical retrieval uses words or identifiers in the query and documents. A simple version counts shared terms. More sophisticated versions reward informative terms and reduce the effect of repetition. Dense retrieval compares embeddings, which can connect different wording when the encoder represents the relationship. Neither method dominates every question.

Suppose passage A says “ZX-41 reset instructions,” passage B says “Recover access when credentials are lost,” and the query is “forgot password.” Exact overlap may miss B entirely, while a useful semantic representation connects “forgot password” with “credentials are lost.” For the query “ZX-41,” exact overlap strongly identifies A, while an encoder that collapses product codes may tie A with another device.

Normalize text carefully. Lowercasing can help ordinary words, but splitting ZX-41 into unrelated pieces can weaken an identifier match. Preserve literal identifiers as tokens or structured fields. Compare both retrievers on the same fixed questions and source set so that a ranking difference is attributable to the retrieval method rather than a changed corpus.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A document says “credentials are lost”; the query says “forgot password.” Why might dense retrieval help?
2. The query is the exact product code ZX-41. Which signal is especially valuable?
3. Two retrieval methods use different corpora during a comparison. What is the problem?

Section 2.3 3 of 7

Hybrid ranking and reranking

Focus

Combine ranked candidates and then score query-passage pairs more carefully.

Raw lexical and dense scores have different scales. Adding a lexical score of 12 to cosine 0.8 gives lexical magnitude an arbitrary advantage. One simple hybrid method combines ranks instead. Reciprocal rank fusion assigns each candidate 1 / (k + rank) for each list containing it, then adds those values. The constant k softens the difference between early positions; ranks start at one.

With k = 10, a passage ranked first lexically and second densely receives 1/11 + 1/12, approximately 0.1742. A passage appearing only first in the dense list receives 1/11, approximately 0.0909. Agreement across lists can therefore lift a candidate. Choose k and candidate limits using development queries, then report results on untouched queries.

A reranker examines each query-passage pair after initial retrieval and reorders the small candidate set. It may use a learned model or a transparent rule. The lab uses an explicit identifier-aware rule so its behavior is inspectable. Reranking cannot recover a relevant document absent from its candidate pool, and a higher rerank score still does not establish claim support.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. With fusion constant 10, a passage appears at rank 1 in one list and rank 2 in another. What is its score?
2. A reranker receives five candidates; the relevant passage is not among them. What can it do?
3. A lexical score is 18 and a dense cosine is 0.7. Why avoid simply adding them?

Section 2.4 4 of 7

Permission filters and retrieval limits

Focus

Exclude unauthorized evidence before ranking and enforce a bounded context.

Permission filtering asks whether the authenticated caller may use a passage. Relevance asks whether it helps answer the question. These are independent decisions. A private incident report can be the best semantic match and still be unavailable. The authenticated identity comes from the application, not a user_id field proposed by a model.

Take three passages: public reset steps, team-only troubleshooting notes, and another customer’s secret recovery code. A caller authorized only for public content should search only the first. Filtering after taking the top two can return an empty list even when the public passage was third. Worse, sending the top two to a reranker before filtering has already disclosed restricted text to that component. Apply access control before every component that sees content.

Limits also shape the evidence. A candidate limit controls reranker work; a context limit controls the text sent to the answer model. Deduplicate overlapping chunks so repeated content does not crowd out a separate condition or exception. Record what was excluded and why using safe identifiers, while avoiding sensitive text in logs.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A private passage ranks first but the caller has public-only access. When should it be removed?
2. A model supplies user_id = admin in tool arguments. Which identity should retrieval trust?
3. The top two unfiltered results are private; a public relevant result is third. What improves eligible retrieval?

Section 2.5 5 of 7

Put it into practice

Focus

Compare four retrieval stages on identical fixtures and inspect what enters context.

Save week07.py in your exercise folder and run python week07.py --lesson 2. This processor-only exercise reuses the small corpus and encoder from the first lesson. The output shows lexical, dense, fused, and reranked identifiers. It also prints the identifiers eligible for a public caller. No service account or internet connection is needed.

Python’s enumerate(items, 1) attaches positions starting at one. A dictionary stores each identifier’s accumulated fusion score. The membership test checks whether a document survived authorization. This focused example shows rank fusion’s central update:

scores = {}
for ranking in [["A", "B"], ["B", "C"]]:
    for rank, identifier in enumerate(ranking, 1):
        scores[identifier] = scores.get(identifier, 0) + 1 / (10 + rank)
assert scores["B"] > scores["A"]

The get call returns zero for a missing dictionary entry. B appears twice and receives two contributions; A receives one. In the weekly lab, verify that the restricted record never appears in any public candidate text, including the reranker input. The expected rankings demonstrate transparent fixture behavior, not a benchmark of a trained embedding or reranking model.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. In a Python fusion dictionary, what does scores.get("A", 0) do when A is absent?
2. A occurs once at rank 1; B occurs at rank 2 and rank 1. With positive reciprocal contributions, why can B lead?
3. A public-search test inspects only the final answer. What additional trace is needed to detect earlier disclosure?

Section 2.6 6 of 7

Guided comparison

Focus

Explain why an improved ranking still needs independent authorization checks.

Follow a completed product lookup. The lexical list is [product-A, public-reset], while the dense list is [private-note, public-reset, product-A]. The public caller cannot use private-note, so it is removed before fusion or reranking. The eligible dense list becomes [public-reset, product-A]. Both surviving candidates now receive two fusion contributions.

An identifier-aware reranker checks whether the requested code occurs in each candidate’s structured product field. product-A matches ZX-41; public-reset is general advice. It places product-A first. This is a documented rule, not a learned relevance judgment. It helps the exact-code fixture while potentially doing nothing for a paraphrase query without a code.

Now imagine the system instead fuses all three and logs the entire private-note text before removing it. The final answer may look safe, but the pipeline has already violated the permission boundary. The comparison therefore records eligible candidate identifiers at each stage and confirms that unauthorized text never enters a component lacking that access. Success requires both useful ranking and correct access enforcement, measured separately so that a gain in one cannot conceal a failure in the other.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A public caller’s dense list contains a restricted note before two public candidates. Which list should fusion consume?
2. An identifier-aware reranking rule fixes exact-code queries but does not improve paraphrases. What should the report say?
3. Restricted text is logged before final filtering, but the answer omits it. Did the permission check succeed?

Section 2.7 7 of 7

A private document ranked as most similar

Focus

Handle a highly relevant private document without substituting authority for similarity.

A public support assistant receives “Why was tenant North disconnected?” A confidential incident report names North and gives the cause. Public status notes mention only a general outage. The private report is an excellent lexical and semantic match, but the caller’s entitlement allows only public status information.

The completed response pipeline excludes the incident report before retrieval text is exposed. It retrieves the public outage note and can state only what that note supports, such as “A regional interruption was reported at 09:00.” It must not infer the tenant-specific cause from the excluded document. If the question requires that private detail, the assistant explains that the available authorized sources do not establish it.

This case separates three outcomes: a relevant document exists, an authorized relevant document is available, and an authorized document supports the requested claim. They need not occur together. An access-denied result should preserve the boundary while offering an appropriate authorized path, such as directing the caller to their organization’s support process. It should not reveal the private report’s title or snippets merely to prove that the system found it.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A public caller asks for a tenant-specific cause. Only a private report supports it. What is justified?
2. A public outage note establishes a regional interruption but no tenant cause. Which claim is supported?
3. Why report authorization failures separately from ranking quality?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Grounding answers and measuring retrieval →