1use crate::cli::MemoryType;
4use crate::errors::AppError;
5use crate::graph::traverse_from_memories_with_hops;
6use crate::i18n::errors_msg;
7use crate::output::{self, JsonOutputFormat, RecallItem, RecallResponse};
8use crate::paths::AppPaths;
9use crate::storage::connection::open_ro;
10use crate::storage::entities;
11use crate::storage::memories;
12
13#[derive(clap::Args)]
20#[command(after_long_help = "EXAMPLES:\n \
21 # Semantic search for top 5 matches\n \
22 sqlite-graphrag recall \"authentication design\" --k 5\n\n \
23 # Disable automatic graph expansion\n \
24 sqlite-graphrag recall \"JWT tokens\" --k 3 --no-graph\n\n \
25 # Limit graph traversal depth and minimum edge weight\n \
26 sqlite-graphrag recall \"auth\" --k 5 --max-hops 2 --min-weight 0.3\n\n \
27 # Filter by memory type\n \
28 sqlite-graphrag recall \"deployment\" --type decision --k 10\n\n \
29 # Cap results by distance threshold\n \
30 sqlite-graphrag recall \"API design\" --k 5 --max-distance 0.8\n\n \
31NOTES:\n \
32 When --no-graph is active, graph traversal is skipped and every result has\n \
33 source=\"direct\". The source field is therefore redundant with --no-graph and\n \
34 may be ignored by callers in that mode.")]
35pub struct RecallArgs {
36 #[arg(
37 allow_hyphen_values = true,
38 help = "Search query string (semantic vector search via sqlite-vec)"
39 )]
40 pub query: String,
41 #[arg(short = 'k', long, aliases = ["limit", "top-k"], default_value = "10", value_parser = crate::parsers::parse_k_range)]
49 pub k: usize,
50 #[arg(long, value_enum)]
54 pub r#type: Option<MemoryType>,
55 #[arg(long)]
56 pub namespace: Option<String>,
57 #[arg(long)]
58 pub no_graph: bool,
59 #[arg(long)]
65 pub precise: bool,
66 #[arg(long, default_value = "2")]
67 pub max_hops: u32,
68 #[arg(long, default_value = "0.3")]
69 pub min_weight: f64,
70 #[arg(long, value_name = "N")]
76 pub max_graph_results: Option<usize>,
77 #[arg(long, alias = "min-distance", default_value = "1.0")]
82 pub max_distance: f32,
83 #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
84 pub format: JsonOutputFormat,
85 #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
86 pub db: Option<String>,
87 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
89 pub json: bool,
90 #[arg(long, conflicts_with = "namespace")]
95 pub all_namespaces: bool,
96 #[arg(
100 long,
101 help = "Skip live query embedding; use FTS5 BM25 + LIKE prefix only"
102 )]
103 pub fallback_fts_only: bool,
104}
105
106#[tracing::instrument(skip_all, level = "debug", name = "recall")]
107pub fn run(args: RecallArgs, llm_backend: crate::cli::LlmBackendChoice) -> Result<(), AppError> {
108 let start = std::time::Instant::now();
109 let _ = args.format;
110 tracing::debug!(target: "recall", query = %args.query, k = args.k, "searching");
111
112 if args.no_graph {
114 if args.max_hops != 2 {
115 return Err(AppError::Validation(
116 "--max-hops has no effect with --no-graph; remove one".to_string(),
117 ));
118 }
119 if (args.min_weight - 0.3).abs() > f64::EPSILON {
120 return Err(AppError::Validation(
121 "--min-weight has no effect with --no-graph; remove one".to_string(),
122 ));
123 }
124 }
125
126 if args.query.trim().is_empty() {
127 return Err(AppError::Validation(crate::i18n::validation::empty_query()));
128 }
129 let namespaces: Vec<String> = if args.all_namespaces {
133 Vec::new()
134 } else {
135 vec![crate::namespace::resolve_namespace(
136 args.namespace.as_deref(),
137 )?]
138 };
139 let namespace_for_graph = namespaces
141 .first()
142 .cloned()
143 .unwrap_or_else(|| "global".to_string());
144 let paths = AppPaths::resolve(args.db.as_deref())?;
145
146 crate::storage::connection::ensure_db_ready(&paths)?;
147
148 output::emit_progress_i18n(
149 "Computing query embedding...",
150 "Calculando embedding da consulta...",
151 );
152 let conn = open_ro(&paths.db)?;
153 let (embedding, vec_degraded, vec_error) = if args.fallback_fts_only {
159 (None, true, Some("fallback_fts_only requested".to_string()))
160 } else {
161 match crate::embedder::try_embed_query_with_choice(
163 &paths.models,
164 &args.query,
165 Some(llm_backend),
166 ) {
167 Ok(v) => (Some(v), false, None),
168 Err(reason) => {
169 let msg = reason.to_string();
170 tracing::warn!(target: "recall", fallback_reason = %msg, "live embedding failed; falling back to FTS5");
171 (None, true, Some(msg))
172 }
173 }
174 };
175
176 let memory_type_str = args.r#type.map(|t| t.as_str());
177 let effective_k = if args.precise { 100_000 } else { args.k };
180
181 let (direct_matches, memory_ids): (Vec<RecallItem>, Vec<i64>) =
186 if let Some(emb) = embedding.as_ref() {
187 let knn_results =
188 memories::knn_search(&conn, emb, &namespaces, memory_type_str, effective_k)?;
189 let mut items: Vec<RecallItem> = Vec::with_capacity(knn_results.len());
190 let mut memory_ids: Vec<i64> = Vec::with_capacity(knn_results.len());
191 for (memory_id, distance) in knn_results {
192 let row = {
193 let mut stmt = conn.prepare_cached(
194 "SELECT id, namespace, name, type, description, body, body_hash,
195 session_id, source, metadata, created_at, updated_at
196 FROM memories WHERE id=?1 AND deleted_at IS NULL",
197 )?;
198 stmt.query_row(rusqlite::params![memory_id], |r| {
199 Ok(memories::MemoryRow {
200 id: r.get(0)?,
201 namespace: r.get(1)?,
202 name: r.get(2)?,
203 memory_type: r.get(3)?,
204 description: r.get(4)?,
205 body: r.get(5)?,
206 body_hash: r.get(6)?,
207 session_id: r.get(7)?,
208 source: r.get(8)?,
209 metadata: r.get(9)?,
210 created_at: r.get(10)?,
211 updated_at: r.get(11)?,
212 deleted_at: None,
213 })
214 })
215 .ok()
216 };
217 if let Some(row) = row {
218 let snippet: String = row.body.chars().take(300).collect();
219 items.push(RecallItem {
220 memory_id: row.id,
221 name: row.name,
222 namespace: row.namespace,
223 memory_type: row.memory_type,
224 description: row.description,
225 snippet,
226 distance,
227 score: RecallItem::score_from_distance(distance),
228 source: "direct".to_string(),
229 graph_depth: None,
230 });
231 memory_ids.push(memory_id);
232 }
233 }
234 (items, memory_ids)
235 } else {
236 let fts_rows = memories::fts_search(
242 &conn,
243 &args.query,
244 &namespace_for_graph,
245 memory_type_str,
246 effective_k,
247 )?;
248 let mut items: Vec<RecallItem> = Vec::with_capacity(fts_rows.len());
249 for (rank, row) in fts_rows.into_iter().enumerate() {
250 let dist = 1.0 - 1.0 / (rank as f32 + 1.0);
251 let snippet: String = row.body.chars().take(300).collect();
252 items.push(RecallItem {
253 memory_id: row.id,
254 name: row.name,
255 namespace: row.namespace,
256 memory_type: row.memory_type,
257 description: row.description,
258 snippet,
259 distance: dist,
260 score: RecallItem::score_from_distance(dist),
261 source: "fts_fallback".to_string(),
262 graph_depth: None,
263 });
264 }
265 (items, Vec::new())
266 };
267
268 let mut graph_matches = Vec::with_capacity(8);
269 if let Some(emb) = (!args.no_graph).then_some(()).and(embedding.as_ref()) {
270 let entity_knn = entities::knn_search(&conn, emb, &namespace_for_graph, 5)?;
271 let entity_ids: Vec<i64> = entity_knn.iter().map(|(id, _)| *id).collect();
272
273 let all_seed_ids: Vec<i64> = memory_ids
274 .iter()
275 .chain(entity_ids.iter())
276 .copied()
277 .collect();
278
279 if !all_seed_ids.is_empty() {
280 let graph_memory_ids = traverse_from_memories_with_hops(
281 &conn,
282 &all_seed_ids,
283 &namespace_for_graph,
284 args.min_weight,
285 args.max_hops,
286 )?;
287
288 for (graph_mem_id, hop) in graph_memory_ids {
289 if let Some(cap) = args.max_graph_results {
292 if graph_matches.len() >= cap {
293 break;
294 }
295 }
296 let row = {
297 let mut stmt = conn.prepare_cached(
298 "SELECT id, namespace, name, type, description, body, body_hash,
299 session_id, source, metadata, created_at, updated_at
300 FROM memories WHERE id=?1 AND deleted_at IS NULL",
301 )?;
302 stmt.query_row(rusqlite::params![graph_mem_id], |r| {
303 Ok(memories::MemoryRow {
304 id: r.get(0)?,
305 namespace: r.get(1)?,
306 name: r.get(2)?,
307 memory_type: r.get(3)?,
308 description: r.get(4)?,
309 body: r.get(5)?,
310 body_hash: r.get(6)?,
311 session_id: r.get(7)?,
312 source: r.get(8)?,
313 metadata: r.get(9)?,
314 created_at: r.get(10)?,
315 updated_at: r.get(11)?,
316 deleted_at: None,
317 })
318 })
319 .ok()
320 };
321 if let Some(row) = row {
322 let snippet: String = row.body.chars().take(300).collect();
323 let graph_distance = 1.0 - 1.0 / (hop as f32 + 1.0);
324 graph_matches.push(RecallItem {
325 memory_id: row.id,
326 name: row.name,
327 namespace: row.namespace,
328 memory_type: row.memory_type,
329 description: row.description,
330 snippet,
331 distance: graph_distance,
332 score: RecallItem::score_from_distance(graph_distance),
333 source: "graph".to_string(),
334 graph_depth: Some(hop),
335 });
336 }
337 }
338 }
339 }
340
341 if args.max_distance < 1.0 && !vec_degraded {
343 let has_relevant = direct_matches
344 .iter()
345 .any(|item| item.distance <= args.max_distance);
346 if !has_relevant {
347 return Err(AppError::NotFound(errors_msg::no_recall_results(
348 args.max_distance,
349 &args.query,
350 &namespace_for_graph,
351 )));
352 }
353 }
354
355 let results: Vec<RecallItem> = direct_matches
356 .iter()
357 .cloned()
358 .chain(graph_matches.iter().cloned())
359 .collect();
360
361 let warning = if vec_degraded {
362 Some(
363 "live query embedding unavailable; results are FTS5 BM25 only (semantic relevance reduced)"
364 .to_string(),
365 )
366 } else {
367 None
368 };
369
370 output::emit_json(&RecallResponse {
371 query: args.query,
372 k: args.k,
373 direct_matches,
374 graph_matches,
375 results,
376 elapsed_ms: start.elapsed().as_millis() as u64,
377 vec_degraded,
378 vec_error,
379 warning,
380 })?;
381
382 Ok(())
383}
384
385#[cfg(test)]
386mod tests {
387 use crate::output::{RecallItem, RecallResponse};
388
389 fn make_item(name: &str, distance: f32, source: &str) -> RecallItem {
390 RecallItem {
391 memory_id: 1,
392 name: name.to_string(),
393 namespace: "global".to_string(),
394 memory_type: "fact".to_string(),
395 description: "desc".to_string(),
396 snippet: "snippet".to_string(),
397 distance,
398 score: RecallItem::score_from_distance(distance),
399 source: source.to_string(),
400 graph_depth: if source == "graph" { Some(0) } else { None },
401 }
402 }
403
404 #[test]
406 fn recall_item_score_is_present_and_finite_for_direct_match() {
407 let item = make_item("mem", 0.25, "direct");
408 let json = serde_json::to_value(&item).expect("serialization failed");
409 let score = json["score"].as_f64().expect("score must be a number");
410 assert!(
411 (0.0..=1.0).contains(&score),
412 "score must be in [0, 1], got {score}"
413 );
414 assert!(
415 (score - 0.75).abs() < 1e-6,
416 "score must equal 1 - distance for canonical case"
417 );
418 }
419
420 #[test]
421 fn recall_item_score_clamps_distance_outside_unit_range() {
422 assert_eq!(RecallItem::score_from_distance(2.0), 0.0);
424 assert_eq!(RecallItem::score_from_distance(-0.5), 1.0);
425 assert_eq!(RecallItem::score_from_distance(f32::NAN), 0.0);
426 }
427
428 #[test]
429 fn recall_response_serializes_required_fields() {
430 let resp = RecallResponse {
431 query: "rust memory".to_string(),
432 k: 5,
433 direct_matches: vec![make_item("mem-a", 0.12, "direct")],
434 graph_matches: vec![],
435 results: vec![make_item("mem-a", 0.12, "direct")],
436 elapsed_ms: 42,
437 vec_degraded: false,
438 vec_error: None,
439 warning: None,
440 };
441
442 let json = serde_json::to_value(&resp).expect("serialization failed");
443 assert_eq!(json["query"], "rust memory");
444 assert_eq!(json["k"], 5);
445 assert_eq!(json["elapsed_ms"], 42u64);
446 assert!(json["direct_matches"].is_array());
447 assert!(json["graph_matches"].is_array());
448 assert!(json["results"].is_array());
449 }
450
451 #[test]
452 fn recall_item_serializes_renamed_type() {
453 let item = make_item("mem-test", 0.25, "direct");
454 let json = serde_json::to_value(&item).expect("serialization failed");
455
456 assert_eq!(json["type"], "fact");
458 assert_eq!(json["distance"], 0.25f32);
459 assert_eq!(json["source"], "direct");
460 }
461
462 #[test]
463 fn recall_response_results_contains_direct_and_graph() {
464 let direct = make_item("d-mem", 0.10, "direct");
465 let graph = make_item("g-mem", 0.0, "graph");
466
467 let resp = RecallResponse {
468 query: "query".to_string(),
469 k: 10,
470 direct_matches: vec![direct.clone()],
471 graph_matches: vec![graph.clone()],
472 results: vec![direct, graph],
473 elapsed_ms: 10,
474 vec_degraded: false,
475 vec_error: None,
476 warning: None,
477 };
478
479 let json = serde_json::to_value(&resp).expect("serialization failed");
480 assert_eq!(json["direct_matches"].as_array().unwrap().len(), 1);
481 assert_eq!(json["graph_matches"].as_array().unwrap().len(), 1);
482 assert_eq!(json["results"].as_array().unwrap().len(), 2);
483 assert_eq!(json["results"][0]["source"], "direct");
484 assert_eq!(json["results"][1]["source"], "graph");
485 }
486
487 #[test]
488 fn recall_response_empty_serializes_empty_arrays() {
489 let resp = RecallResponse {
490 query: "nothing".to_string(),
491 k: 3,
492 direct_matches: vec![],
493 graph_matches: vec![],
494 results: vec![],
495 elapsed_ms: 1,
496 vec_degraded: false,
497 vec_error: None,
498 warning: None,
499 };
500
501 let json = serde_json::to_value(&resp).expect("serialization failed");
502 assert_eq!(json["direct_matches"].as_array().unwrap().len(), 0);
503 assert_eq!(json["results"].as_array().unwrap().len(), 0);
504 }
505
506 #[test]
507 fn graph_matches_distance_uses_hop_count_proxy() {
508 let cases: &[(u32, f32)] = &[(0, 0.0), (1, 0.5), (2, 0.6667), (3, 0.75)];
514 for &(hop, expected) in cases {
515 let d = 1.0_f32 - 1.0 / (hop as f32 + 1.0);
516 assert!(
517 (d - expected).abs() < 0.001,
518 "hop={hop} expected={expected} got={d}"
519 );
520 }
521 }
522}