Repository navigation
Description
Motivation
Uteke currently operates two retrieval systems independently:
- Semantic recall (
recall_hybrid) — vector similarity + FTS5, merged via RRF. Scoring is purely rank-based. - Graph traversal (
recall_related) — multi-hop BFS through typed edges. Returns results separately, not fused into recall scores.
This means the knowledge graph (#346) has zero influence on retrieval quality. A memory that is well-connected in the graph (referenced by 20 other memories, high salience) receives no boost over an isolated memory with similar embedding distance.
True Graph RAG means using graph structure to modify retrieval scoring — not just returning graph results separately. Research shows that graph-augmented retrieval improves P@5 by 15–31% over vector-only RAG.
What We Have Today
| Component | Location | Status |
|---|---|---|
| Typed auto-edges | edges.rs (938 LOC) |
✅ Live — memory_edges SQLite table |
| Multi-hop traversal | graph.rs (827 LOC) |
✅ Live — recall_related() with configurable depth |
| RRF hybrid scoring | operations.rs |
✅ Live — recall_rrf() with k=60 |
| Hot tier boost | operations.rs:237 |
✅ Live — +hot_boost for recently accessed memories |
| Edge count query | edges.rs |
✅ list_memory_edges() returns EdgeList with incoming/outgoing |
What's Missing
Graph signals (edge density, centrality, salience) never touch recall scoring.
Current Scoring Pipeline
// recall_hybrid() → recall_rrf()
// For Hybrid strategy:
fn recall_rrf(query, limit, tags_filter, namespace, min_score) -> Vec<SearchResult> {
// 1. Vector search → ranked results
// 2. FTS5 search → ranked results
// 3. RRF fusion: score = Σ 1/(k + rank + 1) for both channels
// 4. Normalize to 0..1
// 5. Sort by score, take top `limit`
// → Graph signals are NOT involved at any step
}
// recall() for Vector strategy:
fn recall(query, limit, tags_filter, namespace, min_score) -> Vec<SearchResult> {
// 1. Embed query (~50ms)
// 2. Search usearch index (cosine distance)
// 3. Convert to similarity score (0..1)
// 4. Post-filter: namespace, tags, min_score
// 5. Boost hot memories: score = (score + hot_boost).min(1.0) ← ONLY graph-adjacent signal
// → No edge density or centrality influence
}Proposal
Phase 1: Graph Signal Extraction (zero LLM)
Add a lightweight function that computes graph-based signals for a set of candidate memories. All signals are derived from existing memory_edges table — no new data, no LLM calls.
/// Graph signals computed per memory, all from existing `memory_edges` table.
#[derive(Debug, Clone, Default)]
pub struct GraphSignals {
/// Total edge count (incoming + outgoing). Well-connected = likely important.
pub edge_count: u32,
/// Unique neighbors count (deduplicated across edge types).
pub neighbor_count: u32,
/// Number of distinct edge types. High variety = hub node.
pub edge_type_diversity: u32,
/// Incoming edge count. Many references from others = authority.
pub incoming_count: u32,
/// Outgoing edge count. Many references to others = index node.
pub outgoing_count: u32,
}
/// Batch-compute graph signals for a list of memory IDs.
/// Single indexed query per signal type — O(n) in candidate count, not total memories.
fn compute_graph_signals(
conn: &Connection,
memory_ids: &[String],
) -> Result<HashMap<String, GraphSignals>, Error> {
// One query to fetch all relevant edges at once:
// SELECT source_id, target_id, edge_type
// FROM memory_edges
// WHERE source_id IN (candidates) OR target_id IN (candidates)
// Then aggregate in Rust — no N+1 queries.
}Phase 2: Reranking Function
Add a configurable reranker that fuses graph signals into existing recall scores.
/// Configuration for graph-augmented reranking.
#[derive(Debug, Clone)]
pub struct GraphRerankConfig {
/// Weight for edge density boost (0.0 = disabled, 0.1 = subtle, 0.3 = strong).
pub density_weight: f32,
/// Weight for incoming edge authority boost.
pub authority_weight: f32,
/// Whether to enable graph reranking at all (feature flag).
pub enabled: bool,
}
impl Default for GraphRerankConfig {
fn default() -> Self {
Self {
enabled: true,
density_weight: 0.1, // subtle by default
authority_weight: 0.1,
}
}
}
/// Rerank search results by fusing graph signals.
/// Preserves relative order of non-boosted results — only shifts graph-rich memories up.
fn rerank_with_graph(
results: Vec<SearchResult>,
graph_signals: &HashMap<String, GraphSignals>,
config: &GraphRerankConfig,
) -> Vec<SearchResult> {
if !config.enabled || graph_signals.is_empty() {
return results; // no-op when disabled
}
let mut reranked = results.into_iter().map(|mut sr| {
if let Some(signals) = graph_signals.get(&sr.memory.id) {
// Log-scaled density boost (prevents hub-dominance)
let density_boost = (signals.edge_count as f32).ln() / 10.0 * config.density_weight;
// Log-scaled authority boost
let authority_boost = (signals.incoming_count as f32).ln() / 10.0 * config.authority_weight;
sr.score = (sr.score + density_boost + authority_boost).min(1.0);
}
sr
}).collect::<Vec<_>>();
// Re-sort by new score, maintaining stable sort for equal scores
reranked.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
reranked
}Phase 3: Integration into Recall Pipeline
Modify recall_rrf() and recall() to apply reranking after initial scoring.
// In recall_rrf(), after RRF fusion and normalization:
let results = /* ... existing RRF logic ... */;
// NEW: Graph-augmented reranking
if self.graph_rerank_config.enabled {
let signals = compute_graph_signals(&self.store.conn(), &memory_ids)?;
results = rerank_with_graph(results, &signals, &self.graph_rerank_config);
}Phase 4: New Recall Strategy
Add Graph as a 4th RecallStrategy variant that combines everything:
pub enum RecallStrategy {
Hybrid, // vector + FTS5 (current default)
Vector, // vector only
Fts5, // FTS5 only
Graph, // NEW: hybrid + graph reranking (new default for v0.3.0?)
}CLI Integration
# New flag on recall command
uteke recall "how does auth work?" --strategy graph
# New config in uteke.toml
[recall]
default_strategy = "graph"
graph_density_weight = 0.1
graph_authority_weight = 0.1Edge Cases & Considerations
| Concern | Mitigation |
|---|---|
| Cold start — no edges yet | Graph boost is additive, not multiplicative. Zero edges = zero boost = no change. Existing scores untouched. |
| Hub dominance — popular memories always win | Log-scaled boost (ln(count)/10) saturates quickly. Going from 1→10 edges gives same boost as 100→1000. |
| Performance — extra DB query per recall | Single batch query fetches all edges for candidates at once. O(candidates × avg_edges) not O(total_memories). Expected: <5ms for typical limit=10. |
| Recall cache — cached results bypass reranking | Cache key includes strategy. Graph strategy has its own cache entries. Existing Hybrid cache unaffected. |
| Backward compatibility — existing users | Default strategy stays Hybrid. Graph is opt-in. Zero behavior change for existing installations. |
Dependencies
- feat: typed auto-edges — self-wiring knowledge graph on every remember() #346 (typed auto-edges) — ✅ CLOSED —
memory_edgestable exists - feat: backlink auto-generation — bidirectional links on memory references #350 (backlink auto-generation) — OPEN — would improve incoming edge accuracy
- feat: salience + recency dual-axis recall ranking #352 (salience + recency ranking) — OPEN — complementary, can be stacked
Acceptance Criteria
-
compute_graph_signals()— batch edge query, returnsHashMap<String, GraphSignals>for candidate IDs -
rerank_with_graph()— fuses density + authority signals intoSearchResult.score -
RecallStrategy::Graph— new variant that applies reranking after RRF fusion - CLI
--strategy graphflag works -
uteke.toml[recall]config section for weights and default strategy - Unit tests: reranking with zero edges (no-op), hub-dominance (log scaling), cache isolation
- Benchmarks: recall latency impact < 10ms for limit=10
- No regression: existing
Hybrid/Vector/Fts5strategies unchanged
Out of Scope
- Community detection / clustering (future issue)
- PageRank-style global centrality computation (expensive, needs background job — aligns with feat: dream cycle — automated local maintenance pipeline (lint → backlinks → dedup → orphans) #353 dream cycle)
- LLM-based edge extraction or reasoning chains
- Graph visualisation UI
References
- GraphRAG paper (Microsoft, 2024) — graph-based retrieval improves P@5 by 15-31%
- GBrain self-wiring graph — inspiration for feat: typed auto-edges — self-wiring knowledge graph on every remember() #346 auto-edges
- RAG Fusion paper — RRF as multi-query fusion method
Activity
feat: graph-augmented RAG reranking (codecoradev#378) (codecoradev#379)
feat: graph-augmented RAG reranking (#378) (#379)