Query-time relation traversal in search (one-hop graph expansion)
Summary
Basic Memory indexes relations (- relation_type [[Entity]]) as first-class searchable rows, but search_notes never follows them at query time. A note that is highly relevant to a query but doesn't lexically/semantically match the query text — yet is one relation-hop from a note that does match — is invisible to search today. This proposes an optional one-hop relation expansion in the search path that recovers exactly those notes.
The graph-traversal primitive already exists: ContextService.find_related() (src/basic_memory/services/context_service.py:299) walks the relation graph via a recursive CTE (it powers build_context). This feature would reuse it from the search service rather than build traversal anew.
Motivation / evidence
Measured in the benchmark harness (basic-memory-benchmarks) on LoCoMo multi_hop (63 questions, 272-doc shared corpus, hybrid search post-#994):
- Of the gold-evidence notes that hybrid search misses in its top-K, a large fraction are one relation-hop from a note that was retrieved.
- Naive "follow any shared relation" floods results — hub entities (a person who appears in 40+ notes) pull in ~40 notes/query at ~1% precision. Unusable as-is.
- Specificity-weighted traversal (down-weight/skip high-degree targets, rank candidates by count of rare shared entities, cap fan-out) recovers ~38% of the true misses at ~+4 added notes/query — i.e. ~+4 pts recall@5 on this slice, and it is additive (it recovers notes lexical + vector retrieval miss entirely).
- The payoff scales with entity quality: with canonical, deduped entity names the usable recovery roughly doubled vs naive per-note extraction (naive expansion dropped from ~42 to ~13 notes/query). Traversal is only as good as the relation graph it walks.
So this is a real, additive retrieval lever, distinct from ranking tweaks.
Proposed shape (prototype)
- Refactor the CTE query builders out of
ContextService(_build_sqlite_query:590,_build_postgres_query:432) into a shared helper bothContextServiceand the search service can call (one hop, seeded by a set of entity ids). SearchService.search()(src/basic_memory/services/search_service.py:275) gains an optionalexpand_relationspath: after the base hybrid result set, take the top-N entity/observation hits, traverse one hop to their related entities, and merge the new entities in as additional results.- Specificity weighting (the part that makes it usable, not just the traversal): down-weight or skip high-degree relation targets, score expanded candidates by the number of rare shared entities, and cap the number of expanded notes added per query.
- Merge + rerank: dedup expanded hits against direct hits (key on
(type, id), matching the existing fusion insearch_repository_base.py:_search_hybrid), and score them below strong direct matches so traversal never displaces a good lexical/vector hit — it only fills the tail. - Result assembly: expanded rows flow through the existing
to_search_results()hydration (src/basic_memory/api/v2/utils.py:203);SearchIndexRowalready carriesfrom_id/to_id/to_name/relation_type(search_index_row.py:37-40), so no schema change is required for resolved relations.
What "feature complete" needs
- [ ] Unresolved relations, not just resolved
to_id. Auto-extracted and conversational notes frequently have unresolved[[wikilinks]](to_idNULL,to_nameset). Traversal should also connect notes that share a rareto_name, or the feature won't fire on exactly the corpora that need it most. - [ ] Specificity weighting / hub suppression as a first-class part of the algorithm (inverse-frequency on entity degree, fan-out cap). Without it the feature is net-negative on precision.
- [ ] Reranking so expanded hits are ordered relative to direct hits — preserve precision@k / MRR on queries that don't need expansion (most of them).
- [ ] Depth = 1 to start, with a configurable cap; guard against fan-out blow-up on dense graphs.
- [ ] Default-behavior decision (open question). We prefer not to ship behind a flag. Options: (a) on by default once it provably never regresses recall/MRR, (b) a
search_type/parameter onsearch_notes. Recommend landing it parameterized + off for validation, then flipping the default once the benchmark shows no regression — but flagging this for discussion given the no-flag preference. - [ ] Performance: one extra CTE per search; measure added latency, keep it bounded by the fan-out cap.
- [ ] Tests: unit (traversal merge/dedup/specificity-weighting/rerank) alongside
tests/repository/test_search_repository.py; integration intest-int/mcp/test_search_integration.py(write notes linked by a rare shared entity, assert the non-matching related note surfaces; assert a hub-linked note does not flood results). - [ ] Benchmark gate: re-run the LoCoMo
multi_hoprecall A/B in basic-memory-benchmarks to confirm the recall lift holds end-to-end with no MRR regression before defaulting on.
Notes / caveats
- This is a retrieval improvement (recall), not an end-to-end QA improvement: in the harness, a fixed downstream answerer model means recall gains don't fully convert to answered-correctly. The value is better search results for an agent/user, measured by recall/MRR.
- The lever's ceiling depends on the quality of the relation graph (canonical entities). It pairs naturally with any future entity-resolution/canonicalization at ingest.
Filed from search/retrieval benchmarking work; happy to drive the prototype.
Claude finished @groksrc's task in 2m 7s —— View job
Issue Triage
- [x] Gather context and read the issue
- [x] Analyze issue type, priority, component, and complexity
- [x] Check for duplicate issues
- [x] Read relevant source files to understand current implementation
- [x] Add labels to the issue
- [x] Post triage analysis
Analysis
Type: Enhancement / Feature Request — adds a new retrieval capability (one-hop relation expansion) to search_notes.
No duplicate found. This is closely related to the LoCoMo benchmark series by the same author, but is distinct from the existing open issues:
- #950 — Add a rerank stage (ranking failures, recall@10 → recall@5 conversion)
- #951 — Entity-aware ranking boost (cross-conversation entity confusion)
- #1001 (this issue) — Addresses true top-10 misses via graph traversal (additive to the above two)
All three are complementary search improvements. This one targets the recall ceiling that reranking cannot address, since the gold document never enters the candidate set at all.
Priority: Medium. Meaningful recall improvement (~+4 pts recall@5 on the hard multi-hop slice), but not a correctness or data-integrity issue. The benchmark evidence is solid and the failure mode is well-understood.
Component: Search service + search repository (both SQLite and Postgres paths), MCP search_notes tool. Key files:
src/basic_memory/services/search_service.py:275—SearchService.search()is the integration pointsrc/basic_memory/services/context_service.py:299,432,590—find_related()and the CTE builders to refactor into shared helperssrc/basic_memory/repository/search_repository_base.py— fusion/dedup logic to extend
Complexity: Complex. This requires:
- Extracting the recursive CTE builders from
ContextServiceinto shared helpers (refactor) - A specificity-weighting / hub-suppression algorithm (new algorithmic work)
- Score-preserving merge + rerank that never displaces strong direct hits
- Dual-engine support (SQLite CTE at
:590, Postgres LATERAL CTE at:432) - Handling unresolved wikilinks (
to_id NULL,to_nameset) as a first-class case - Unit tests (traversal, dedup, specificity weighting, rerank), integration tests (hub suppression, rare-entity recall lift)
- Benchmark gate before flipping the default on
Labels added: enhancement (only this label currently exists in the repo for the relevant categories)
Implementation Notes
The issue proposal is well-scoped with precise code references. A few things worth noting before implementation begins:
-
The traversal primitive is already there.
ContextService.find_related()(context_service.py:299) does the recursive CTE walk. The main work is refactoring the CTE builders into a shared module so search can reuse them without pulling in all ofContextService. -
Hub suppression is non-negotiable for precision. The benchmark data is clear: naive traversal drops precision to ~1% on hub entities (40+ notes per entity). The specificity-weighting (inverse-degree weighting) must be part of the initial implementation, not a follow-up.
-
Unresolved wikilinks (
to_id NULL) are critical for real-world corpora. Auto-extracted and conversational notes frequently have unresolved[[wikilinks]]. The traversal needs to join onto_nameas well asto_idto fire on the corpora that need it most. -
Parameterized first, default later (per the issue's own recommendation): ship it behind a parameter on
search_notes, validate on the benchmark that it never regresses MRR on the non-multi-hop slices, then flip the default. -
Fan-out cap is required — must be enforced before the CTE returns to bound worst-case query latency on dense graphs.
This feels like an important step from “searching notes” toward actual vault recall.
For a personal memory vault, the useful memory is often not the note that lexically matches the query. It is the adjacent note that shares a person, decision, project, constraint, or unresolved thread. Pure lexical/vector retrieval misses exactly the kind of associative recall humans expect from a long-lived vault.
I’d frame the retrieval stack as three generated views over the authored markdown source:
lexical view = words and exact terms
semantic view = approximate meaning
relation view = entities, links, decisions, projects, people, constraints
One-hop relation expansion is valuable because it composes the third view with the first two instead of treating the graph as only a context-building tool after retrieval.
The specificity weighting is the critical piece. In a personal vault, high-degree entities like the user’s own name, “AI”, or a company/project root can become recall hubs that flood everything. Rare shared edges are much more meaningful:
rare relation + weak semantic match -> good recall candidate
hub relation only -> probably noise
explicit authored link -> stronger than auto-extracted co-mention
I’d also distinguish relation provenance:
- authored wikilink
- extracted entity
- inferred relation
- generated backlink
That lets the search layer weight authored structure higher than auto-extracted structure, which matters for user-owned memory. The user’s deliberate links should carry more authority than accidental co-occurrence.
I’ve been exploring a similar Personal AI OS / Memory Vault direction: markdown remains the source of truth, while lexical/vector/graph recall are generated views that should be rebuildable, inspectable, and provenance-aware.
Related public projects:
- https://github.com/hegu-1/personal-memory-vault-starter
- https://github.com/hegu-1/personal-ai-os
This is not something I want to support with our search as it is now. We can explore using milvus later or when postgres 19 ships with graph query.