Module 06: Projects
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:
uv init vector-search --bare --python 3.13 && cd vector-searchThen 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: 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
Embedderprotocol and swapping backends without touching search code (lesson 06.1, Part 10) - Running an open-weight model locally with
sentence-transformers, includingmax_seq_lengthand 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
VectorStorecontract, the exactNumpyVectorStore, and Chroma/Qdrant local mode as drop-in alternatives (06.5, Part 7) - Building filters safely from user input with
FilterSpecand translating them per store (06.6, 2.3, 1.3) - The metric conventions that make "similar" mean something (06.3, 2.2)
Setup:
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:
- Create the project and the corpus. Run the
uv initabove, then copycorpus.pyfrom 06.10, Part 4 verbatim — it buildsCHUNKS(fourteenChunkrecords withid,doc_id,section,text,metadata) deterministically. Writeexport_chunks.pythat emits one JSON object per chunk tochunks.jsonlwith fieldsid,doc_id,section,text,metadata— dropvector,topicanddomain(the toy-vector scaffolding the projects replace). Module 05 alternative: if you havedata/chunks/chunks.jsonlfrom 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. - Copy the embedder seam. Copy
embedder_protocol.pyand theLocalSTEmbedderandFakeEmbedderclasses from 06.1, Part 10 intoembedder.py. InstantiateLocalSTEmbedder("sentence-transformers/all-MiniLM-L6-v2")— itsencode_document/encode_querypath is the lesson's adapter; MiniLM needs no task prefixes (06.1, 3.1). KeepFakeEmbedder(dims=64)for tests. - Embed the corpus. Write
embed_corpus.py: loadchunks.jsonl, callembedder.embed_documents([c["text"] for c in chunks])(batch throughpack_batchesfrom 06.2, 2.3 if the corpus ever outgrows one call), runvalidate_embeddings(vectors, expected_dim=embedder.dimensions)from 06.2, 11.2 on the result, and writevectors.jsonl— one line per chunk carryingid,vector, and the embedding-space metadata from 06.1, 9.1:model_id,dimensions,task_type(document),preprocessingversion andcreated_at. Re-running must produce identical vectors (the local model is deterministic on CPU — if yours differs, checktorchthreading settings before blaming the pipeline). - Load the store. Copy
vector_store.pyandnumpy_store.pyfrom 06.5, Parts 7.1–7.2. Writeload_store.pythat readsvectors.jsonl+chunks.jsonl, buildsVectorRecord(id=..., vector=..., text=..., metadata=...)per chunk (copysectionanddoc_idintometadataas well, sosearch.pycan print the section and a hit can be traced to its document) and callsstore.upsert(records)on aNumpyVectorStore(dim=embedder.dimensions). Print the record count and a samplestore.get(id). - Prove the store seam. Run the same
load_store.pyagainstChromaVectorStore(chromadb.PersistentClient(path="./chroma_db"), 06.5, 6.1) andQdrantVectorStorein local mode (QdrantClient(path="./qdrant_db"), 06.5, 5.2) by adding a--storeflag — 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. - Filters that are safe. Copy
filter_spec.pyfrom 06.6, 2.3 — it gives youPredicate,FilterSpec,Op, theALLOWEDfield allow-list andvalidated(). The lesson'sALLOWEDnamestenant_id,doc_typeandlanguage, but this corpus's metadata fields aretenant,kindandlang, so rename those three keys (keep their operators) before you use it; otherwise--filter tenant=acmeis rejected as "not filterable". That rejection is the allow-list working, not a bug. Writespec_to_store(spec)translating validated predicates into each store's filter shape:to_chroma()andto_qdrant()already exist in the lesson; forNumpyVectorStorewrite ~15 lines mapping predicates to its{"field": {"$in": [...]}}/{"field": value}dict form (its_matchessupports equality, ranges and$in). - 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 withembedder.embed_query, parses--filterargs intoPredicates (never raw store syntax — that's the whole lesson of 06.6, 2.3), validates theFilterSpec, callsstore.query(query_vec, top_k=k, filters=...), and printsrank id score section text-snippetper hit. Sort ties deterministically. - Test without a model. Write
test_search.pywithFakeEmbedder: upsert the corpus, assertsearch("vacation")returnshandbook-001/handbook-002in the top results (the fake hashes words into shared dimensions, so same-topic chunks cluster), assert atenant=acmefilter excludesticket-77/contract-9, and assert an impossible filter returns[]not an error. - The endpoint (optional but recommended). Add
serve.py:POST /searchtaking{"query": str, "k": int, "filters": {...}}, building theFilterSpecserver-side, calling the samestore.query, returning[{id, score, section, text}]. Capkand query length; never interpolate filter values into store syntax (06.6, 2.3 owns why).uvicorn serve:app --reloadandcurlit. - Swap in a hosted embedder (extension, needs a key). Add
OpenAIEmbedder/GeminiEmbedderfrom 06.1, Part 10, re-runembed_corpus.pyintovectors_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:
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=initechWhat to check, concretely:
vectors.jsonlhas 384-dim vectors (MiniLM-L6) withmodel_id,dimensions,task_typeon every line; a secondembed_corpus.pyrun 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 likeVPN-ERR-2041may rank worse than keyword search would; that's expected and is what 06.7 and the stretch project fix. --filter tenant=acmeon the payment-terms query returns onlyacmechunks, with low scores because nothing in that tenant is about payment terms —contract-9belongs toinitechand must not appear;--filter tenant=initechreturns it first. This is the cross-tenant leak check from 06.6 in miniature.store.queryonNumpyVectorStoreis 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):
# 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.jsonland a loaded store exist; re-running the embed step is deterministic.search.pyanswers the probe queries above correctly: the vacation query finds the leave chunks,tenant=initechreturns the contract chunks, andtenant=acmenever returns acontract-*chunk.- The same
VectorRecords load into at least two stores (numpypluschromaorqdrant) with identical query results, and the contract test passes on each. - Every stored vector carries its embedding-space metadata, and
test_search.pypasses withFakeEmbedderand no model download. - You can explain in two sentences why applying the
tenantfilter 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
CachingEmbedderfrom 06.2, 5.3 in front ofLocalSTEmbedderand show the secondembed_corpus.pyrun is all cache hits — then change one chunk's text and show only it re-embeds. - Swap
NumpyVectorStorefor pgvector: thedocker run pgvector/pgvector:pg17reference and fullpgvector_store.pyare in 06.5, Parts 4 and 7.3; add the HNSW index and anEXPLAINcheck 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, orgoogle/embeddinggemma-300m, which needs you to accept Google's Gemma terms on Hugging Face). Use each model's documented query/document prompts throughLocalSTEmbedder(prompts=...), record dimensions andmax_seq_length, and stamp eachvectors_<model>.jsonlwith 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
--diversifyflag so near-duplicate leave chunks don't fill the top-k. - Needs a key: wire
OpenAIEmbedderorVoyageEmbedder-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-transformersfetches weights from Hugging Face on firstSentenceTransformer(...)call — check your network/proxy, or setHF_HOMEto a writable cache dir. TheFakeEmbedderpath intest_search.pyneeds no download at all. normalize_embeddingsin the wrong place. It's anencode()-family argument, not a constructor argument — the lesson'sLocalSTEmbedderalready passes it through; don't "fix" it by setting an attribute (06.1, 4.1).- Dimension mismatch on
upsert.NumpyVectorStore(dim=...)must equalembedder.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_storemapping:NumpyVectorStore._matchestreats a bare value as equality and a dict as operators — aPredicate(op="in", value=[...])must become{"$in": [...]}, not a nested dict the store can't read. And remember Chroma has no$not— the lesson'sto_chromaalready 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-2041ranks poorly; that's the lexical-gap lesson of 06.7, and the stretch project measures it properly.
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
Retrieverprotocol as the single seam every configuration satisfies (lesson 06.10, 4.1) - The labelled eval set: qrels, dev/test splits, query types, the
filtered-emptyleak check and the no-answer query (06.10, 4.2) - Every retrieval metric and the harness:
run_eval,aggregate_by,compare_runswith 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, finalk, and theRerankerprotocol withIdentityReranker/KeywordRerankerfakes (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:
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-dotenvSteps:
- Copy the eval spine verbatim. From 06.10 copy
corpus.py,metrics.py,retrievers.py,eval_queries.jsonl,harness.py,spans.py,query_techniques.pyanddemo.pyinto the project. Runuv run python demo.pyand 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. - Understand the baseline. Open
eval_queries.jsonland note the contract:relevantmaps chunk IDs to grades (2 = answers, 1 = useful),neededmarks multi-chunk answers,filtersexercises the tenant check,splitis dev vs test. Runharness.py's failure browser on the weakest retriever and read five misses before changing anything (06.10, 5.2). - Add the fusion library. Copy
fusion.pyfrom 06.8, Part 2 — it hasrrf,borda,score_fusion,dbsfandinterleaveoverRankedLists. Writefusion_retrievers.pywith aFusionRetrieverclass implementing 06.10'sRetrieverprotocol: it holds a dict of first-stage retrievers ({"dense": ..., "bm25": ...}), calls eachsearch(), convertsHits toRankedLists, fuses with a chosen function, and maps fused IDs back toHits (keep the max first-stage score and setsource="fusion:<method>"). Register configs:rrf,score_fusion_minmax(α=0.5),borda,interleave. - Measure the fusion variants. Run
run_eval+aggregateon each config over the dev split; print a table ofrecall@10,mrr,ndcg@10per 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). - Add the rerank stage. Copy
reranker.pyandadapters_rerank.pyfrom 06.9, Part 9 —IdentityReranker(baseline/fallback) andKeywordReranker(deterministic fake). WriteRerankedRetriever(Retriever):search()calls the fused retriever forrerank_depthcandidates, callsreranker.rerank(query, hits), trims tok. Mind the seam: 06.9'sHithas nosourcefield — map it through (addsourceto metadata or reconstruct it) rather than letting provenance die at the boundary. - 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). - Compare with statistics. Use
save_run/compare_runsfromharness.py: save the best dev config and the dense-only baseline, thencompare_runsthem — 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. - Confirm on test, then analyse. Take the single best dev config, evaluate it on the
testsplit only, and record the delta vs dev — that gap is your overfitting signal (06.10, 6.4). Runfailures()on it, classify each miss with the 5.1 taxonomy, and writeFAILURE_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). - Query techniques, measured. Wire
query_techniques.py'smulti_query_retrieveandhyde_retrievebehind the sameRetrieverprotocol (they already return fusedHits) and evaluatemulti-queryandhydeas configs on theambiguous/multilingual/multi-hoptypes only — the lesson's evidence is mixed, so let your numbers decide (06.10, 7.8). - 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:
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.mdInvariants 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 returnscontract-9, or any other chunk outside theacmetenant, under itstenant=acmefilter on every config: the harness'sleakedflag staysFalse. 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 ano-answerquery: 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.mdclassifies 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).
q16provably never leaks (leakedisFalseon every config) andq04/q15show the expected lexical/dense split.
Stretch ideas:
- Real embeddings, still keyless: write
RealDenseRetrieverimplementing the protocol — embed each chunk'stextonce withLocalSTEmbedder(reuse the starter project'svectors.jsonl), embed queries withembed_query, cosine-rank. Re-run the whole benchmark; the ranking of configs may flip — that's the finding. - A real reranker: swap
KeywordRerankerforLocalCrossEncoderReranker(cross-encoder/ms-marco-MiniLM-L6-v2, ~22M params, CPU-friendly — 06.9, 2.3–2.4) and re-sweeprerank_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+textfields, 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
Hitslightly differently (sourcefield, field order). Normalise to 06.10'sHitinside 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=10guarantees 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): 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/Retrieverseams 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
CachingEmbedderfor 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_embeddingson 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:
uv add fastapi uvicorn httpx pytestSteps:
-
Extend the corpus metadata. In
export_chunks.py, add anacllist to each chunk'smetadata(the field name 06.6'sALLOWEDmap andacl_predicatealready use): contracts →["legal", "initech-admins"], everything else →["all-staff"](the 05.8 ACL model in miniature — chunk-level groups, document-level inheritance). Re-exportchunks.jsonland re-runembed_corpus.py/load_store.pyso the store carries the new payload. -
Copy the ACL pattern. Copy
acl.pyfrom 06.6, 3.2:user_groups_from_session(session)andacl_predicate(groups)producing the store-side predicate. In production the groups come from your IdP/JWT; here they come from aAPI_KEYSdict 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 theinitechtenant in the running corpus, so the legal key has to be aninitechkey). -
Write
app.py.POST /searchwithAuthorization: Bearer <key>: resolve the key to a session (401 on unknown), embed the query through aCachingEmbedderwrappingLocalSTEmbedder(06.2, 5.3; itsembed_fn(texts, spec)hook is where you plug inlambda texts, spec: [local.embed_query(t) for t in texts], with anEmbedSpecthat carriestask_type="query"); read the model name from an environment variableLOCAL_ST_MODEL(defaultsentence-transformers/all-MiniLM-L6-v2) so step 8 can break it on purpose, build oneFilterSpec= user filters ANDtenant == session.tenantAND the ACL predicate ANDed onacl, validate withvalidated(), translate per store (the lesson'sNumpyVectorStore._matchescompares 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 finalelse: raise, and make the translator emit it foracl), callstore.query, return hits withid,score,section,text,source. The tenant and ACL predicates are added server-side — a client can narrow, never widen. -
Guard the embedding space at startup. On boot, load the
embedding_spacemetadata fromvectors.jsonland callassert_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 onGET /health. -
Versioned re-embedding. Write
reembed.py --model <name> --out vectors_v2.jsonlthat re-runsembed_corpus.py's path with a different embedder and stamps the new space metadata.load_store.py --vectors vectors_v2.jsonlloads it;app.py --vectorsselects 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. -
The CI gate. Write
test_service.pyusing FastAPI'sTestClientagainst theNumpyVectorStore(no server, no model download — useFakeEmbedderfor 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
acmekey searching "net-30 payment terms" gets noinitechchunks; theall-staffinitech key gets nocontract-*chunks (they needlegal) while the initech legal key gets them; the globex key sees onlyticket-*; - injection test: a filter value containing store syntax (
tenant": "acme" OR "1"="1) is rejected byFilterSpecvalidation, not interpolated; - space test:
assert_compatiblerejects a vectors file stamped with a differentmodel_id; - sanity query: "vacation" returns
handbook-001in the top 3 (06.2, 11.1).
-
Run it.
uvicorn app:app --port 8000then: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 needlegal). Repeat with the globex key on a billing question — it sees its own tickets only. -
Failure path. Point
LOCAL_ST_MODELat a nonsense name and restart: startup must fail loudly at model load or the space guard must catch a stalevectors.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 trivialin-operator scorer is fine until 06.7's BM25 drops in) withsource: "keyword-fallback"so callers can tell.
Verify it, and what you should see:
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):
// 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 -qpasses 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.jsonlwhose 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.pyproduces a second vectors file thatload_store.pyaccepts andapp.pycan 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
NumpyVectorStoreforChromaVectorStore/QdrantVectorStorelocal 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/explainreturning 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. aclsemantics. Decide and document: overlap (ANY) vs superset (CONTAINS ALL). The lesson'sacl_predicateuses overlap — a user inlegalsees legal docs andall-staffdocs 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 tamperedvectors.jsonl.