Skip to main content

velesdb_memory/
fused_recall.rs

1//! [`MemoryService::recall_fused`]: vector recall combined with the graph
2//! reach `why()` already walks, re-ranked by [`crate::fusion::fuse`]. Split
3//! out of `service.rs` to keep that file under the crate's NLOC budget; a
4//! child module of `service`, so it freely uses `MemoryService`'s private
5//! fields and methods (`traverse`, `search`, `HUB_FIELD`, …).
6
7use std::collections::HashMap;
8
9use serde_json::Value;
10
11use super::{
12    reject_reserved_keys, strip_reserved_keys, MemoryService, Metadata, HUB_FIELD,
13    MENTIONS_RELATION,
14};
15use crate::embedder::Embedder;
16use crate::error::MemoryError;
17use crate::fusion::{self, Candidate};
18use crate::model::{FusionOptions, MemoryEdge, MemoryNode, Recollection};
19use crate::rerank::Reranker;
20use crate::storage::MemoryStore;
21
22impl<E: Embedder, S: MemoryStore> MemoryService<E, S> {
23    /// Fused recall: like [`Self::recall`], but also walks the graph from the
24    /// query's top vector hit and folds any fact it reaches (hop ≥ 1) into the
25    /// ranking, scored by `opts.graph_boost · graph_weight` on top of its
26    /// normalised vector similarity. A fact the graph reaches never displaces
27    /// a strong vector hit unless the boosted score genuinely outranks it; a
28    /// fact the vector pool ranked low (or missed) can still surface if the
29    /// graph connects it. This is the tri-engine ranking measured on
30    /// HotpotQA/TimeQA/LoCoMo (`examples/multihop`, `examples/timeqa`,
31    /// `examples/locomo`) — [`Self::recall`] stays pure-vector and unchanged,
32    /// so existing callers see no behavior shift.
33    ///
34    /// The graph reach requires a wired graph to find anything: it walks
35    /// edges from [`Self::relate`] or the entity hubs
36    /// [`Self::remember_extracted`] auto-wires. Entity hubs themselves are
37    /// never returned, exactly like [`Self::recall`].
38    ///
39    /// # Errors
40    /// Returns [`MemoryError`] if embedding, vector search, or graph
41    /// traversal fails.
42    pub fn recall_fused(
43        &self,
44        query: &str,
45        k: usize,
46        filter: Option<&Metadata>,
47        opts: FusionOptions,
48    ) -> Result<Vec<Recollection>, MemoryError> {
49        let query = query.trim();
50        if query.is_empty() || k == 0 {
51            return Ok(Vec::new());
52        }
53        let opts = opts.sanitized();
54        reject_reserved_keys(filter)?;
55        let embedding = self.embedder.embed(query)?;
56        let pool = self.fused_pool(&embedding, pool_depth(k, opts), filter)?;
57        let reached = self.graph_reached(&embedding, filter, opts.hops)?;
58        Ok(fusion::fuse(pool, &reached, k, opts.graph_boost))
59    }
60
61    /// [`Self::recall_fused`] with the per-candidate score ventilation kept
62    /// (normalised vector term, graph weight, fused score) — consumed by the
63    /// context compiler's memory bridge, whose provenance records an
64    /// explainable `relevance ∈ [0, 1]` per pulled memory. Same pipeline,
65    /// same ordering, same numbers as [`Self::recall_fused`]; only the
66    /// breakdown is kept instead of dropped.
67    ///
68    /// # Errors
69    /// Returns [`MemoryError`] if embedding, vector search, or graph
70    /// traversal fails.
71    #[cfg(feature = "context")]
72    pub(crate) fn recall_fused_scored(
73        &self,
74        query: &str,
75        k: usize,
76        filter: Option<&Metadata>,
77        opts: FusionOptions,
78    ) -> Result<Vec<fusion::ScoredCandidate>, MemoryError> {
79        let query = query.trim();
80        if query.is_empty() || k == 0 {
81            return Ok(Vec::new());
82        }
83        let opts = opts.sanitized();
84        reject_reserved_keys(filter)?;
85        let embedding = self.embedder.embed(query)?;
86        let pool = self.fused_pool(&embedding, pool_depth(k, opts), filter)?;
87        let reached = self.graph_reached(&embedding, filter, opts.hops)?;
88        Ok(fusion::fuse_scored(pool, &reached, k, opts.graph_boost))
89    }
90
91    /// [`Self::recall_fused`] paired with the dated-context rendering of its
92    /// results: returns the recalled facts and the
93    /// [`DatedContext`](crate::DatedContext) built from their `date_field`
94    /// metadata (see [`format_dated_context`](crate::format_dated_context)).
95    /// Every binding that exposes a "dated recall" (the MCP `recall_fused`
96    /// tool's `date_field`, Node/WASM `recallFusedDated`) calls this, so the
97    /// "recall then format" pairing lives in exactly one place and can't drift
98    /// between surfaces.
99    ///
100    /// # Errors
101    /// Returns [`MemoryError`] if the underlying [`Self::recall_fused`] fails.
102    pub fn recall_fused_dated(
103        &self,
104        query: &str,
105        k: usize,
106        filter: Option<&Metadata>,
107        opts: FusionOptions,
108        date_field: &str,
109    ) -> Result<(Vec<Recollection>, crate::DatedContext), MemoryError> {
110        let hits = self.recall_fused(query, k, filter, opts)?;
111        let ctx = crate::format_dated_context(&hits, date_field);
112        Ok((hits, ctx))
113    }
114
115    /// Like [`Self::recall_fused`], but hands the FULL fused-ranked candidate
116    /// pool (before the final `k` cutoff) to `reranker` for a second-stage
117    /// re-score, then truncates to `k`. Closes the ranking-miss gap the
118    /// `LoCoMo` ceiling diagnostic found: a relevant fact can be IN the pool
119    /// (recall@64 ≈ 89% on multi-hop) yet outranked out of a tight `k`
120    /// (recall@8 ≈ 50%) — a reranker recovers it without widening `k` itself.
121    ///
122    /// No built-in reranker ships: bring your own (cross-encoder, LLM judge,
123    /// …) via [`Reranker`]. Never call this as a default — a reranker can
124    /// also *hurt* out-of-distribution conversational queries (measured on
125    /// `LoCoMo`), so it is opt-in, one call at a time.
126    ///
127    /// # Errors
128    /// Returns [`MemoryError`] if embedding, vector search, graph traversal,
129    /// or `reranker` itself fails.
130    pub fn recall_fused_reranked<R: Reranker>(
131        &self,
132        query: &str,
133        k: usize,
134        filter: Option<&Metadata>,
135        opts: FusionOptions,
136        reranker: &R,
137    ) -> Result<Vec<Recollection>, MemoryError> {
138        let query = query.trim();
139        if query.is_empty() || k == 0 {
140            return Ok(Vec::new());
141        }
142        let opts = opts.sanitized();
143        reject_reserved_keys(filter)?;
144        let embedding = self.embedder.embed(query)?;
145        let depth = pool_depth(k, opts);
146        let pool = self.fused_pool(&embedding, depth, filter)?;
147        let reached = self.graph_reached(&embedding, filter, opts.hops)?;
148        let fused = fusion::fuse(pool, &reached, depth, opts.graph_boost);
149        let ranked = reranker.rerank(query, fused)?;
150        Ok(ranked.into_iter().take(k).collect())
151    }
152
153    /// The oversampled vector pool [`Self::recall_fused`] re-ranks. One
154    /// batched metadata lookup covers the whole pool (up to hundreds of ids
155    /// at the deepest `pool_depth`), not one round trip per hit.
156    fn fused_pool(
157        &self,
158        embedding: &[f32],
159        depth: usize,
160        filter: Option<&Metadata>,
161    ) -> Result<Vec<Candidate>, MemoryError> {
162        let hits = self.search(embedding, depth, filter)?;
163        let ids: Vec<u64> = hits.iter().map(|(id, _, _)| *id).collect();
164        let metadata = self.recall_metadata_batch(&ids)?;
165        Ok(hits
166            .into_iter()
167            .zip(metadata)
168            .map(|((id, score, content), metadata)| Candidate {
169                recollection: Recollection {
170                    id,
171                    score,
172                    content,
173                    metadata,
174                },
175                vector_score: f64::from(score),
176                graph_weight: 0.0,
177            })
178            .collect())
179    }
180
181    /// The caller-supplied metadata for every id in `ids` (reserved system
182    /// keys excluded, `None` per-id when it carries none), in the same
183    /// order — one batched storage round trip, so a `k`- or pool-sized
184    /// result set (here, and in [`MemoryService::recall`]) costs one
185    /// metadata lookup, not `k`/`pool_size` of them.
186    pub(crate) fn recall_metadata_batch(
187        &self,
188        ids: &[u64],
189    ) -> Result<Vec<Option<Metadata>>, MemoryError> {
190        Ok(self
191            .store
192            .get_metadata_batch(ids)?
193            .into_iter()
194            .map(strip_reserved_keys)
195            .collect())
196    }
197
198    /// Facts the graph reaches (hop ≥ 1) from the query's top vector seed,
199    /// entity hubs excluded, each weighted by [`Self::reach_weight`]: a link
200    /// through a rare, specific entity hub promotes harder than one through a
201    /// generic mega-hub whose connections carry little signal — the idf lever
202    /// validated on `HotpotQA` (+5.0pp both-facts-complete) and `LoCoMo` (turns
203    /// the graph net-positive on multi-hop, no regression elsewhere).
204    ///
205    /// `filter` is re-checked against every reached fact's own metadata, not
206    /// just the seed: the graph walk is otherwise filter-blind, so a fact
207    /// outside the caller's scope (e.g. a different tenant/project) could
208    /// leak in just by being graph-connected to the seed.
209    fn graph_reached(
210        &self,
211        embedding: &[f32],
212        filter: Option<&Metadata>,
213        hops: usize,
214    ) -> Result<Vec<Candidate>, MemoryError> {
215        let seeds = self.search(embedding, 1, filter)?;
216        let Some((seed_id, _score, seed_content)) = seeds.into_iter().next() else {
217            return Ok(Vec::new());
218        };
219        let explanation = self.traverse(seed_id, seed_content, hops)?;
220        let nodes: Vec<&MemoryNode> = explanation.nodes.iter().filter(|n| n.hop != 0).collect();
221        let ids: Vec<u64> = nodes.iter().map(|n| n.id).collect();
222        let raw_payloads = self.store.get_metadata_batch(&ids)?;
223
224        let mut idf_cache: HashMap<u64, f64> = HashMap::new();
225        let mut reached = Vec::new();
226        for (node, raw) in nodes.into_iter().zip(raw_payloads) {
227            if let Some(candidate) =
228                self.reached_candidate(node, raw, &explanation.edges, filter, &mut idf_cache)?
229            {
230                reached.push(candidate);
231            }
232        }
233        Ok(reached)
234    }
235
236    /// The graph-reached candidate for `node` given its already-fetched raw
237    /// payload `raw`, or `None` when it's an entity hub (internal
238    /// scaffolding, never a caller fact) or outside `filter`'s scope — split
239    /// out of [`Self::graph_reached`] to keep that loop's complexity within
240    /// budget. `raw` is fetched once, batched across the whole traversal, by
241    /// the caller — not per node — and serves both the hub check and the
242    /// returned candidate's metadata: the hub flag lives under the reserved
243    /// `_veles_hub` key, so it must be checked before `strip_reserved_keys`
244    /// removes it for the caller-facing metadata. `idf_cache` memoizes
245    /// [`Self::entity_idf`] per hub across the whole traversal (siblings
246    /// under the same hub would otherwise recompute an identical value once
247    /// per fact).
248    fn reached_candidate(
249        &self,
250        node: &MemoryNode,
251        raw: Option<Metadata>,
252        edges: &[MemoryEdge],
253        filter: Option<&Metadata>,
254        idf_cache: &mut HashMap<u64, f64>,
255    ) -> Result<Option<Candidate>, MemoryError> {
256        if raw
257            .as_ref()
258            .is_some_and(|meta| meta.get(HUB_FIELD) == Some(&Value::Bool(true)))
259        {
260            return Ok(None);
261        }
262        let metadata = strip_reserved_keys(raw);
263        if !matches_filter(metadata.as_ref(), filter) {
264            return Ok(None);
265        }
266        let weight = self.reach_weight(node.id, edges, idf_cache)?;
267        Ok(Some(Candidate {
268            recollection: Recollection {
269                id: node.id,
270                score: 0.0,
271                content: node.content.clone(),
272                metadata,
273            },
274            vector_score: 0.0,
275            graph_weight: weight,
276        }))
277    }
278
279    /// The strength of the link(s) that reached `fact_id`: the maximum
280    /// entity-idf ([`Self::entity_idf`]) over every hub with a `mentions`
281    /// edge into it, or a flat `1.0` when it was reached through a direct
282    /// (non-hub) [`Self::relate`] edge instead — idf has nothing to weight
283    /// there, so the original flat signal is kept.
284    fn reach_weight(
285        &self,
286        fact_id: u64,
287        edges: &[MemoryEdge],
288        idf_cache: &mut HashMap<u64, f64>,
289    ) -> Result<f64, MemoryError> {
290        let mut weight: Option<f64> = None;
291        for edge in edges {
292            if edge.to == fact_id && edge.relation == MENTIONS_RELATION {
293                let idf = self.cached_entity_idf(edge.from, idf_cache)?;
294                weight = Some(weight.map_or(idf, |w: f64| w.max(idf)));
295            }
296        }
297        Ok(weight.unwrap_or(1.0))
298    }
299
300    /// [`Self::entity_idf`], memoized in `cache` for the lifetime of one
301    /// [`Self::graph_reached`] call — sibling facts under the same hub would
302    /// otherwise each pay a fresh `relations`+`count` store round trip for an
303    /// identical value.
304    fn cached_entity_idf(
305        &self,
306        hub_id: u64,
307        cache: &mut HashMap<u64, f64>,
308    ) -> Result<f64, MemoryError> {
309        if let Some(&idf) = cache.get(&hub_id) {
310            return Ok(idf);
311        }
312        let idf = self.entity_idf(hub_id)?;
313        cache.insert(hub_id, idf);
314        Ok(idf)
315    }
316
317    /// Normalised inverse document frequency of hub `hub_id`, in `[0, 1]`:
318    /// `1` when it links a single fact (maximally specific), trending to `0`
319    /// as it links ever more (a generic mega-hub whose links carry little
320    /// answer signal). Mirrors the `LoCoMo` harness formula
321    /// (`examples/locomo/ingest.rs`), using the store's total memory count
322    /// (facts + hubs) as a corpus-size proxy.
323    fn entity_idf(&self, hub_id: u64) -> Result<f64, MemoryError> {
324        let degree = self.store.relations(hub_id)?.len();
325        let n = self.store.count();
326        if degree == 0 || n <= 1 {
327            return Ok(0.0);
328        }
329        #[allow(clippy::cast_precision_loss)] // corpus/degree sizes are far below f64's exact range
330        let (n, d) = (n as f64, degree as f64);
331        Ok((n / d).ln() / n.ln())
332    }
333}
334
335/// True when `filter` is absent, or every key in it matches `metadata`
336/// exactly — the same "all filter keys must match" semantics
337/// [`MemoryService::search`]'s vector-side filtering applies, now also
338/// enforced on graph-reached facts so a caller-scoped `recall_fused` can't
339/// leak a fact outside that scope just because it's graph-connected to the
340/// seed.
341fn matches_filter(metadata: Option<&Metadata>, filter: Option<&Metadata>) -> bool {
342    let Some(filter) = filter else {
343        return true;
344    };
345    // Mirrors velesdb-core's `payload_matches`: an empty (not absent) filter
346    // matches everything, including a metadata-less fact — `Some({})` from a
347    // caller (e.g. a JS `recallFused(q, k, {})`) must behave exactly like
348    // `None`, not like "reject anything without metadata".
349    if filter.is_empty() {
350        return true;
351    }
352    let Some(metadata) = metadata else {
353        return false;
354    };
355    filter.iter().all(|(k, v)| metadata.get(k) == Some(v))
356}
357
358/// The oversampled candidate pool depth for a `k`-sized fused recall:
359/// `opts.pool` if the caller set one (floored at 1), else the proven default
360/// ([`fusion::pool_size`]) — either way, capped at
361/// [`crate::limits::MAX_RECALL_LIMIT`], the same `DoS` ceiling `k`/`hops`
362/// carry. Both bounds live here, not at each binding's FFI boundary:
363/// - the floor of 1 stops an explicit `pool` of 0 (a binding now exposes the
364///   knob: `options={"pool": 0}` in Python) from oversampling *zero* candidates
365///   and returning nothing. A caller can still deliberately narrow the pool
366///   below the default (e.g. `pool: 1` to admit only the top vector hit — the
367///   documented behavior fusion's tests pin); the floor only rules out the
368///   degenerate empty-set case, it does not force a minimum recall depth.
369/// - the cap bounds the default too: `k.saturating_mul(8)` exceeds the limit
370///   well before `k` itself does, so even a caller who never touches `pool` is
371///   bounded.
372fn pool_depth(k: usize, opts: FusionOptions) -> usize {
373    let depth = opts.pool.map_or_else(|| fusion::pool_size(k), |p| p.max(1));
374    crate::limits::clamp_recall_limit(depth)
375}