See it run
Lesson 2.2 keeps words and vectors side by side, filters before it ranks, and fuses the two rankings. Then it measures on an 834-document drive full of old versions and look-alike passages. The right passage lands in the top five for 34% of the questions with naive top-k, 54% with hybrid and 60% with a stand-in rerank. For the questions that have an outdated or look-alike passage to find, the baseline puts one in the top five 28% of the time. Hybrid: 11%.
6 min 48 s · captions in the video, transcript below the lesson · narrated by an AI version of Charafeddine's voice, from his script.
The numbers on screen are an offline run: hashed-word embeddings and a word-overlap stand-in for the reranker, so the terminal calls them a floor. With real embeddings, the lesson’s live run reaches 53% for the baseline and 68% for hybrid.
Lesson 2.2 of 20 in Context Architecture · €197, lifetime access · Enroll
Score your own retrieval
The same two numbers on your system: how often the right passage is in the top five, and how often an outdated or look-alike one is. You export your retriever's ranked results; one file, standard library only.
python3 stale_at_k.py --example # writes naive.jsonl and hybrid.jsonl, to see the format
python3 stale_at_k.py naive.jsonl hybrid.jsonl # one file per method, side by side
With LlamaIndex, one way to write a file from your own questions (each with its relevant and outdated ids):
import json
with open("hybrid.jsonl", "w") as f:
for q in questions: # [{"question": ..., "relevant": [...], "outdated": [...]}, ...]
nodes = retriever.retrieve(q["question"])
f.write(json.dumps({**q, "retrieved": [n.node.node_id for n in nodes]}) + "\n")
Download stale_at_k.py or copy it below.
The script (102 lines)
"""Score your own retrieval the way lesson 2.2 does: how often the right passage is in the top k, and how often an
outdated or look-alike passage is.
python3 stale_at_k.py --example # writes naive.jsonl and hybrid.jsonl, to see the format
python3 stale_at_k.py naive.jsonl hybrid.jsonl # one file per retrieval method, compared side by side
Each line of a file is one question your retriever answered:
{"question": "...", "relevant": ["doc-12#3"], "outdated": ["doc-07#3"], "retrieved": ["doc-07#3", "doc-12#3", ...]}
relevant: the passages that answer it. outdated: old versions or look-alikes that must not be used (may be empty).
retrieved: your retriever's ranked ids for that question. Use the same questions in every file.
recall@k: share of questions with a relevant passage in the top k. MRR: mean of 1 / rank of the first relevant
passage, over the full ranked list. stale@k (neg@k in the lesson): among the questions that have an outdated
passage to find, the share with one in the top k.
Standard library only. Python 3.9 or later.
"""
# From lesson 2.2 of Cohorte's Context Architecture (cohorte.co/context-architecture).
import argparse
import json
import sys
import textwrap
from pathlib import Path
EXAMPLE = [ # three questions; the two files differ only in how each method ranked them
("What is the return window for opened items?", ["policy-2026#returns"], ["policy-2024#returns"],
["policy-2024#returns", "faq#returns", "policy-2026#returns"], ["policy-2026#returns", "faq#returns"]),
("Who approves net-60 payment terms?", ["finance-handbook#terms"], [],
["contract-northgate#7", "finance-handbook#terms"], ["finance-handbook#terms", "contract-northgate#7"]),
("What is the liability cap in the Northgate contract?", ["contract-northgate#12"], ["contract-northline#12"],
["contract-northline#12", "contract-northgate#12"], ["contract-northgate#12", "faq#contracts"]),
]
def load(path):
rows = []
with open(path, encoding="utf-8") as f:
for i, line in enumerate(f, 1):
if not line.strip():
continue
try:
r = json.loads(line)
rows.append((r["question"], set(r["relevant"]), set(r.get("outdated") or []), list(r["retrieved"])))
except (json.JSONDecodeError, KeyError, TypeError) as e:
sys.exit(f"{path}, line {i}: needs question, relevant and retrieved ({type(e).__name__}: {e}).")
if not rows:
sys.exit(f"No questions in {path}.")
return rows
def score(rows, k):
hit1 = hitk = rr = stale = with_outdated = 0
for _, relevant, outdated, retrieved in rows:
ranks = [i for i, d in enumerate(retrieved, 1) if d in relevant]
hit1 += bool(ranks) and ranks[0] == 1
hitk += bool(ranks) and ranks[0] <= k
rr += 1 / ranks[0] if ranks else 0
if outdated:
with_outdated += 1
stale += any(d in outdated for d in retrieved[:k])
n = len(rows)
return {"n": n, "r1": hit1 / n, "rk": hitk / n, "mrr": rr / n, "with_outdated": with_outdated,
"stale": stale / with_outdated if with_outdated else None}
def write_example():
names = ("naive.jsonl", "hybrid.jsonl")
if any(Path(n).exists() for n in names):
sys.exit("naive.jsonl or hybrid.jsonl already exists here; run --example in an empty folder.")
for col, name in ((3, names[0]), (4, names[1])):
Path(name).write_text("".join(json.dumps({"question": q[0], "relevant": q[1], "outdated": q[2],
"retrieved": q[col]}) + "\n" for q in EXAMPLE))
print("wrote naive.jsonl and hybrid.jsonl")
def main():
ap = argparse.ArgumentParser(description="recall@k, MRR and stale@k for your retrieval results.")
ap.add_argument("files", nargs="*", help="one JSONL file per retrieval method")
ap.add_argument("-k", type=int, default=5, help="cut-off (default 5)")
ap.add_argument("--example", action="store_true", help="write naive.jsonl and hybrid.jsonl, then stop")
a = ap.parse_args()
if a.k < 1:
ap.error("-k must be 1 or more")
if a.example:
return write_example()
if not a.files:
ap.error("give one JSONL file per method, or --example")
runs = [(Path(f).stem, load(f)) for f in a.files]
if len({frozenset(q for q, *_ in rows) for _, rows in runs}) > 1:
print("Warning: the files don't hold the same questions; compare like with like.")
w = max(8, max(len(name) for name, _ in runs) + 2)
cols = [("recall@1", "r1")] + ([(f"recall@{a.k}", "rk")] if a.k > 1 else [])
print(f"{'method':<{w}}{'n':>5}" + "".join(f"{c:>10}" for c, _ in cols) + f"{'MRR':>7}{f'stale@{a.k}':>10}")
for name, rows in runs:
s = score(rows, a.k)
stale = f"{s['stale']:.0%} of {s['with_outdated']}" if s["stale"] is not None else "n/a"
print(f"{name:<{w}}{s['n']:>5}" + "".join(f"{s[key]:>10.0%}" for _, key in cols) + f"{s['mrr']:>7.2f}{stale:>10}")
print(textwrap.fill(f"stale@{a.k} counts only the questions that have an outdated or look-alike passage "
f"to find: the number after 'of'.", 72))
if __name__ == "__main__":
main()
What it prints on its own example: three questions, two ways of ranking them.
$ python3 stale_at_k.py --example
wrote naive.jsonl and hybrid.jsonl
$ python3 stale_at_k.py naive.jsonl hybrid.jsonl
method n recall@1 recall@5 MRR stale@5
naive 3 0% 100% 0.44 100% of 2
hybrid 3 100% 100% 1.00 0% of 2
stale@5 counts only the questions that have an outdated or look-alike
passage to find: the number after 'of'.
On your files, compare methods on the same questions. A high stale@5 means your model reads old versions in its context, whatever recall says.
Where retrieval goes next
Retrieval is one wall of the context layer. The course builds the others: documents parsed once with their tables, contextual retrieval, an agent that chooses between grep and search, results filtered by who is asking, connectors, citations a reader can check, and memory that records where it came from. Here is the whole course, in order.
Context Architecture · the whole course
20 lessons in six modules, plus a Start Here section: 5 films with Charafeddine (lesson 0.2 opens the course), 12 screencasts, 3 labs and a capstone.
Module 1 · Context engineering
- 1.1The quality of the answer is bounded by the contextfilm · 6 min
- 1.2The context auditscreencast · 5 min
- 1.3Long context or retrieval: the cost and the evidenceThe film at the top of this pagefilm · 7 min
Module 2 · Retrieval that holds
- 2.1Parsing documents once: Docling, tables, native PDF pagesscreencast · 6 min
- 2.2Hybrid search in PostgresThis lessonscreencast · 7 min
- 2.3Contextual retrievalscreencast · 5 min
- 2.4Lab: beat the naive baseline, measuredlab
Module 3 · Agentic search
- 3.1Search as tools: when grep beats embeddings, and when it doesn'tfilm · 5 min
- 3.2A read-only text mirrorscreencast · 6 min
- 3.3Lab: the agent chooses its toolslab
Module 4 · Permission-aware knowledge
- 4.1The classic leaks: filter the results before the prompt, never the answer afterfilm · 7 min
- 4.2OpenFGA: the model, the tuples and the wallsscreencast · 6 min
- 4.3Row-level security as wall 3screencast · 5 min
- 4.4Lab: same question, different people, different answerslab
Module 5 · Connectors, freshness, memory
- 5.1MCP connectorsscreencast · 5 min
- 5.2Freshness and provenance: citations a reader can checkscreencast · 5 min
- 5.3Memory with provenance and quarantinescreencast · 5 min
- 5.4A research note: Context Kubernetes and what its evaluation teachesreading
Module 6 · Evaluation and capstone
- 6.1Retrieval metrics on both corporascreencast · 6 min
- 6.2Capstone: the Larkfield knowledge layerscreencast · 4 min
One-time, lifetime access, with 3 months in the Engine Room. Or the six courses for €797.
Read the full lesson 2.2
Course 5 of 6 in the Engineering Series, which builds one AI platform in Python for Larkfield Supply, a fictional company. In the lesson, E1 to E6 are the six courses; you can skip mentions of other lessons on a first read. Reading needs no setup. To run the code, you need the course repository (tag e5-m2-l2) and the retrieval primer and lesson 2.1.
You'll leave with one Postgres table of chunks with a full-text index and a vector index, one SQL query that fuses both with every filter applied before any limit, and the price row the naive pipeline missed, found at rank 1.
In one screen
- Use it on Monday: Measure naive top-k against hybrid on your own questions before you add a reranker, and put every permission and status filter before the limit, in the same query.
- The picture: One Postgres table holds each chunk, its access list, a full-text index and a vector index; one query filters the candidates first, ranks them both ways, then fuses the two lists by rank.
- The decision: Postgres full-text plus pgvector, fused in one query, every filter before any limit. A BM25 extension or Qdrant only when your measurements say Postgres is where you lose.
- You'll run: The Step 5 snippet, which asks both pipelines "What is the list price of LK-3150?". Naive reaches the price list at rank 4 without the row; hybrid puts
*pdf-price-listfirst.
Why this matters
Ask Larkfield's naive pipeline (400-character windows, nearest vectors, top k) "What is the list price of LK-3150?". It misses. The answer is one table row, and the window that holds it is mostly other rows and other numbers. On 38 labeled questions over 15 documents, the naive pipeline finds nothing in its top 10 for 11 of them.
On a drive closer to a real one, 834 documents with old versions and 49 near-identical customer agreements, it's worse: the right passage is in the top 5 for a third of the questions offline (about half live), and for 28% of them offline (55% live) an outdated or sibling passage sits there instead.
This part builds the search that fixes most of that, in one Postgres query, and ends by asking it the LK-3150 question again. The vocabulary (embedding, BM25 (Best Matching 25), hybrid, reranker, the three numbers) is in the retrieval primer, so if a word below is new, that's the page to open.
The idea
Two indexes find different things. A lexical index matches words: it nails LK-3150, a clause number, a name. A dense index matches meaning: it can connect "money back for a broken pallet" to "credit note for damaged goods". Run both and fuse them.
Reciprocal rank fusion (RRF). For each chunk, add 1 / (60 + rank) from each list. Ranks only, so you never calibrate a full-text score against a cosine distance. The 60 is the constant from the original RRF paper, where it was "near-optimal, but the choice was not critical" (Cormack, Clarke and Büttcher, SIGIR 2009, the information-retrieval conference).
Postgres for all of it. One table holds the chunk text, its access list, and both indexes. Why one table? Permissions then apply to chunks like to any other row (module 4), and there's one system to back up. Step 1 names the two index types when you see them.
Every filter before any limit. A filter that runs after LIMIT 10 leaves you three rows, or a superseded document in a slot a current one needed.
The lexical side is Postgres full-text search, and that isn't BM25. BM25 weights a rare word above a common one, saturates repeated words and normalizes for length (the primer has it in full). Postgres's ts_rank_cd counts matching words and their proximity, and its ranking functions "do not use any global information" (PostgreSQL 17 docs).
I chose it anyway: no extension, the stock image, and most teams already run it. A BM25 extension is the upgrade if lexical ranking measures as your bottleneck.
Rerank is optional. A reranker reorders the top 30 with a second, slower model. Our live provider (OpenAI, as of November 2026) has no rerank endpoint, so it's a setting, off by default live. Part 2 covers it.
question ─┬─> plainto_tsquery, & → | ──> ts_rank_cd over tsv (GIN) top 30 ─┐
└─> embed (embed-default) ──> cosine over embedding (HNSW) top 30 ─┤
▼
RRF: Σ 1/(60 + rank) ──> top k ──> optional rerank (AIP_RERANK)
both branches read one candidate set: allowed documents, current status, index
Build it
Four steps: a table, a query, embeddings, and a baseline to beat. Then Step 5 asks the LK-3150 question of both pipelines. Everything here runs on your laptop with no model called, so start Postgres and apply the migration:
git checkout e5-m2-l2 && uv sync --all-extras
(cd infra/compose && docker compose up -d --wait --force-recreate postgres)
uv run alembic upgrade heads
Pinned at e5-m2-l2: Python 3.12, uv 0.11.21, Postgres 17 with pgvector 0.8.7 (image pgvector/pgvector:0.8.7-pg17), psycopg 3.3.8, Alembic 1.20.1.
No model is called anywhere in this part: OfflineModel stands in, with hashed words as "embeddings". If your stack predates E5, "Going deeper" has the one-line pgvector fix.
Step 1: the schema
What to notice: the chunk carries its own copy of the access list, and Postgres computes the full-text column itself, from three columns. So when lesson 2.3 adds a short generated context in front of each chunk, it gets indexed with no code change.
Two index types appear here. A GIN (generalized inverted index) index is Postgres's index for words, built on a tsvector column (the chunk's words, stemmed). An HNSW (hierarchical navigable small world) index is the graph pgvector, the Postgres extension for vectors, walks to find near neighbors of a vector(1024).
From src/aip/knowledge/migrations/0001_knowledge.py:
op.execute(f"""
CREATE TABLE knowledge.chunks (
chunk_id text PRIMARY KEY,
index_name text NOT NULL DEFAULT 'main', -- 'main' or 'baseline'
doc_id text NOT NULL REFERENCES knowledge.documents ON DELETE CASCADE,
ord int NOT NULL,
section text NOT NULL,
body text NOT NULL,
context text NOT NULL DEFAULT '',
acl text[] NOT NULL, -- copied from the document, so RLS needs no join
tsv tsvector GENERATED ALWAYS AS
(to_tsvector('english', context || ' ' || section || ' ' || body)) STORED,
embedding vector({DIM}) NOT NULL
)""")
op.execute("CREATE INDEX chunks_tsv ON knowledge.chunks USING gin (tsv)")
op.execute("CREATE INDEX chunks_hnsw ON knowledge.chunks USING hnsw (embedding vector_cosine_ops)")
op.execute("CREATE INDEX chunks_doc ON knowledge.chunks (doc_id)")
The documents table, the extension check and the grants are in "Full code", at the end of part 2.
Decisions worth naming:
tsvis a generated column: Postgres keeps it in step with the text. It indexescontext || section || body, so headings count, and lesson 2.3's context will too.vector({DIM})fixes the dimension (AIP_EMBED_DIM, default 1024). Another dimension is a new migration and a full re-embed.aclsits on every chunk, so lesson 4.3's row filter needs no join. Row-level security (RLS) is the Postgres feature that hides rows a role may not see; module 4 makes it the last of three permission checks.index_namekeeps the naive baseline in the same table.aip_app, the database login the application reads with, getsSELECTand nothing else. Alembic is the migration tool:alembic.iniadds the knowledge migrations to the list every package shares, souv run alembic upgrade headsapplies this one. The sync job never migrates.
(cd infra/compose && docker compose exec postgres psql -U aip -d aip -c '\d knowledge.chunks') | cut -c1-78
...
tsv | tsvector | | | generated always as (to_ts
embedding | vector(1024) | | not null |
Indexes:
"chunks_pkey" PRIMARY KEY, btree (chunk_id)
"chunks_doc" btree (doc_id)
"chunks_hnsw" hnsw (embedding vector_cosine_ops)
"chunks_tsv" gin (tsv)
...
Step 2: the hybrid query
This is the heart of the course's retrieval, so we'll read it in three pieces. Each named block of the WITH is a CTE (common table expression). What to notice overall: one block, candidates, applies every filter, and both rankings read only from it.
First, the question and the filters:
From src/aip/knowledge/pgstore.py:
HYBRID_SQL = """
WITH q AS (
SELECT replace(plainto_tsquery('english', %(query)s)::text, '&', '|')::tsquery AS tsq -- any word, not all
), candidates AS NOT MATERIALIZED ( -- every filter before any LIMIT (inlined: HNSW still applies)
SELECT c.* FROM knowledge.chunks c JOIN knowledge.documents d USING (doc_id)
WHERE c.index_name = %(index)s AND c.doc_id = ANY(%(allowed)s)
AND (%(current_only)s = false OR d.status = 'current')
plainto_tsquery joins the stemmed words with &, so every word must match, and a natural question almost never does. We swap & for |, so a chunk matching more words just ranks higher. candidates then applies every filter in one place (allowed documents, index, current status) before anything ranks or limits. NOT MATERIALIZED lets Postgres inline it, so the dense branch still uses HNSW.
Why every filter here? Ask for 10, let the ranking cut to 10, filter afterwards, and 7 superseded or forbidden chunks leave you with 3.
Then the two rankings, each over the candidates only:
From src/aip/knowledge/pgstore.py:
), lexical AS (
SELECT c.chunk_id, row_number() OVER (ORDER BY ts_rank_cd(c.tsv, q.tsq) DESC, c.chunk_id) AS r
FROM candidates c, q
WHERE c.tsv @@ q.tsq
ORDER BY r LIMIT %(n)s
), dense AS (
SELECT c.chunk_id, row_number() OVER (ORDER BY c.embedding <=> %(qvec)s::vector, c.chunk_id) AS r
FROM candidates c
ORDER BY c.embedding <=> %(qvec)s::vector LIMIT %(n)s
Each branch numbers its own top n with row_number(). @@ is "the words match", and <=> is pgvector's cosine distance between the chunk's vector and the question's (qvec, Step 3 makes it).
Last, the fusion:
From src/aip/knowledge/pgstore.py:
), fused AS (
SELECT chunk_id, coalesce(1.0 / (60 + l.r), 0) + coalesce(1.0 / (60 + d.r), 0) AS rrf
FROM lexical l FULL OUTER JOIN dense d USING (chunk_id)
)
SELECT c.chunk_id, c.doc_id, d.title, c.section, c.body, c.context, d.uri, d.updated::text,
d.fetched_at::text, d.status, f.rrf
FROM fused f
JOIN knowledge.chunks c USING (chunk_id)
JOIN knowledge.documents d ON d.doc_id = c.doc_id
ORDER BY f.rrf DESC, c.chunk_id
LIMIT %(n)s
"""
fused is RRF over a full outer join, so a chunk found by one branch only still scores. The final SELECT adds the text and metadata and cuts to n again.
Try it 1: two predictions, on paper.
- A chunk ranks 1st in
lexicaland doesn't appear indense. Another ranks 2nd in both. Which one doesfusedput first? Use the primer's formula, 1/(60 + rank) per list. - Move
d.status = 'current'out ofcandidatesand into the finalWHERE. A search asks for 3 passages, both branches return the same 3 chunks, and one of them is superseded. How many passages come back?
Write both answers down; they're in "Check yourself".
One more setting matters with filters. Each search turns on pgvector's iterative scans, which keep a filtered HNSW scan going until enough rows pass the filter. Without them, a filter that rejects most neighbors can return fewer rows than you asked for.
Step 3: embeddings through E1's client
The dense branch needs the question as a vector, qvec. It comes from the platform's gateway client, aip.llm.Client, the one class every model call goes through, with retries, a deadline and trace headers. Until now its private _post only sent chat requests to one path. This step gives _post the path and a response parser as arguments, so embeddings reuse all of that, and adds embed:
From src/aip/llm/client.py:
def embed(self, alias: str, texts: list[str], *, dimensions: int | None = None) -> list[list[float]]:
"""E5: embeddings by alias (`embed-default`), with the same retries and deadline as complete."""
body = {"model": alias, "input": texts, **({"dimensions": dimensions} if dimensions else {})}
data = self._post(body, path="/v1/embeddings", parse=lambda resp, **_: resp.json())
return [d["embedding"] for d in sorted(data["data"], key=lambda d: d["index"])]
GatewayModel, the knowledge layer's thin wrapper over this client, calls it with aliases only (embed-default, fast), never a model id. An alias is a gateway name that maps to a real model, so swapping the model is a gateway setting. It also sends dimensions with every call, so the provider returns the size the schema fixed. (rerank arrives the same way; part 2's Appendix A.)
Step 4: the same pipeline in memory, and the baseline
Every result needs something to beat. The baseline is what most RAG tutorials ship: fixed windows, dense only, no filter. It runs on MemoryIndex, the same pipeline as the SQL in plain Python, for aip-knowledge --memory, the tests and the labs. Its lexical side is textbook BM25, with the inverse document frequency Postgres lacks ("Going deeper" shows its search).
From src/aip/knowledge/baseline.py:
"""Naive top-k RAG: the baseline students must beat, and the low-latency path.
Fixed 400-character windows, dense similarity only, top 5, no rerank, no context,
no freshness filter. Every number reported for the real pipeline is measured against this.
"""
from aip.knowledge.retrieval import MemoryIndex, Passage
def naive_search(index: MemoryIndex, query: str, k: int = 5, allowed: set[str] | None = None) -> list[Passage]:
return index.search(query, k=k, allowed=allowed, mode="dense", current_only=False)
That's where most tutorials stop. Its Postgres twin is PgStore.dense_only; the eval in part 2 runs both.
Step 5: ask the LK-3150 question again
Back to the question this lesson opened on. The snippet builds both pipelines in memory (Step 4's MemoryIndex, so no database) over the 15 documents and prints the top 5 documents of each. A * marks a passage that holds the LK-3150 row. Before you run it, guess: does naive get the row anywhere in its top 5, and where does hybrid put it?
uv run python - <<'EOF'
from aip.config import get_settings
from aip.knowledge.baseline import naive_search
from aip.knowledge.ingest import pull_local
from aip.knowledge.model import OfflineModel
from aip.knowledge.pipeline import build_baseline_index, build_memory_index
s = get_settings()
snap, model, cache = pull_local(s.knowledge_dir), OfflineModel(), s.knowledge_dir / "_parsed"
q = "What is the list price of LK-3150?"
naive = naive_search(build_baseline_index(snap, model, cache), q)
hybrid = build_memory_index(snap, model, cache).search(q, k=5)
for name, hits in [("naive", naive), ("hybrid", hybrid)]:
print(f"{name:6}", ", ".join(("*" if "LK-3150" in p.text else "") + p.doc_id for p in hits))
EOF
naive fin-margin-q3, hr-handbook, fin-pricing-authority, pdf-price-list, pol-shipping
hybrid *pdf-price-list, con-brightwater, fin-margin-q3, hr-handbook, pol-refunds
Run offline at e5-m2-l2 on 16 November 2026.
Naive does reach the price list, at rank 4, but in a 400-character window that doesn't hold the row. Hybrid puts the row itself first: the lexical side matches LK-3150 exactly, and lesson 2.1's chunks keep the row whole.
You now have the search every later lesson stands on: two indexes, one query, every filter before any limit, and it finds the row the naive pipeline missed. One question with hashed-word embeddings proves the pipeline, not the model. Part 2 measures it on all 38 questions, then on 834 documents, offline and live.
Check yourself
- A teammate wants to drop RRF and add the two raw scores instead:
ts_rank_cdplus cosine similarity, half and half. What breaks, and what do you tell them? The two scores aren't on the same scale, so one side quietly dominates, and which one depends on the question. RRF uses only ranks, so there's nothing to calibrate. If they want to weight one side, weight its rank term and measure the change with part 2's eval. - Your search for 5 passages sometimes returns 3. Where do you look first? A filter that runs after a
LIMIT, or a filtered HNSW scan without iterative scans. - Try it 1. (1) The chunk that's 2nd in both: 1/62 + 1/62 ≈ 0.032, against 1/61 ≈ 0.016. Agreement beats one high rank. (2) Two. The superseded chunk takes a slot in a branch, gets dropped at the end, and nothing replaces it. The live run of 12 November 2026 hit exactly that, which is why every filter sits in
candidates.
Part 2: sync, measure, and a harder corpus
Why this matters
Part 1 built the search and watched it put the LK-3150 row first. One question isn't a measurement, though. So now the question every team skips: is it better, and by how much?
On 38 labeled questions over 15 documents, the naive pipeline finds nothing in its top 10 for 11 of them. On 834 documents it finds the right passage in its top 5 for only a third offline (about half live). This part syncs the corpus, measures both pipelines, and shows you which numbers to believe.
Build it, continued
Step 6: the sync job
Before you can measure, the table needs the documents. The sync job reads the connector and indexes what changed. What to notice: the hash check comes first. Most syncs change nothing, and they should cost nothing.
From src/aip/knowledge/sync.py:
def sync(snapshot: Snapshot, store: PgStore, model: ModelClient, mirror: Mirror | None = None,
authz: OpenFGA | None = None, source: str = "larkfield-drive",
parse_cache: Path | None = None, full: bool = False) -> SyncReport:
"""full=True re-indexes every document: use it after changing the chunker or the context prompt."""
report, cache = SyncReport(), PgContextCache(store.conn)
known = {} if full else store.indexed_sha()
for doc in snapshot.docs:
if known.get(doc.meta.doc_id) == doc.sha256:
store.refresh_meta(doc)
if mirror and not mirror.refresh(source, doc):
mirror.write(source, doc, parse(doc, parse_cache).markdown)
report.unchanged += 1
continue
markdown, chunks = prepare(doc, model, cache, parse_cache)
store.upsert(source, doc, chunks, model.embed([c.indexed_text() for c in chunks]))
naive = fixed_chunks(doc.meta.doc_id, markdown)
store.upsert(source, doc, naive, model.embed([c.body for c in naive]), index="baseline")
if mirror: # lesson 3.2
mirror.write(source, doc, markdown)
report.indexed += 1
report.chunks += len(chunks)
Unchanged bytes are not parsed or embedded again, but freshness and the access list are refreshed, because permissions change more often than text. Each changed document is indexed twice, chunks under main and naive windows under baseline.
After the loop, documents gone from the source are pruned. Two branches wait for later lessons: the mirror (lesson 3.2) and OpenFGA (lesson 4.2).
uv run aip-knowledge sync
uv run aip-knowledge sync
(cd infra/compose && docker compose exec postgres psql -U aip -d aip -c "SELECT index_name, count(*) FROM knowledge.chunks GROUP BY index_name ORDER BY index_name;")
sync: 15 documents from the connector (ttlMs=900000); indexed=15 unchanged=0 pruned=0 chunks=60 tuples +0 -0
sync: 15 documents from the connector (ttlMs=900000); indexed=0 unchanged=15 pruned=0 chunks=0 tuples +0 -0
index_name | count
------------+-------
baseline | 42
main | 60
(2 rows)
The second run does no work.
Step 7: measure
You'll see numbers from two corpora (15 documents and 834) and two modes (offline on your laptop, live with real embeddings). Step 8 puts them side by side in one table. Here, the offline run on the small corpus.
Labels are quotes, not chunk ids, so the same labels grade any chunker. The metric functions:
From src/aip/knowledge/evals.py:
def recall_at(case: Case, passages: list[Passage], k: int) -> float:
slots = case.required()
filled = sum(1 for slot in slots if any(r <= k for r, _ in hits(case, passages, slot)))
return filled / len(slots)
def reciprocal_rank(case: Case, passages: list[Passage]) -> float:
ranks = [r for r, _ in hits(case, passages, [e for slot in case.required() for e in slot])]
return 1.0 / min(ranks) if ranks else 0.0
def negative_at(case: Case, passages: list[Passage], k: int = 5) -> bool:
"""A hard negative (an outdated or sibling passage) in the top k."""
return any(r <= k for r, _ in hits(case, passages, case.negatives))
You computed these by hand in the primer: recall@k, reciprocal rank, and neg@5, a hard negative (an outdated or sibling passage) in the top 5. ndcg_at sits just below them in the same file. What a change in each means in practice:
- recall@5 up: evidence that was missing now reaches the model.
- MRR (mean reciprocal rank) up, recall@5 flat: the evidence was there and moved up the list.
- nDCG@10 up: the answering passage now comes before the ones that only support it.
- neg@5 down: fewer outdated or sibling passages in the top 5. Lower is better.
eval runs baseline, hybrid, and hybrid plus rerank (30 candidates to 10) as a principal who may read everything, on the corpus's labels: _evals/queries.yaml if it has one (the large corpus), else _evals/retrieval.yaml (the small one). The label loader is in "Full code".
uv run aip-knowledge eval
AIP_RERANK=off uv run aip-knowledge eval
model: OfflineModel rerank: overlap (offline numbers are a floor, not a model's quality)
naive top-k (baseline) n=38 recall@1=0.434 recall@5=0.579 recall@10=0.711 mrr=0.512 ndcg@10=0.551 misses=q09,q11,q12,q13,q14,q16,q18,q31,q36,q37,q38
hybrid, no rerank n=38 recall@1=0.605 recall@5=0.816 recall@10=0.947 mrr=0.701 ndcg@10=0.762 misses=q09,q16
hybrid + rerank n=38 recall@1=0.645 recall@5=0.921 recall@10=0.947 mrr=0.763 ndcg@10=0.811 misses=q09,q16
model: OfflineModel rerank: off (offline numbers are a floor, not a model's quality)
naive top-k (baseline) n=38 ...
hybrid, no rerank n=38 recall@1=0.605 recall@5=0.816 ...
hybrid + rerank skipped: rerank is off (AIP_RERANK, decision 0508)
The first line says what ran. With rerank off, the third row is skipped, never faked.
One question is worth about 0.026 of recall here, so a 0.02 difference is noise; the 0.24 between baseline and hybrid is not.
q09 and q16 miss in every row, for a reason lesson 6.1 reads.
Try it 2: nDCG by hand. Question q28 in _evals/retrieval.yaml asks when a doctor's note is needed. Its labels hold two quotes from the HR handbook: "From the fourth day, a doctor's note is required" (grade 2) and "self-certify sickness for up to 3 days" (grade 1). Suppose a search ranks the grade-1 passage first and the grade-2 passage fourth. Work out nDCG@10 on paper first, the way the primer does. Then check:
uv run python - <<'EOF'
from pathlib import Path
from aip.knowledge.evals import load_cases, ndcg_at
from aip.knowledge.retrieval import Passage
case = next(c for c in load_cases(Path("data/larkfield/knowledge/_evals/retrieval.yaml")) if c.id == "q28")
hr = lambda text: Passage("hr#1", "hr-handbook", "Employee handbook", "", text, "uri", "2026-07-01")
other = Passage("x#1", "pol-expenses", "Travel and expenses", "", "Submit expense claims within 30 days of the trip.", "uri", "2026-03-30")
ranked = [hr("You may self-certify sickness for up to 3 days."), other, other,
hr("From the fourth day, a doctor's note is required.")]
print(round(ndcg_at(case, ranked), 3))
EOF
0.631
Then Try it 3: move the doctor's-note passage to rank 2 in ranked and predict the number before you run it. Both answers, worked, are in "Check yourself".
Then run the tests:
uv run pytest -q tests/knowledge -m "not docling"
...
41 passed, 1 deselected in ...
test_integration_search.py runs against this database. test_superseded_documents_are_filtered_before_the_limit asks for 1, 2 and 3 passages and must get exactly that many, all current. The Docling test from lesson 2.1 is left out for speed.
Step 8: what the large corpus changes
Fifteen documents are too few to tell methods apart. So the course tracks one running recall table on the large corpus: recall@5 over its 125 questions. It starts here, lesson 2.3 adds rows, and lesson 6.1 closes it, always with the same columns. Offline is your laptop, OfflineModel. Live is real embeddings.
| Pipeline | Added in | Offline | Live |
|---|---|---|---|
| naive baseline: fixed windows, dense only | 2.2 | 0.340 | 0.528 |
| hybrid: full-text and dense, fused | 2.2 | 0.536 | 0.684 |
| hybrid + overlap rerank | 2.2 | 0.604 | not run (no reranker live) |
Live: the run of 14 November 2026, the Postgres path, OpenAI's text-embedding-3-small at 1,024 dimensions behind embed-default, rerank off. Offline commands and the full table: Appendix B.
Live, real embeddings lift the baseline a lot, and hybrid still leads. The live column is the one to carry forward.
The large corpus pulls every number down, which is the point of it. On the small corpus the same three pipelines score 0.579, 0.816 and 0.921 offline (Step 7). It was too easy even live: on 12 November 2026 the naive baseline reached 0.895 and hybrid 1.000 (the large corpus's README).
One more live number: neg@5 drops from 0.55 for the baseline to 0.15 for hybrid. It counts only the questions that have an outdated or sibling passage to find. Better embeddings find old versions as easily as current ones, so the status filter matters more live.
(A second indexing gave the baseline 0.536, not 0.528: re-embedding the same text through the gateway isn't bit-identical.)
Many of hybrid's misses ask about the template agreements, whose clauses say "the Customer" and never the name. That's lesson 2.3.
Your turn (10 min)
Hybrid is two rankings fused. How much does each half carry on its own? Write a short script that builds the in-memory index of the small corpus (build_memory_index from aip.knowledge.pipeline builds part 1's MemoryIndex from a snapshot) and scores three search modes with evaluate from aip.knowledge.evals. MemoryIndex.search takes mode="lexical", "dense" or "hybrid" (Step 4 of part 1), and load_cases reads _evals/retrieval.yaml. Print recall@5 and MRR for each mode. Before you run it, rank the three modes. Then decide what you'd tell a teammate who wants to drop the dense half.
What breaks
The code above prevents three failures: an all-words query that silences the lexical branch (the & to | swap), a filter after the limit that returns a short page or an outdated passage (one candidate set, iterative scans), and a reranker the provider doesn't have (an explicit setting, lenient on the answer path, strict in the eval, Appendix A). Two it doesn't:
- A model change without a re-embed. Old vectors against new query vectors give quietly random results. Control: the dimension fixed in the migration, and
sync --full(lesson 2.3). - A test set too easy to fail. On 15 documents a regression from 0.92 to 0.89 is one question. Control: keep a corpus with versions, siblings and noise in the eval.
Decide
- Default: Postgres full-text plus pgvector HNSW, fused by RRF in one query, every filter in the candidate set. One store, permissions on rows, one backup.
- Rerank: off unless your provider reranks and your eval shows the gain. Set
AIP_RERANK=gatewayoncererank-defaultmaps to one. - Add a BM25 extension when lexical ranking measures as where you lose (rare identifiers, long documents). Add Qdrant when one node can't hold the vectors or the query rate.
- Keep the baseline in every eval, on a corpus hard enough to tell methods apart.
You now have the search every later lesson stands on. Lesson 2.3 makes each chunk say which document it came from.
Check yourself
- A colleague wants the overlap rerank on in production because it adds 0.07 of recall@5 offline. What do you say? Offline the "embeddings" are shared words too, so a shared-word rerank helps there. Live, decision record 0508 notes it made the metrics worse than no rerank. Measure live first.
- Hybrid with the offline rerank gets 0.921 recall@5 on the small corpus and 0.604 on the large one. Which do you report to your team? Both, and the large one as the target. The small one fits in a prompt and can't tell methods apart.
- Try it 2. 0.631. The gains are 1 at rank 1 and 3 at rank 4:
1/log2(2) + 3/log2(5)is 2.292, over the ideal 3.631. - Try it 3. 0.797:
1/log2(2) + 3/log2(3)is 2.893, over the same 3.631. - Your turn. One way to write it:
from aip.config import get_settings
from aip.knowledge.evals import evaluate, load_cases
from aip.knowledge.ingest import pull_local
from aip.knowledge.model import OfflineModel
from aip.knowledge.pipeline import build_memory_index
s = get_settings()
snap = pull_local(s.knowledge_dir)
index = build_memory_index(snap, OfflineModel(), s.knowledge_dir / "_parsed")
cases = load_cases(s.knowledge_dir / "_evals" / "retrieval.yaml")
for mode in ("lexical", "dense", "hybrid"):
r = evaluate(mode, cases, lambda q: index.search(q, k=10, mode=mode))
print(f"{mode:8} recall@5={r.metrics['recall@5']:.3f} mrr={r.metrics['mrr']:.3f}")
lexical recall@5=0.895 mrr=0.793
dense recall@5=0.737 mrr=0.533
hybrid recall@5=0.789 mrr=0.738
Run at tag e5-m2-l2 on 16 Nov 2026. In memory, hybrid scores 0.789, not the 0.816 of the Postgres eval in Step 7: the in-memory lexical side is real BM25 and Postgres's is ts_rank_cd, as the primer warned, so the two backends rank a little differently. If you ranked hybrid first, offline says otherwise: lexical alone wins. Don't drop the dense half on this evidence. Offline, the "embeddings" are hashed words, so the dense half is a weaker copy of the lexical one and mostly adds noise to the fusion, and the lexical half here is MemoryIndex's real BM25. Synonyms are what a real embedding model is for, and they only show up live. This course has no live lexical-only run, so the honest answer to your teammate is "measure both halves live before you drop either".
Transcript
Hybrid search, in plain Postgres, that's today. You'll put words and vectors in one table, filter before you rank, and measure the result. All right, this lesson adds the search itself: a schema, one SQL query, the sync job, a baseline, and the evals. And it adds a second corpus: eight hundred and forty-three files, which is eight hundred and thirty-four documents plus a README, the labels and the build files.
A drive closer to a real one, with old versions, drafts and near-identical contracts. We'll need it by the end. So, one table of chunks. The full-text column is generated, so Postgres keeps it in step with the text, and nobody forgets to update it. It indexes the heading too. Now, the vector column has a fixed dimension. That means a new embedding model is a migration and a full re-embed, never a quiet swap.
Two indexes: GIN, an inverted index, for words, and HNSW, a graph that finds near neighbors fast, for vectors. And the application role gets select, nothing else. Now, the query. First, the question becomes a text search query. By default Postgres wants every word to match, and real questions almost never do, right? So we swap "and" for "or". Then the part I care most about: one candidate set, with every filter in it.
The documents you may read, and only current versions. Both branches rank inside that set. Why does that matter? If the status filter ran at the end, after each branch had cut to its top thirty, a superseded chunk could take a slot, and you'd get two passages when you asked for three. That happened in our first live run. Then reciprocal rank fusion: one over sixty plus the rank, summed.
Ranks only, so we never compare a text score with a cosine distance. Two connections here. Searches run as the application's role, which can only read. The sync job writes as the owner. And nobody switches roles in the middle of a transaction, so a bug in a search path can't write. Oh, and iterative scans keep a filtered vector search going until it has enough rows.
Now, the models. And yes, this changes E1 code. The client we wrote there gains embed and rerank, with the same retries, deadline and trace headers as chat. A reranker, by the way, is a second, slower model that scores the question and each candidate together. The knowledge layer calls an alias, embed default, and sends the dimension the schema fixed.
So there's no model id anywhere in this code. Reranking is a setting: off, overlap, or gateway. Auto means overlap offline and off live. Overlap counts the question's words in each passage. To be clear, it's a stand-in so the path runs without a gateway, and there's no model in it. Why so careful? In our first live run, the provider had no rerank endpoint, the gateway answered five hundred, and every path that reranked crashed.
Now a failed rerank keeps the fused order on the answer path. The eval is strict and fails instead, because an eval has to measure what it says it measures. All right, the sync job. Each document's hash decides. Unchanged bytes don't go through the parser or get embedded again, but freshness and the access list are refreshed, because permissions change more often than text.
Sixty chunks. And if we run it again, there's nothing to do. Now, the labels are quotes from the document that answers, never chunk ids, so the same labels grade any chunker. And a quote only counts from its own document. Why? The same payment clause sits in thirty-one contracts on the big drive, so only the one the question names gets credit.
So let's measure. Three rows, on thirty-eight questions. The naive baseline finds the evidence in its top five for fifty-eight percent, and misses eleven questions completely. Hybrid search, eighty-two percent. With the overlap rerank, ninety-two. By the way, the first line says what ran: the stand-in model, and the rerank mode. Turn rerank off, and the third row says it was skipped.
It never pretends. And one question is worth about three points of recall here, so a two-point difference is noise. Twenty-four points, that's real. Now, question nine. A pallet arrived crushed, how fast must the customer tell us? What comes back is the refund policy. Reasonable, but it doesn't answer the question. The answer is in the shipping policy: damage must be reported within forty-eight hours.
Crushed and damage, different words for the same idea, and hashed words can't connect them. A real embedding model should. And here's the test for step three. Ask for one, two, three passages on a question where an old refund policy competes. You get exactly that many, all current. Ask with the filter off, and the old policy is there. The rest of the knowledge tests run against this database too.
All right, now the big drive. Eight hundred and thirty-four documents, about four hundred and forty-seven thousand tokens. One variable points every command at it, and it's still the stand-in model. This runs in process and takes about a minute, so while it runs, remember what we're looking for: whether the order of the methods survives a drive that looks real.
Same three rows. Recall at five: thirty-four percent for the baseline, fifty-four for hybrid, sixty for hybrid with the overlap rerank. On the small corpus the same rows read fifty-eight, eighty-two, ninety-two. So the order holds, every number drops, and now you can see how much is left. Look at the last column, too. The baseline puts an outdated or sibling passage in the top five for twenty-eight percent of the questions.
Hybrid, with every filter first, eleven. And many of the misses are questions about contracts whose clauses say "the Customer", never the name. That's the next lesson: contextual retrieval. See you there.
Going deeper
Part 1
- A stack created before E5. Add pgvector once with
(cd infra/compose && docker compose exec postgres sh /docker-entrypoint-initdb.d/03-pgvector.sh). Creating an extension needs a superuser, so the migration only checks that it's there. - The search, in memory.
MemoryIndex.search: filters first (allowed set, status), then rank, fuse, cut, the same order as the SQL.
From src/aip/knowledge/retrieval.py:
def search(self, query: str, k: int = 8, allowed: set[str] | None = None, mode: str = "hybrid",
rerank: Reranker | None = None, candidates: int = 30, current_only: bool = True) -> list[Passage]:
"""Filters first (allowed set, status), then rank, fuse, cut; rerank only if one is given."""
ids = self._ids(allowed, current_only)
if mode == "dense":
fused = [(i, 0.0) for i in self.dense(query, ids, candidates)]
elif mode == "lexical":
fused = [(i, 0.0) for i in self.lexical(query, ids, candidates)]
else:
fused = rrf([self.lexical(query, ids, candidates), self.dense(query, ids, candidates)])[:candidates]
order = [i for i, _ in fused]
if rerank and order:
ranked = rerank(query, [self.chunks[i].indexed_text() for i in order], k)
fused = [(order[j], s) for j, s in ranked]
return [self.passage(i, s) for i, s in fused[:k]]
- The two connections, checked.
PgStore, the class that runs the query, reads asaip_apponreader, for every search, and writes as the owner onconn, for the sync job, with no role switching. So a bug in a search path can't write. Check it (the class is in "Full code", at the end of part 2):
uv run python -c "
from aip.knowledge.pgstore import PgStore
s = PgStore()
print('reads as', s.reader.execute('SELECT current_user').fetchone()[0], '| writes as', s.conn.execute('SELECT current_user').fetchone()[0])
"
reads as aip_app | writes as aip
- What this tag adds.
git diff --stat=72 e5-m2-l1..e5-m2-l2 -- src data agents testslists it. The code: eight new files undersrc/aip/knowledge/(seven modules and the migration), small changes to E1's client, and tests (the full list is in "Full code", at the end of part 2). The data: the large corpus lands at this tag (834 documents, part 2's Appendix B); that's most of the diff. Two new people inpersonas.yaml, for the large corpus: Ravi, the CFO (chief financial officer), and Hana, a racking contractor. - The decisions behind this part, in
docs/decisions/: decision record 0501 (Qdrant, a dedicated vector database, beside Postgres is the runner-up when one node can't hold the load), 0502 (Postgres full-text over a BM25 extension) and 0505 (the offline model's hashed-word embeddings). - Iterative scans, the setting. Each search sets
hnsw.iterative_scan = relaxed_order(pgvector 0.8.0 and later), which keeps a filtered HNSW scan going until enough rows pass the filter. Without it, a filter that rejects most neighbors can return fewer rows than you asked for.
Part 2
- Labels as quotes are decision record 0504 in
docs/decisions/: the same labels grade any chunker.
Appendix A: rerank modes
Read this when you turn a reranker on, or when lesson 6.1 sends you here.
aip.llm.Client.rerank and GatewayModel.rerank call the gateway's /v1/rerank with the rerank-default alias (both in "Full code"). Which reranker runs is a setting. From src/aip/knowledge/model.py:
def default_model() -> ModelClient:
s = get_settings()
return GatewayModel(dim=s.embed_dim) if s.live else OfflineModel(s.embed_dim)
def rerank_mode(model: ModelClient) -> str:
mode = get_settings().rerank
if mode == "auto":
return "overlap" if isinstance(model, OfflineModel) else "off"
return mode
def reranker(model: ModelClient, mode: str | None = None, strict: bool = False) -> Reranker | None:
"""None means: keep the fused order. A gateway reranker that fails keeps it too and says so,
unless strict (an eval must measure what it says it measures)."""
mode = mode or rerank_mode(model)
if mode == "off":
return None
if mode == "overlap":
return overlap_rerank
if not isinstance(model, GatewayModel):
raise ValueError("AIP_RERANK=gateway needs the gateway model (AIP_LIVE=1)")
def through_gateway(query: str, documents: list[str], top_n: int) -> list[tuple[int, float]]:
try:
return model.rerank(query, documents, top_n)
except GatewayError as e: # rerank is an optimization: the fused order still stands
if strict:
raise
log.warning("rerank failed (%s): keeping the fused order", e)
return [(i, 0.0) for i in range(min(top_n, len(documents)))]
return through_gateway
AIP_RERANK is off, overlap, gateway or auto (overlap offline, off live). overlap is overlap_rerank, the share of the question's words each passage contains: a gateway-free stand-in, not a model. gateway calls rerank-default, for a provider that reranks (Cohere, Jina or Voyage behind LiteLLM, the platform's model gateway).
Why the ceremony? On 12 November 2026 the live run crashed every path that reranked: OpenAI has no rerank endpoint, and the gateway answered 500. Now a failed rerank keeps the fused order and logs it, except in the eval, which is strict and fails. An eval must measure what it says it measures.
uv run pytest -q tests/knowledge/test_model.py::test_a_provider_without_rerank_keeps_the_fused_order
. [100%]
1 passed in ...
Appendix B: the large corpus, step by step
The small corpus (15 documents, about 3,700 tokens) is too easy to separate methods: hybrid plus rerank already finds 92% in the top 5. The large one is 834 documents and about 447,000 tokens, with 15 superseded versions and 3 drafts that keep their titles, 49 agreements from one template, 320 support tickets, split tables and an OCR (optical character recognition) scan (its README.md has the statistics). One variable selects it.
AIP_KNOWLEDGE_DIR=data/larkfield/knowledge-large uv run aip-knowledge --memory eval
model: OfflineModel rerank: overlap (offline numbers are a floor, not a model's quality)
naive top-k (baseline) n=125 recall@1=0.144 recall@5=0.340 recall@10=0.388 mrr=0.240 ndcg@10=0.238 neg@5=0.277 misses=q001,...
hybrid, no rerank n=125 recall@1=0.276 recall@5=0.536 recall@10=0.632 mrr=0.406 ndcg@10=0.419 neg@5=0.106 misses=q001,...
hybrid + rerank n=125 recall@1=0.328 recall@5=0.604 recall@10=0.636 mrr=0.463 ndcg@10=0.471 neg@5=0.085 misses=q001,...
About a minute, in process. n=125 because 4 of the 129 questions are unanswerable for everyone (lesson 6.1 counts those).
On the small corpus a method looks finished at 92%. On the large one you see what's left: the baseline puts an outdated or sibling passage in the top 5 for 28% of the questions; hybrid, filtering status first, for 11%. Many of hybrid's misses (q037 to q042) ask about the template agreements.
Full code
Part 1
Where the excerpts in the lesson sit in their files, at tag e5-m2-l2:
src/aip/knowledge/migrations/0001_knowledge.py, lines 35-51src/aip/knowledge/pgstore.py, lines 23-29, 30-38 and 39-50src/aip/llm/client.py, lines 104-108src/aip/knowledge/baseline.py, lines 1-11src/aip/knowledge/retrieval.py, lines 94-108
Part 2
Where the excerpts in the lesson sit in their files, at tag e5-m2-l2:
src/aip/knowledge/sync.py, lines 38-58src/aip/knowledge/evals.py, lines 75-89src/aip/knowledge/model.py, lines 99-130
The diff for this tag, git diff --stat=72 e5-m2-l1..e5-m2-l2 -- src data agents tests (the ... is the large corpus: 834 documents plus its README and build files, 843 files in all):
data/larkfield/identity/personas.yaml | 4 +
...
.../larkfield/knowledge/_evals/retrieval.yaml | 47 +
src/aip/config.py | 3 +
src/aip/knowledge/baseline.py | 11 +
src/aip/knowledge/cli.py | 12 +-
src/aip/knowledge/evals.py | 174 +
.../knowledge/migrations/0001_knowledge.py | 62 +
src/aip/knowledge/model.py | 130 +
src/aip/knowledge/pgstore.py | 158 +
src/aip/knowledge/pipeline.py | 36 +
src/aip/knowledge/retrieval.py | 113 +
src/aip/knowledge/sync.py | 67 +
src/aip/llm/client.py | 22 +-
.../mcp_servers/connectors/larkfield_drive.py | 9 +-
tests/knowledge/stack.py | 16 +
tests/knowledge/test_evals.py | 54 +
tests/knowledge/test_integration_search.py | 54 +
tests/knowledge/test_large_corpus.py | 74 +
tests/knowledge/test_model.py | 57 +
tests/knowledge/test_retrieval.py | 25 +
863 files changed, 52233 insertions(+), 9 deletions(-)
The whole migration, from src/aip/knowledge/migrations/0001_knowledge.py, lines 15-58:
def upgrade() -> None:
# pgvector comes from the compose init (03-pgvector.sh): creating an extension needs a superuser.
op.execute("""DO $$ BEGIN
IF NOT EXISTS (SELECT FROM pg_extension WHERE extname = 'vector') THEN
RAISE EXCEPTION 'extension vector is missing: run infra/compose/init/postgres/03-pgvector.sh';
END IF; END $$""")
op.execute("CREATE SCHEMA IF NOT EXISTS knowledge")
op.execute("""
CREATE TABLE knowledge.documents (
doc_id text PRIMARY KEY,
source text NOT NULL, -- connector that synced it
path text NOT NULL, -- path in the source
title text NOT NULL,
uri text NOT NULL, -- where a reader opens the original
updated date NOT NULL, -- last change, as the source reports it
fetched_at timestamptz NOT NULL, -- when the connector last read it
status text NOT NULL DEFAULT 'current',
content_sha256 text NOT NULL,
acl text[] NOT NULL -- 'group:finance', 'user:priya': mirror of the source ACL
)""")
op.execute(f"""
CREATE TABLE knowledge.chunks (
chunk_id text PRIMARY KEY,
index_name text NOT NULL DEFAULT 'main', -- 'main' or 'baseline'
doc_id text NOT NULL REFERENCES knowledge.documents ON DELETE CASCADE,
ord int NOT NULL,
section text NOT NULL,
body text NOT NULL,
context text NOT NULL DEFAULT '',
acl text[] NOT NULL, -- copied from the document, so RLS needs no join
tsv tsvector GENERATED ALWAYS AS
(to_tsvector('english', context || ' ' || section || ' ' || body)) STORED,
embedding vector({DIM}) NOT NULL
)""")
op.execute("CREATE INDEX chunks_tsv ON knowledge.chunks USING gin (tsv)")
op.execute("CREATE INDEX chunks_hnsw ON knowledge.chunks USING hnsw (embedding vector_cosine_ops)")
op.execute("CREATE INDEX chunks_doc ON knowledge.chunks (doc_id)")
op.execute("""
CREATE TABLE knowledge.context_cache (
key text PRIMARY KEY, context text NOT NULL, created_at timestamptz NOT NULL DEFAULT now())""")
# The application reads as aip_app, which owns nothing (E3): lesson 4.3 turns on row-level security for it.
op.execute("GRANT USAGE ON SCHEMA knowledge TO aip_app")
op.execute("GRANT SELECT ON knowledge.documents, knowledge.chunks TO aip_app")
The query and the store, from src/aip/knowledge/pgstore.py, lines 23-73:
HYBRID_SQL = """
WITH q AS (
SELECT replace(plainto_tsquery('english', %(query)s)::text, '&', '|')::tsquery AS tsq -- any word, not all
), candidates AS NOT MATERIALIZED ( -- every filter before any LIMIT (inlined: HNSW still applies)
SELECT c.* FROM knowledge.chunks c JOIN knowledge.documents d USING (doc_id)
WHERE c.index_name = %(index)s AND c.doc_id = ANY(%(allowed)s)
AND (%(current_only)s = false OR d.status = 'current')
), lexical AS (
SELECT c.chunk_id, row_number() OVER (ORDER BY ts_rank_cd(c.tsv, q.tsq) DESC, c.chunk_id) AS r
FROM candidates c, q
WHERE c.tsv @@ q.tsq
ORDER BY r LIMIT %(n)s
), dense AS (
SELECT c.chunk_id, row_number() OVER (ORDER BY c.embedding <=> %(qvec)s::vector, c.chunk_id) AS r
FROM candidates c
ORDER BY c.embedding <=> %(qvec)s::vector LIMIT %(n)s
), fused AS (
SELECT chunk_id, coalesce(1.0 / (60 + l.r), 0) + coalesce(1.0 / (60 + d.r), 0) AS rrf
FROM lexical l FULL OUTER JOIN dense d USING (chunk_id)
)
SELECT c.chunk_id, c.doc_id, d.title, c.section, c.body, c.context, d.uri, d.updated::text,
d.fetched_at::text, d.status, f.rrf
FROM fused f
JOIN knowledge.chunks c USING (chunk_id)
JOIN knowledge.documents d ON d.doc_id = c.doc_id
ORDER BY f.rrf DESC, c.chunk_id
LIMIT %(n)s
"""
class PgStore:
def __init__(self, app_url: str | None = None, owner_url: str | None = None):
# autocommit: each transaction() is top-level, so set_config(..., true) ends with it
self.reader = psycopg.connect(app_url or db.url(), autocommit=True) # aip_app
self.conn = psycopg.connect(owner_url or db.url(admin=True), autocommit=True) # the owner
@contextmanager
def as_reader(self, principals: list[str]) -> Iterator[psycopg.Cursor]:
"""One transaction as the application (aip_app), with RLS keyed on the caller's principals."""
with self.reader.transaction(), self.reader.cursor() as cur:
cur.execute("SELECT set_config('aip.principals', %s, true)", (",".join(principals),))
cur.execute("SET LOCAL hnsw.iterative_scan = relaxed_order") # filtered HNSW keeps filling k
yield cur
def search(self, query: str, qvec: list[float], principals: list[str], allowed: set[str],
k: int = 30, index: str = "main", current_only: bool = True) -> list[Passage]:
with self.as_reader(principals) as cur:
cur.execute(HYBRID_SQL, {"query": query, "qvec": vec(qvec), "allowed": sorted(allowed),
"n": k, "index": index, "current_only": current_only})
rows = cur.fetchall()
return [Passage(r[0], r[1], r[2], r[3], r[4], r[6], r[7], r[8], r[9], float(r[10])) for r in rows]
embed and rerank on E1's client, from src/aip/llm/client.py, lines 104-117:
def embed(self, alias: str, texts: list[str], *, dimensions: int | None = None) -> list[list[float]]:
"""E5: embeddings by alias (`embed-default`), with the same retries and deadline as complete."""
body = {"model": alias, "input": texts, **({"dimensions": dimensions} if dimensions else {})}
data = self._post(body, path="/v1/embeddings", parse=lambda resp, **_: resp.json())
return [d["embedding"] for d in sorted(data["data"], key=lambda d: d["index"])]
def rerank(self, alias: str, query: str, documents: list[str], *, top_n: int) -> list[tuple[int, float]]:
"""E5: (index, score) best first, through the gateway's /v1/rerank. Only some providers rerank
(Cohere, Jina, Voyage); OpenAI does not, and the gateway answers 500 (decision 0508)."""
body = {"model": alias, "query": query, "documents": documents, "top_n": top_n}
data = self._post(body, path="/v1/rerank", parse=lambda resp, **_: resp.json())
return [(r["index"], r["relevance_score"]) for r in data["results"]]
def _post(self, body: dict, path: str = "/v1/chat/completions", parse=None) -> Any:
The knowledge layer's gateway model, from src/aip/knowledge/model.py, lines 36-51:
class GatewayModel:
"""aip.llm.Client on this application's key (AIP_GATEWAY_KEY): retries, deadline, cost header, traces."""
def __init__(self, client: Client | None = None, dim: int | None = None):
self.client = client or Client()
self.dim = dim or get_settings().embed_dim
def chat(self, messages: list[dict], alias: str = "fast") -> str:
return self.client.complete(alias, messages, tags=("knowledge",)).text or ""
def embed(self, texts: list[str]) -> list[list[float]]:
return self.client.embed("embed-default", texts, dimensions=self.dim)
def rerank(self, query: str, documents: list[str], top_n: int) -> list[tuple[int, float]]:
"""Only with AIP_RERANK=gateway, and only if `rerank-default` maps to a provider that reranks."""
return self.client.rerank("rerank-default", query, documents, top_n=top_n)
The whole sync job, from src/aip/knowledge/sync.py, lines 38-67:
def sync(snapshot: Snapshot, store: PgStore, model: ModelClient, mirror: Mirror | None = None,
authz: OpenFGA | None = None, source: str = "larkfield-drive",
parse_cache: Path | None = None, full: bool = False) -> SyncReport:
"""full=True re-indexes every document: use it after changing the chunker or the context prompt."""
report, cache = SyncReport(), PgContextCache(store.conn)
known = {} if full else store.indexed_sha()
for doc in snapshot.docs:
if known.get(doc.meta.doc_id) == doc.sha256:
store.refresh_meta(doc)
if mirror and not mirror.refresh(source, doc):
mirror.write(source, doc, parse(doc, parse_cache).markdown)
report.unchanged += 1
continue
markdown, chunks = prepare(doc, model, cache, parse_cache)
store.upsert(source, doc, chunks, model.embed([c.indexed_text() for c in chunks]))
naive = fixed_chunks(doc.meta.doc_id, markdown)
store.upsert(source, doc, naive, model.embed([c.body for c in naive]), index="baseline")
if mirror: # lesson 3.2
mirror.write(source, doc, markdown)
report.indexed += 1
report.chunks += len(chunks)
keep = {d.meta.doc_id for d in snapshot.docs}
report.pruned = store.prune(source, keep)
if mirror:
mirror.prune(source, keep)
if authz is not None: # lesson 4.2
from aip.knowledge.authz import desired_tuples
report.tuples_written, report.tuples_deleted = authz.sync(desired_tuples(snapshot))
return report
The label loader. One loader reads both label files: the small corpus's retrieval.yaml (38 questions, quotes graded 2 for answers, 1 for support) and the large corpus's queries.yaml, which adds grade 3, groups (an answer needing a passage from each of two places), hard negatives at grade 0 and the expected outcome per person. contains binds a quote to its document: the same payment clause sits in 31 sibling agreements, and only the named one counts. From src/aip/knowledge/evals.py, lines 43-61:
def required(self) -> list[list[Evidence]]:
"""What recall counts: one slot per group (any grade>=2 item of it fills it); without groups,
one slot per evidence item (the small set)."""
names = sorted({g for e in self.evidence for g in e.groups})
if not names:
return [[e] for e in self.evidence]
return [[e for e in self.evidence if g in e.groups and e.grade >= 2] for g in names]
def load_cases(path: Path) -> list[Case]:
raw = yaml.safe_load(path.read_text())["cases"]
item = lambda e: Evidence(e["doc"], e["quote"], e["grade"], e.get("groups", [])) # noqa: E731
return [Case(c["id"], c["query"], [item(e) for e in c.get("evidence", [])],
[item(e) for e in c.get("hard_negatives", [])], c.get("expected", {}), c.get("answerable", True))
for c in raw]
def contains(p: Passage, e: Evidence) -> bool:
return p.doc_id == e.doc and norm(e.quote) in norm(f"{p.section}\n{p.text}")
Sources
- PostgreSQL 17 documentation, 12.3.3 Ranking Search Results ("do not use any global information"). https://www.postgresql.org/docs/17/textsearch-controls.html (checked 12 Nov 2026)
- pgvector changelog (0.8.7; iterative scans since 0.8.0). https://github.com/pgvector/pgvector/blob/master/CHANGELOG.md (checked 11 Nov 2026)
- Qdrant releases, the runner-up store. https://github.com/qdrant/qdrant/releases (checked 11 Nov 2026)
- Cormack, Clarke and Büttcher, "Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods", SIGIR 2009 (k = 60, "near-optimal, but the choice was not critical"). https://cormack.uwaterloo.ca/cormacksigir09-rrf.pdf (checked 15 Nov 2026: the quote is verbatim)
- Reference repository
ai-platform, tage5-m2-l2; decision records 0501, 0502, 0504, 0505 and 0508 indocs/decisions/;data/larkfield/knowledge-large/README.md. Outputs run at the tag on 14 Nov 2026; live run of 14 Nov 2026 indocs/LIVE_RUNS_E5.md, branchlive-e5.