Module 06: Projects

Retrieval3 projects0 of 3 complete

Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.

Three projects: one starter and two stretches (the retrieval service is optional). Everything runs keylessly and serverless — embeddings come from a small open-weight model that sentence-transformers downloads once (~90 MB, no key), vectors live in the pure-NumPy NumpyVectorStore, Qdrant local mode or Chroma's embedded client, and every reranker and retriever has a deterministic fake. Hosted embedding and rerank APIs are the marked extensions for each project.

First time? Create the shared project once:

bash
uv init vector-search --bare --python 3.13 && cd vector-search

Then uv add the packages each project's Setup names, and run scripts with uv run python file.py. The starter project needs no .env file at all; the stretch projects add keys only for their optional hosted steps.

The reusable spine. The projects assemble the seams the lessons built: the Embedder protocol and its adapters including LocalSTEmbedder and FakeEmbedder (06.1), the embedding-space version guard (06.1, Part 9), pack_batches and validate_embeddings (06.2), the VectorStore protocol with NumpyVectorStore and the store adapters (06.5), FilterSpec and its translators (06.6), the BM25 class and tokenize (06.7), the fusion library (06.8), the Reranker protocol and retrieve_fuse_rerank_trim (06.9), and the Retriever/Hit types, metrics.py, harness.py and eval_queries.jsonl (06.10). Where a project says "copy the file from lesson X", the full source is printed in that lesson — copy it verbatim, then modify.

The running corpus. Every project uses the module's shared Acme corpus — handbook policies, help-centre articles, tickets and contracts — as the fourteen chunks in 06.10's corpus.py (the same texts 06.5 uses, extended). Its deterministic toy vectors are for the lessons' plumbing demos; the projects replace them with real embeddings. If you finished Module 05's starter project and have a chunks.jsonl, an adapter in step 3 of the starter project shows how to use it instead — but nothing here requires it.


Starter

Starter: Semantic search over the running corpus#

Goal: Turn the fourteen Acme chunks into a searchable index: embed them with a real local model, store the vectors behind the VectorStore protocol, and build a CLI (then a small FastAPI endpoint) that answers natural-language questions with metadata filters — the whole 06.1 → 06.6 pipeline on one screen.

What you'll practise:

  • The Embedder protocol and swapping backends without touching search code (lesson 06.1, Part 10)
  • Running an open-weight model locally with sentence-transformers, including max_seq_length and normalization (06.1, 4.1)
  • Recording the embedding-space metadata every stored vector needs — model ID, dimensions, task type, preprocessing hash (06.1, Part 9)
  • Batching under limits and validating vectors before they poison the index (06.2, 2.3, 11.2)
  • The VectorStore contract, the exact NumpyVectorStore, and Chroma/Qdrant local mode as drop-in alternatives (06.5, Part 7)
  • Building filters safely from user input with FilterSpec and translating them per store (06.6, 2.3, 1.3)
  • The metric conventions that make "similar" mean something (06.3, 2.2)

Setup:

bash
uv add numpy sentence-transformers pydantic pytest
# optional store alternatives (both run with no server):
uv add chromadb qdrant-client
# optional FastAPI endpoint:
uv add fastapi uvicorn
# hosted providers, only if you add the extension:
uv add openai google-genai python-dotenv

(Or pip install the same package names.) These install the newest release of each package; the samples were checked against the versions in each lesson's Setup (for example sentence-transformers 6.2.0, chromadb 1.5.9, qdrant-client 1.20.0, fastapi 0.162.0 and uvicorn 0.54.0 as of November 2026), and a newer major version may change names, so check the library's changelog if something does not match. sentence-transformers downloads the model weights from Hugging Face on first use; everything else is local. No .env needed for the core path.

Steps:

  1. Create the project and the corpus. Run the uv init above, then copy corpus.py from 06.10, Part 4 verbatim — it builds CHUNKS (fourteen Chunk records with id, doc_id, section, text, metadata) deterministically. Write export_chunks.py that emits one JSON object per chunk to chunks.jsonl with fields id, doc_id, section, text, metadata — drop vector, topic and domain (the toy-vector scaffolding the projects replace). Module 05 alternative: if you have data/chunks/chunks.jsonl from that module's starter project, emit the same five fields from it instead — id←chunk_id, section←section_path, metadata←meta — and the rest of this project is unchanged.
  2. Copy the embedder seam. Copy embedder_protocol.py and the LocalSTEmbedder and FakeEmbedder classes from 06.1, Part 10 into embedder.py. Instantiate LocalSTEmbedder("sentence-transformers/all-MiniLM-L6-v2") — its encode_document/encode_query path is the lesson's adapter; MiniLM needs no task prefixes (06.1, 3.1). Keep FakeEmbedder(dims=64) for tests.
  3. Embed the corpus. Write embed_corpus.py: load chunks.jsonl, call embedder.embed_documents([c["text"] for c in chunks]) (batch through pack_batches from 06.2, 2.3 if the corpus ever outgrows one call), run validate_embeddings(vectors, expected_dim=embedder.dimensions) from 06.2, 11.2 on the result, and write vectors.jsonl — one line per chunk carrying id, vector, and the embedding-space metadata from 06.1, 9.1: model_id, dimensions, task_type (document), preprocessing version and created_at. Re-running must produce identical vectors (the local model is deterministic on CPU — if yours differs, check torch threading settings before blaming the pipeline).
  4. Load the store. Copy vector_store.py and numpy_store.py from 06.5, Parts 7.1–7.2. Write load_store.py that reads vectors.jsonl + chunks.jsonl, builds VectorRecord(id=..., vector=..., text=..., metadata=...) per chunk (copy section and doc_id into metadata as well, so search.py can print the section and a hit can be traced to its document) and calls store.upsert(records) on a NumpyVectorStore(dim=embedder.dimensions). Print the record count and a sample store.get(id).
  5. Prove the store seam. Run the same load_store.py against ChromaVectorStore (chromadb.PersistentClient(path="./chroma_db"), 06.5, 6.1) and QdrantVectorStore in local mode (QdrantClient(path="./qdrant_db"), 06.5, 5.2) by adding a --store flag — the whole point of the protocol is that only the adapter changes. Then run the contract test from 06.5, 7.4 against all three.
  6. Filters that are safe. Copy filter_spec.py from 06.6, 2.3 — it gives you Predicate, FilterSpec, Op, the ALLOWED field allow-list and validated(). The lesson's ALLOWED names tenant_id, doc_type and language, but this corpus's metadata fields are tenant, kind and lang, so rename those three keys (keep their operators) before you use it; otherwise --filter tenant=acme is rejected as "not filterable". That rejection is the allow-list working, not a bug. Write spec_to_store(spec) translating validated predicates into each store's filter shape: to_chroma() and to_qdrant() already exist in the lesson; for NumpyVectorStore write ~15 lines mapping predicates to its {"field": {"$in": [...]}} / {"field": value} dict form (its _matches supports equality, ranges and $in).
  7. The CLI. Write search.py: python search.py "how much vacation do I get" --k 5 [--filter tenant=acme] [--filter kind=policy]. It embeds the query with embedder.embed_query, parses --filter args into Predicates (never raw store syntax — that's the whole lesson of 06.6, 2.3), validates the FilterSpec, calls store.query(query_vec, top_k=k, filters=...), and prints rank id score section text-snippet per hit. Sort ties deterministically.
  8. Test without a model. Write test_search.py with FakeEmbedder: upsert the corpus, assert search("vacation") returns handbook-001/handbook-002 in the top results (the fake hashes words into shared dimensions, so same-topic chunks cluster), assert a tenant=acme filter excludes ticket-77/contract-9, and assert an impossible filter returns [] not an error.
  9. The endpoint (optional but recommended). Add serve.py: POST /search taking {"query": str, "k": int, "filters": {...}}, building the FilterSpec server-side, calling the same store.query, returning [{id, score, section, text}]. Cap k and query length; never interpolate filter values into store syntax (06.6, 2.3 owns why). uvicorn serve:app --reload and curl it.
  10. Swap in a hosted embedder (extension, needs a key). Add OpenAIEmbedder/GeminiEmbedder from 06.1, Part 10, re-run embed_corpus.py into vectors_openai.jsonl, and compare top-5 results on your question set against MiniLM's. Do not mix the two vector files in one store — that's the silent-failure the version guard exists for (06.1, 9.2).

Verify it, and what you should see:

bash
uv run python export_chunks.py && wc -l chunks.jsonl          # 14 lines
uv run python embed_corpus.py                                 # downloads ~90 MB once, then embeds
uv run python load_store.py --store numpy                     # 14 records
uv run pytest -q test_search.py                               # all pass
uv run python search.py "how much vacation do I get" --k 5
uv run python search.py "net-30 payment terms" --k 5 --filter tenant=acme
uv run python search.py "net-30 payment terms" --k 5 --filter tenant=initech

What to check, concretely:

  • vectors.jsonl has 384-dim vectors (MiniLM-L6) with model_id, dimensions, task_type on every line; a second embed_corpus.py run produces identical vectors.
  • The vacation query puts handbook-001 ("accrue 1.5 days of paid vacation per month") first or second — real semantic match, not word overlap. Exact-identifier queries like VPN-ERR-2041 may rank worse than keyword search would; that's expected and is what 06.7 and the stretch project fix.
  • --filter tenant=acme on the payment-terms query returns only acme chunks, with low scores because nothing in that tenant is about payment terms — contract-9 belongs to initech and must not appear; --filter tenant=initech returns it first. This is the cross-tenant leak check from 06.6 in miniature.
  • store.query on NumpyVectorStore is exact cosine k-NN — your scores are cosine similarities in [-1, 1] because MiniLM emits normalized vectors (06.3, 2.2).

Illustrative output (your exact ranking and scores will differ — they depend on the model and its version):

text
# search.py "how much vacation do I get" --k 3
 1  handbook-001  0.71  Leave > Vacation      Full-time employees accrue 1.5 days…
 2  handbook-002  0.58  Leave > Sick Leave    Sick leave is separate from vacation…
 3  handbook-005  0.44  Leave > Parental      Parental leave: 16 weeks…

# search.py "net-30 payment terms" --k 3 --filter tenant=acme
 1  handbook-003  0.19  Expenses > Per Diem   Domestic travel per diem is $75 per day…
 2  handbook-004  0.15  Expenses > Reviews    Expense reports are reviewed by your manager…
 3  help-103      0.09  Access > Password    To reset your password, choose 'Forgot password'…
  (no contract-* chunk: the only matching chunks belong to initech)

# search.py "net-30 payment terms" --k 3 --filter tenant=initech
 1  contract-9    0.83  MSA > 2025 Terms       Master service agreement: payment terms net-30…
 2  contract-10   0.51  MSA > 2025 Terms       Renewal notice must be given 60 days…

Done when:

  • chunks.jsonl, vectors.jsonl and a loaded store exist; re-running the embed step is deterministic.
  • search.py answers the probe queries above correctly: the vacation query finds the leave chunks, tenant=initech returns the contract chunks, and tenant=acme never returns a contract-* chunk.
  • The same VectorRecords load into at least two stores (numpy plus chroma or qdrant) with identical query results, and the contract test passes on each.
  • Every stored vector carries its embedding-space metadata, and test_search.py passes with FakeEmbedder and no model download.
  • You can explain in two sentences why applying the tenant filter before ranking matters, and why your filter values can never come straight from client input (client input → FilterSpec → allow-list).

Stretch ideas:

  • Add the content-hash CachingEmbedder from 06.2, 5.3 in front of LocalSTEmbedder and show the second embed_corpus.py run is all cache hits — then change one chunk's text and show only it re-embeds.
  • Swap NumpyVectorStore for pgvector: the docker run pgvector/pgvector:pg17 reference and full pgvector_store.py are in 06.5, Parts 4 and 7.3; add the HNSW index and an EXPLAIN check that it's used.
  • Local model bake-off (keyless): run the 06.1, Part 8 harness over two or three models from the 06.1, 4.6 shortlist (for example Qwen/Qwen3-Embedding-0.6B, Apache-2.0, or google/embeddinggemma-300m, which needs you to accept Google's Gemma terms on Hugging Face). Use each model's documented query/document prompts through LocalSTEmbedder(prompts=...), record dimensions and max_seq_length, and stamp each vectors_<model>.jsonl with its own space metadata. Fourteen chunks cannot rank models, so treat the result as a plumbing check and say so.
  • Add MMR diversification from 06.3, 5.2 as a --diversify flag so near-duplicate leave chunks don't fill the top-k.
  • Needs a key: wire OpenAIEmbedder or VoyageEmbedder-style adapters, embed the same corpus, and run the 06.1, Part 8 test-set comparison between MiniLM and the hosted model — recall@k and MRR, not vibes.

Common problems:

  • Model download fails or is slow. sentence-transformers fetches weights from Hugging Face on first SentenceTransformer(...) call — check your network/proxy, or set HF_HOME to a writable cache dir. The FakeEmbedder path in test_search.py needs no download at all.
  • normalize_embeddings in the wrong place. It's an encode()-family argument, not a constructor argument — the lesson's LocalSTEmbedder already passes it through; don't "fix" it by setting an attribute (06.1, 4.1).
  • Dimension mismatch on upsert. NumpyVectorStore(dim=...) must equal embedder.dimensions; assert it at startup — the 06.1 failure gallery lists this as the classic silent-ish bug.
  • Filters return everything or nothing. Check your spec_to_store mapping: NumpyVectorStore._matches treats a bare value as equality and a dict as operators — a Predicate(op="in", value=[...]) must become {"$in": [...]}, not a nested dict the store can't read. And remember Chroma has no $not — the lesson's to_chroma already inverts operators for you.
  • Toy-corpus expectations. With only fourteen chunks, "semantic search" is partly word overlap — don't conclude MiniLM is bad because VPN-ERR-2041 ranks poorly; that's the lexical-gap lesson of 06.7, and the stretch project measures it properly.

Stretch

Stretch: Hybrid retrieval benchmark#

Goal: Assemble the module's second half into one measurable system — BM25 + dense retrieval fused with RRF (and the other fusion methods), an optional reranking stage, all behind the Retriever protocol — then evaluate every configuration on the labelled 16-query set with recall@k, MRR and nDCG, bootstrap confidence intervals, a sweep over the tuning knobs, and a written failure analysis. The whole thing runs on the deterministic toy corpus with zero keys; swapping in real MiniLM embeddings is the marked extension.

What you'll practise:

  • The Retriever protocol as the single seam every configuration satisfies (lesson 06.10, 4.1)
  • The labelled eval set: qrels, dev/test splits, query types, the filtered-empty leak check and the no-answer query (06.10, 4.2)
  • Every retrieval metric and the harness: run_eval, aggregate_by, compare_runs with bootstrap CIs, failures (06.10, Part 3, 4.3)
  • BM25 as a first-class retriever, not a library demo (06.7, 3.5, 4.1)
  • Fusion methods beyond RRF — score fusion, Borda, DBSF, interleaving — and what incomparable scores do to naive addition (06.8, Part 2)
  • The two-stage architecture: candidate depth N, final k, and the Reranker protocol with IdentityReranker/KeywordReranker fakes (06.9, Part 1, 9.1)
  • The tuning loop: one change at a time, sweep on dev, confirm on test (06.10, Part 6)
  • Failure analysis: the miss taxonomy and triage table (06.10, Part 5)

Setup:

bash
uv add numpy pytest
# optional: real embeddings for the extension step
uv add sentence-transformers
# optional: a real local cross-encoder reranker
uv add sentence-transformers   # model downloads on first use
# hosted rerankers, only for the marked extension:
uv add cohere voyageai openai python-dotenv

Steps:

  1. Copy the eval spine verbatim. From 06.10 copy corpus.py, metrics.py, retrievers.py, eval_queries.jsonl, harness.py, spans.py, query_techniques.py and demo.py into the project. Run uv run python demo.py and read its headline table — this is the lesson's own three-way comparison (toy dense, toy BM25, hybrid-RRF) on the 16-query set. Everything below modifies configurations, never the metrics.
  2. Understand the baseline. Open eval_queries.jsonl and note the contract: relevant maps chunk IDs to grades (2 = answers, 1 = useful), needed marks multi-chunk answers, filters exercises the tenant check, split is dev vs test. Run harness.py's failure browser on the weakest retriever and read five misses before changing anything (06.10, 5.2).
  3. Add the fusion library. Copy fusion.py from 06.8, Part 2 — it has rrf, borda, score_fusion, dbsf and interleave over RankedLists. Write fusion_retrievers.py with a FusionRetriever class implementing 06.10's Retriever protocol: it holds a dict of first-stage retrievers ({"dense": ..., "bm25": ...}), calls each search(), converts Hits to RankedLists, fuses with a chosen function, and maps fused IDs back to Hits (keep the max first-stage score and set source="fusion:<method>"). Register configs: rrf, score_fusion_minmax (α=0.5), borda, interleave.
  4. Measure the fusion variants. Run run_eval + aggregate on each config over the dev split; print a table of recall@10, mrr, ndcg@10 per config. Expect RRF to be the robust default — the lesson's warning is that raw-score fusion needs normalisation and the toy BM25/dense scores live on different scales (06.8, 2.1).
  5. Add the rerank stage. Copy reranker.py and adapters_rerank.py from 06.9, Part 9 — IdentityReranker (baseline/fallback) and KeywordReranker (deterministic fake). Write RerankedRetriever(Retriever): search() calls the fused retriever for rerank_depth candidates, calls reranker.rerank(query, hits), trims to k. Mind the seam: 06.9's Hit has no source field — map it through (add source to metadata or reconstruct it) rather than letting provenance die at the boundary.
  6. Sweep the second stage. Grid rerank_depth ∈ {10, 50, 200} × final_k ∈ {3, 5, 10} × {identity, keyword} reranker on dev. The lesson's bound applies: recall@N of the first stage caps everything downstream, so check whether depth 200 beats 50 on this corpus before assuming it does (06.9, 6.1).
  7. Compare with statistics. Use save_run/compare_runs from harness.py: save the best dev config and the dense-only baseline, then compare_runs them — read the paired difference and bootstrap CI, not just the point estimate (06.10, 4.5). With 16 queries the CIs will be wide; say so.
  8. Confirm on test, then analyse. Take the single best dev config, evaluate it on the test split only, and record the delta vs dev — that gap is your overfitting signal (06.10, 6.4). Run failures() on it, classify each miss with the 5.1 taxonomy, and write FAILURE_ANALYSIS.md: for each miss, the fix and the lesson that owns it (re-chunk → 05, hybrid → 06.8, rerank → 06.9, query rewrite → 06.10 Part 7).
  9. Query techniques, measured. Wire query_techniques.py's multi_query_retrieve and hyde_retrieve behind the same Retriever protocol (they already return fused Hits) and evaluate multi-query and hyde as configs on the ambiguous/multilingual/multi-hop types only — the lesson's evidence is mixed, so let your numbers decide (06.10, 7.8).
  10. Write the memo. One page: the config table (retriever × fusion × rerank × k → metrics on dev and test), which differences beat the bootstrap CI, the failure analysis, and what you'd change first at 100k chunks (the answer is probably "real embeddings + a real store", not more fusion knobs).

Verify it, and what you should see:

bash
uv run python demo.py                        # the lesson's baseline: three retrievers, one table
uv run python run_benchmark.py               # your sweep: one row per config
uv run python compare_runs.py                # paired diff + bootstrap CI, best vs baseline
cat FAILURE_ANALYSIS.md

Invariants that must hold on the toy corpus (they're deterministic — if one breaks, it's a bug, not noise):

  • q04 ("VPN-ERR-2041", an exact identifier) is won by BM25-containing configs; pure dense should miss it — that's the lexical-gap lesson made visible.
  • q15 (the Spanish vacation question) is won by dense-containing configs; BM25-only cannot match it.
  • q16 (the cross-tenant trap) never returns contract-9, or any other chunk outside the acme tenant, under its tenant=acme filter on every config: the harness's leaked flag stays False. A forbidden chunk in the results is a leak, full stop (06.10, 4.2, 06.6). The query is excluded from the metric averages; the leak flag is its test.
  • q13 (office wifi password) is a no-answer query: your configs will still return something (retrieval always returns k); the honest metric treatment is the lesson's abstention discussion, not a metric hack.
  • RRF configs beat naive score addition on the demo rankings — demo_fusion.py's printed warning shows BM25's ~14 swamping cosine's ~0.9 (06.8, 2.3).

Done when:

  • One command reproduces the baseline and your full config sweep, and every run is saved with provenance (config + evalset hash + code version) via save_run.
  • You've reported dev and test numbers for your chosen config, with a bootstrap CI on the key comparison and an honest statement of sample size.
  • FAILURE_ANALYSIS.md classifies every miss on the test split and maps each to an owning lesson.
  • You can name the single highest-payoff change your numbers support, and the one change the numbers don't support (overfitting check).
  • q16 provably never leaks (leaked is False on every config) and q04/q15 show the expected lexical/dense split.

Stretch ideas:

  • Real embeddings, still keyless: write RealDenseRetriever implementing the protocol — embed each chunk's text once with LocalSTEmbedder (reuse the starter project's vectors.jsonl), embed queries with embed_query, cosine-rank. Re-run the whole benchmark; the ranking of configs may flip — that's the finding.
  • A real reranker: swap KeywordReranker for LocalCrossEncoderReranker (cross-encoder/ms-marco-MiniLM-L6-v2, ~22M params, CPU-friendly — 06.9, 2.3–2.4) and re-sweep rerank_depth; measure the latency it adds per query.
  • Three-way fusion: add a learned-sparse or second-lexical retriever (e.g. a second BM25 over section+text fields, the BM25F idea from 06.7, 3.7) and fuse dense+sparse+bm25.
  • Needs keys: hosted rerankers (Cohere/Voyage/Jina/OpenRouter — request shapes in 06.9, Part 3) and hosted embeddings; cache rerank results per 06.9, 3.7.

Common problems:

  • Hit-shape mismatch at the seam. 06.8/06.9/06.10 each define Hit slightly differently (source field, field order). Normalise to 06.10's Hit inside your adapters — provenance (source) is what makes "which side won" analysable later.
  • Scores compared across retrievers. Never average or threshold raw dense cosine against raw BM25 — that's the 06.8, 2.1 trap; fuse on ranks (RRF/Borda) or normalised scores only.
  • Reranking only the top 10. If the answer sits at rank 40, rerank_depth=10 guarantees the miss — check first-stage recall@N before blaming the reranker (06.9 failure gallery).
  • Tuning on test. If you pick the config on the full 16-query set, your "test" numbers are contaminated — keep the dev/test split sacred; 14 dev queries is tiny, so expect noisy optima and say so.
  • The toy corpus flatters you. Deterministic toy vectors make dense retrieval suspiciously good at paraphrases; real embeddings will be worse on some query types and better on others. Label toy-corpus conclusions "plumbing-verified" and re-measure before believing them.

Stretch (optional)

Stretch (optional): Multi-tenant retrieval service#

Goal: A small FastAPI retrieval service that could front a real product: API-key tenants, server-side ACL filtering, a cached query embedder, embedding-space version guards, a versioned re-embedding workflow, and a CI quality gate — every piece taken from a lesson, composed the way production would.

What you'll practise:

  • The Embedder/VectorStore/Retriever seams under a real HTTP surface (06.1, Part 10, 06.5, Part 7, 06.10, 4.1)
  • The ACL filtering pattern: permissions resolved server-side, never from the client, never from the LLM (06.6, 3.2, 3.6)
  • Safe filter construction end-to-end: user filters → FilterSpec → allow-list → store translation (06.6, 2.3)
  • The CachingEmbedder for query-embedding cache hits and its privacy notes (06.2, 5.3, 5.5)
  • Embedding-space versioning: embedding_space()/assert_compatible() at startup, and re-embedding as a versioned artefact (06.1, Part 9, 06.2, 10.2)
  • Quality gates in CI: validate_embeddings on fixtures, the contract test, and a sanity-query test (06.2, 11.2–11.1, 06.10, 4.3)

Setup: the starter project's files (embedder.py, chunks.jsonl, vectors.jsonl, load_store.py, filter_spec.py) plus:

bash
uv add fastapi uvicorn httpx pytest

Steps:

  1. Extend the corpus metadata. In export_chunks.py, add an acl list to each chunk's metadata (the field name 06.6's ALLOWED map and acl_predicate already use): contracts → ["legal", "initech-admins"], everything else → ["all-staff"] (the 05.8 ACL model in miniature — chunk-level groups, document-level inheritance). Re-export chunks.jsonl and re-run embed_corpus.py/load_store.py so the store carries the new payload.

  2. Copy the ACL pattern. Copy acl.py from 06.6, 3.2: user_groups_from_session(session) and acl_predicate(groups) producing the store-side predicate. In production the groups come from your IdP/JWT; here they come from a API_KEYS dict you define: {"test-acme-key": {"tenant": "acme", "groups": ["all-staff"]}, "test-initech-key": {"tenant": "initech", "groups": ["all-staff"]}, "test-initech-legal": {"tenant": "initech", "groups": ["all-staff", "legal"]}, "test-globex-key": {"tenant": "globex", "groups": ["all-staff"]}} (the contract chunks belong to the initech tenant in the running corpus, so the legal key has to be an initech key).

  3. Write app.py. POST /search with Authorization: Bearer <key>: resolve the key to a session (401 on unknown), embed the query through a CachingEmbedder wrapping LocalSTEmbedder (06.2, 5.3; its embed_fn(texts, spec) hook is where you plug in lambda texts, spec: [local.embed_query(t) for t in texts], with an EmbedSpec that carries task_type="query"); read the model name from an environment variable LOCAL_ST_MODEL (default sentence-transformers/all-MiniLM-L6-v2) so step 8 can break it on purpose, build one FilterSpec = user filters AND tenant == session.tenant AND the ACL predicate ANDed on acl, validate with validated(), translate per store (the lesson's NumpyVectorStore._matches compares scalars, so add one more branch for array-valued fields, elif op == "$overlap": ok = got is not None and any(g in got for g in v), placed before the final else: raise, and make the translator emit it for acl), call store.query, return hits with id, score, section, text, source. The tenant and ACL predicates are added server-side — a client can narrow, never widen.

  4. Guard the embedding space at startup. On boot, load the embedding_space metadata from vectors.jsonl and call assert_compatible(stored_meta, current_meta) from 06.1, 9.1–9.2 — a mismatched model/dims/task must refuse to serve, not silently rank garbage. Expose the space on GET /health.

  5. Versioned re-embedding. Write reembed.py --model <name> --out vectors_v2.jsonl that re-runs embed_corpus.py's path with a different embedder and stamps the new space metadata. load_store.py --vectors vectors_v2.jsonl loads it; app.py --vectors selects which file serves. Document (in a comment) that a real deployment keeps old and new indices side by side and flips an alias — the blue/green pattern from 06.2, 10.2 and 05.9.

  6. The CI gate. Write test_service.py using FastAPI's TestClient against the NumpyVectorStore (no server, no model download — use FakeEmbedder for speed on most tests, one marked test with the real MiniLM):

    • contract test: upsert/query/get/delete round-trip (06.5, 7.4);
    • leak tests: the acme key searching "net-30 payment terms" gets no initech chunks; the all-staff initech key gets no contract-* chunks (they need legal) while the initech legal key gets them; the globex key sees only ticket-*;
    • injection test: a filter value containing store syntax (tenant": "acme" OR "1"="1) is rejected by FilterSpec validation, not interpolated;
    • space test: assert_compatible rejects a vectors file stamped with a different model_id;
    • sanity query: "vacation" returns handbook-001 in the top 3 (06.2, 11.1).
  7. Run it. uvicorn app:app --port 8000 then:

    bash
    curl -s localhost:8000/search -H 'authorization: Bearer test-initech-legal' \
         -H 'content-type: application/json' \
         -d '{"query":"net-30 payment terms","k":3}'
    curl -s localhost:8000/search -H 'authorization: Bearer test-initech-key' \
         -H 'content-type: application/json' \
         -d '{"query":"net-30 payment terms","k":3}'

    The legal key sees contract-9; the staff key sees nothing (contracts need legal). Repeat with the globex key on a billing question — it sees its own tickets only.

  8. Failure path. Point LOCAL_ST_MODEL at a nonsense name and restart: startup must fail loudly at model load or the space guard must catch a stale vectors.jsonl — pick one and document which. Then simulate the embedder being down at query time and implement the 06.2, 8.1 fallback: return a keyword-ranked result set (a trivial in-operator scorer is fine until 06.7's BM25 drops in) with source: "keyword-fallback" so callers can tell.

Verify it, and what you should see:

bash
uv run pytest -q test_service.py                     # all pass, including the three leak tests
uvicorn app:app --port 8000 &
curl -s localhost:8000/health                        # embedding space: model, dims, task
# the two curls above: legal key -> contract-9 hit; staff key -> []

Expected behaviour (illustrative ranking, deterministic isolation):

json
// test-initech-legal, "net-30 payment terms"
{"results": [{"id": "contract-9", "score": 0.71, "section": "MSA > 2025 Terms", "source": "dense"}, ...]}
// test-initech-key, same query
{"results": []}

The security properties are the acceptance criteria, not the ranking: no key ever sees another tenant's chunks, no client-supplied filter can widen access, a mismatched embedding space refuses to boot, and every hit carries provenance. Cache hits are visible in the CachingEmbedder stats — repeat the same query and the second call embeds nothing.

Done when:

  • pytest -q passes with zero keys and zero services, including all three cross-tenant/ACL leak tests.
  • Two different API keys demonstrably see disjoint result sets on the same query.
  • Startup refuses a vectors.jsonl whose space metadata doesn't match the configured embedder.
  • A repeated query is served from the embedding cache (stats show hits), and you can explain the cache key's six components.
  • reembed.py produces a second vectors file that load_store.py accepts and app.py can serve via --vectors, with the old file still loadable.
  • Your README-in-comments states which pieces are toy (key map, in-memory store) and which are production-shaped (ACL pattern, space guard, cache, CI gate).

Stretch ideas:

  • Swap NumpyVectorStore for ChromaVectorStore/QdrantVectorStore local mode — only the adapter and the filter translator change; rerun the leak tests to prove the seam held.
  • Add rate limiting per API key and a per-key daily query budget (06.2, 8 owns the latency side).
  • Add GET /search/explain returning which filter components were applied and the pre-filter candidate count — the post-filter starvation diagnostic from 06.6, 1.2.
  • Needs accounts: point the store at managed Qdrant/Chroma Cloud or pgvector and re-run the contract + leak suite against it; the whole point of the protocol is that this is a config change.

Common problems:

  • ACL applied after retrieval. If you filter results instead of the query, a tenant with few matching chunks gets short/empty pages unpredictably — the predicate must be inside store.query(filters=...) (06.6, 1.2).
  • Groups from the client. Never let the request body carry groups/tenant — resolve them from the key server-side; a client-supplied group list is a privilege-escalation bug wearing a JSON costume.
  • acl semantics. Decide and document: overlap (ANY) vs superset (CONTAINS ALL). The lesson's acl_predicate uses overlap — a user in legal sees legal docs and all-staff docs because the predicate matches any shared group; verify your test expectations match that rule.
  • Cache key missing a component. If you cache on text hash alone, a model or task-type change silently serves stale vectors — the six-component key from 06.2, 5.2 exists precisely to prevent this.
  • Space guard bypassed in tests. If tests construct the store directly they skip the startup guard — keep one integration test that boots app.py's startup path against a tampered vectors.jsonl.
Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close