Building Replaceable Local RAG with Ollama and LanceDB
Part 2: a retrieval-only service with pinned embedding identities, provenance-aware chunks, hybrid search, and replaceable components.
Personal Session Memory · Part 2 of 4
1. Archive · 2. Retrieval · 3. Operations · 4. Recall
A Search Result Should Be Verifiable
Suppose I ask: “Why did I change the indexing schedule?” A useful result is not just a paragraph mentioning schedules. I need to know who said it, when, under which constraints, and whether a later message corrected the proposal.
The foundation from Part 1 is a versioned conversation archive. This part describes Session Search, the separate service that reads a published archive checkpoint and returns relevant passages with enough provenance to inspect them.
The source archive remains authoritative. Search indexes are replaceable. The service returns evidence, not generated answers; Codex can use that evidence through the skill in Part 4, but the CLI also works on its own.
A Small Local Stack
The implementation runs on my M4 Mac mini with 32 GB of memory:
| Component | Role |
|---|---|
| Ollama | Local embedding inference |
qwen3-embedding:0.6b | Pinned embedding model, producing 1,024-dimensional vectors |
| LanceDB OSS | Vector storage and similarity search |
| SQLite catalog and FTS5 | Normalized text, provenance, and lexical search |
| Python API and CLI | A stable retrieval interface for humans and agents |
The Qwen model provides a small multilingual starting point; its model card documents its capabilities. I did not establish it as the best model for this corpus. An affordable baseline and a credible replacement path mattered more than declaring a permanent winner.
The September implementation pins LanceDB to 0.38.0 and the companion Lance SDK to 11.0.0. Its retention behavior depends on that tested combination, not an assumption that every future release is interchangeable.
Ollama and LanceDB Have Different Process Models
The indexer and query path call Ollama’s local POST /api/embed endpoint. Ollama performs inference; my Python code does not load the embedding model through a second Transformers runtime.
The LanceDB adapter, by contrast, opens a local directory inside the Python process. There is no separate always-running LanceDB daemon in this deployment. The official quickstart describes that embedded connection mode.
This keeps the deployment small without coupling the rest of the code to either component’s API.
Make Replaceability Concrete
The core depends on three Python protocols: Embedder, VectorStore, and Ranker. Plain vectors, IDs, and dictionaries cross their boundaries rather than vendor-specific document objects. Trusted local configuration selects the implementations; search requests cannot specify arbitrary code factories.
The practical consequences are:
| Change | Consequence in this implementation |
|---|---|
| Replace the vector backend with the same embedding identity | Reuse cached vectors; rebuild the backend’s storage/index |
| Change the model, digest, dimensions, query instruction, or relevant options | Use a new embedding identity and compute compatible vectors |
| Change rank fusion | Reuse existing embeddings and candidate indexes |
| Change chunking | Rebuild affected chunk identities; reuse vectors only when the exact embedding input still matches |
The embedding cache is keyed by model identity and exact input text. A mutable model name alone is insufficient, so the model digest is pinned too. Equal vector dimensions do not make two models’ embeddings compatible.
An exact flat SQLite vector backend exists for small fixtures and migration checks. Exercising two real backends is a more meaningful test of replaceability than simply naming an interface VectorStore.
This does not make replacement free. Re-embedding can be expensive, and a new backend needs its own index construction. The benefit is that those changes do not require re-acquiring the original conversations or rewriting the caller’s workflow.
Chunk the Evidence Without Losing Its Identity
The first chunker uses a maximum of 2,400 characters with 200 characters of overlap. Those are characters, not tokens, and they are baseline settings rather than a demonstrated optimum.
Each chunk carries its source event, revision, offset, role, session, and provenance. Meaningful message and tool text can enter the index, while empty metadata and inline binary data are not converted into invented prose. Attachment references remain references; this version does not add OCR or follow arbitrary URLs.
Short acknowledgments can include limited preceding context when a verified parent relationship is available. Otherwise, a sentence such as “yes, do that” is difficult to interpret in isolation.
Even with context, chronological proximity is not proof of a conversation branch. An assistant proposal followed by an unrelated user message must not become “the user approved this.” Generated summaries and tool output quoting earlier conversations need the same caution.
This is why the retrieval interface returns more than a similarity score. It preserves the identifiers needed to ask for the original event or a larger session window.
Combine Semantic and Lexical Retrieval
My history mixes Korean, English, code symbols, filenames, measurements, and error messages. A semantic search can find the topic while missing the exact identifier I remember. A keyword search can miss the same idea phrased differently or in another language.
The hybrid path combines both:
flowchart LR
Query["Question"] --> Embed["Ollama query embedding"]
Context["Relevant current-task context"] --> Embed
Embed --> Vector["LanceDB cosine candidates"]
Query --> Lexical["SQLite FTS5 keyword candidates"]
Vector --> Fusion["Weighted rank fusion"]
Lexical --> Fusion
Fusion --> Evidence["Passages, provenance,<br/>and nearby records"]
The lexical representation adds Korean bigrams to its word tokens. Rank fusion combines candidate positions rather than treating raw keyword and vector scores as the same unit:
1
2
3
score(chunk) = sum(weight / (60 + rank))
semantic weight = 1.0
lexical weight = 0.8
These settings and the semantic-only candidate threshold are provisional, not calibrated confidence measures. The implementation also limits hits per session and collapses identical result text so one repeated transcript does not dominate the response. It does not delete distinct archived records.
If semantic retrieval fails in hybrid mode, the response reports a degraded result instead of disguising keyword-only retrieval as full success. “No relevant evidence found” likewise means no match in the indexed material—not proof that I never discussed the subject.
Use It Without an Agent First
The CLI made it possible to inspect retrieval before adding any skill integration:
1
2
3
4
5
# Commands from my Session Search checkout, not a public package installer.
./search.command search 'Why did I change the indexing schedule?'
./search.command search 'cache optimization' \
--context 'Current task: reduce memory use without changing output correctness'
./search.command session SESSION_ID --event-id EVENT_ID --generation GENERATION_ID
The returned generation pins follow-up reads to the same published catalog. If retention has retired that generation, the caller must search again rather than silently pretend it is still reading the old evidence.
Search initially spans projects instead of assuming that only the current repository can contain relevant history. Filters remain available when there is a reason to narrow the scope. Current code and constraints can be supplied as query context without silently turning them into a project restriction.
The service itself does not decide which question an agent should ask. In my integration, that reasoning belongs to Codex and the Recall workflow—not another LLM hidden inside Session Search.
Evaluate Retrieval Separately from Ingestion
The September 28 serving snapshot contained 630,057 text chunks across 21,593 catalog session entries, including internal source representations. These are scale measurements, not evidence of retrieval accuracy or a count of independent human conversations.
I started by reviewing memory-lookup cases and synthetic decision scenarios. I then tested a narrower question: could an agent reuse recorded settings without asking me to repeat them? Part 4 describes the controlled comparison and its limits. That result is not a general retrieval-accuracy score, and automatically drafted evaluation labels are not ground truth.
A model or ranker change should be compared on the same corpus snapshot where possible. Otherwise, a better result might come from newly imported evidence rather than from the replacement component.
For this use case, relevant questions include: did the system recover the right measurement, distinguish a proposal from an adopted decision, and notice when the old conditions no longer apply? A high cosine score alone cannot answer those questions.
What This Layer Gives Me
I now have a retrieval service that can change its model or storage backend while keeping the archive and caller contract intact. More importantly, it returns evidence that can be checked rather than asking the caller to trust a generated memory summary.
The remaining work is not only search quality. Even a sensible retrieval design can become expensive or fragile when it runs every day.
Previous: Building a Durable Archive · Next: Storage, Recovery, and Observability