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