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 required_unless_present = "print_schema",
39 help = "Search query string (semantic vector search via sqlite-vec)"
40 )]
41 pub query: Option<String>,
43 #[arg(short = 'k', long, aliases = ["limit", "top-k"], default_value = "10", value_parser = crate::parsers::parse_k_range)]
51 pub k: usize,
52 #[arg(long, value_enum)]
56 pub r#type: Option<MemoryType>,
57 #[arg(long)]
59 pub namespace: Option<String>,
60 #[arg(long)]
62 pub no_graph: bool,
63 #[arg(long)]
69 pub precise: bool,
70 #[arg(long, default_value = "2")]
72 pub max_hops: u32,
73 #[arg(long, default_value = "0.3")]
75 pub min_weight: f64,
76 #[arg(long, value_name = "N")]
82 pub max_graph_results: Option<usize>,
83 #[arg(long, alias = "min-distance", default_value = "1.0")]
88 pub max_distance: f32,
89 #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
91 pub format: JsonOutputFormat,
92 #[arg(long)]
94 pub db: Option<String>,
95 #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
97 pub json: bool,
98 #[arg(long, conflicts_with = "namespace")]
103 pub all_namespaces: bool,
104 #[arg(
108 long,
109 help = "Skip live query embedding; use FTS5 BM25 + LIKE prefix only"
110 )]
111 pub fallback_fts_only: bool,
112 #[arg(
115 long,
116 default_value_t = false,
117 help = "Print JSON Schema for recall output and exit"
118 )]
119 pub print_schema: bool,
120}
121
122#[tracing::instrument(skip_all, level = "debug", name = "recall")]
124pub fn run(
125 args: RecallArgs,
126 llm_backend: crate::cli::LlmBackendChoice,
127 embedding_backend: crate::cli::EmbeddingBackendChoice,
128) -> Result<(), AppError> {
129 if args.print_schema {
130 return crate::print_schema::emit(crate::print_schema::SchemaId::Recall);
131 }
132 let start = std::time::Instant::now();
133 let _ = args.format;
134 let query = args.query.as_deref().unwrap_or("").to_string();
135 tracing::debug!(target: "recall", query = %query, k = args.k, "searching");
136
137 if args.no_graph {
139 if args.max_hops != 2 {
140 return Err(AppError::Validation(
141 "--max-hops has no effect with --no-graph; remove one".to_string(),
142 ));
143 }
144 if (args.min_weight - 0.3).abs() > f64::EPSILON {
145 return Err(AppError::Validation(
146 "--min-weight has no effect with --no-graph; remove one".to_string(),
147 ));
148 }
149 }
150
151 if query.trim().is_empty() {
152 return Err(AppError::Validation(crate::i18n::validation::empty_query()));
153 }
154 let namespaces: Vec<String> = if args.all_namespaces {
158 Vec::new()
159 } else {
160 vec![crate::namespace::resolve_namespace(
161 args.namespace.as_deref(),
162 )?]
163 };
164 let namespace_for_graph = namespaces
166 .first()
167 .cloned()
168 .unwrap_or_else(|| "global".to_string());
169 let paths = AppPaths::resolve(args.db.as_deref())?;
170
171 crate::storage::connection::ensure_db_ready(&paths)?;
172
173 output::emit_progress_i18n(
174 "Computing query embedding...",
175 "Calculando embedding da consulta...",
176 );
177 let conn = open_ro(&paths.db)?;
178 let (embedding, vec_degraded, vec_error, backend_invoked) = if args.fallback_fts_only {
187 (
188 None,
189 true,
190 Some("fallback_fts_only requested".to_string()),
191 None,
192 )
193 } else {
194 match crate::embedder::try_embed_query_with_embedding_choice(
201 &paths.models,
202 &query,
203 embedding_backend,
204 llm_backend,
205 ) {
206 Ok((v, backend)) => (Some(v), false, None, Some(backend.as_str())),
207 Err(reason) => {
208 let msg = reason.to_string();
209 tracing::warn!(target: "recall", fallback_reason = %msg, reason_code = %reason.reason_code(), "live embedding failed; falling back to FTS5");
210 (None, true, Some(msg), None)
211 }
212 }
213 };
214
215 let memory_type_str = args.r#type.map(|t| t.as_str());
216 let effective_k = if args.precise { 100_000 } else { args.k };
219
220 let (direct_matches, memory_ids): (Vec<RecallItem>, Vec<i64>) =
225 if let Some(emb) = embedding.as_ref() {
226 let knn_results =
227 memories::knn_search(&conn, emb, &namespaces, memory_type_str, effective_k)?;
228 let mut items: Vec<RecallItem> = Vec::with_capacity(knn_results.len());
229 let mut memory_ids: Vec<i64> = Vec::with_capacity(knn_results.len());
230 for (memory_id, distance) in knn_results {
231 let row = {
232 let mut stmt = conn.prepare_cached(
233 "SELECT id, namespace, name, type, description, body, body_hash,
234 session_id, source, metadata, created_at, updated_at
235 FROM memories WHERE id=?1 AND deleted_at IS NULL",
236 )?;
237 stmt.query_row(rusqlite::params![memory_id], |r| {
238 Ok(memories::MemoryRow {
239 id: r.get(0)?,
240 namespace: r.get(1)?,
241 name: r.get(2)?,
242 memory_type: r.get(3)?,
243 description: r.get(4)?,
244 body: r.get(5)?,
245 body_hash: r.get(6)?,
246 session_id: r.get(7)?,
247 source: r.get(8)?,
248 metadata: r.get(9)?,
249 created_at: r.get(10)?,
250 updated_at: r.get(11)?,
251 deleted_at: None,
252 })
253 })
254 .ok()
255 };
256 if let Some(row) = row {
257 let snippet: String = row.body.chars().take(300).collect();
258 items.push(RecallItem {
259 memory_id: row.id,
260 name: row.name,
261 namespace: row.namespace,
262 memory_type: row.memory_type,
263 description: row.description,
264 snippet,
265 distance,
266 score: RecallItem::score_from_distance(distance),
267 source: "direct".to_string(),
268 graph_depth: None,
269 });
270 memory_ids.push(memory_id);
271 }
272 }
273 (items, memory_ids)
274 } else {
275 let fts_rows = memories::fts_search(
281 &conn,
282 &query,
283 &namespace_for_graph,
284 memory_type_str,
285 effective_k,
286 )?;
287 let mut items: Vec<RecallItem> = Vec::with_capacity(fts_rows.len());
288 for (rank, row) in fts_rows.into_iter().enumerate() {
289 let dist = 1.0 - 1.0 / (rank as f32 + 1.0);
290 let snippet: String = row.body.chars().take(300).collect();
291 items.push(RecallItem {
292 memory_id: row.id,
293 name: row.name,
294 namespace: row.namespace,
295 memory_type: row.memory_type,
296 description: row.description,
297 snippet,
298 distance: dist,
299 score: RecallItem::score_from_distance(dist),
300 source: "fts_fallback".to_string(),
301 graph_depth: None,
302 });
303 }
304 (items, Vec::new())
305 };
306
307 let mut graph_matches = Vec::with_capacity(8);
308 if let Some(emb) = (!args.no_graph).then_some(()).and(embedding.as_ref()) {
309 let entity_knn = entities::knn_search(&conn, emb, &namespace_for_graph, 5)?;
310 let entity_ids: Vec<i64> = entity_knn.iter().map(|(id, _)| *id).collect();
311
312 let all_seed_ids: Vec<i64> = memory_ids
313 .iter()
314 .chain(entity_ids.iter())
315 .copied()
316 .collect();
317
318 if !all_seed_ids.is_empty() {
319 let graph_memory_ids = traverse_from_memories_with_hops(
320 &conn,
321 &all_seed_ids,
322 &namespace_for_graph,
323 args.min_weight,
324 args.max_hops,
325 )?;
326
327 for (graph_mem_id, hop) in graph_memory_ids {
328 if let Some(cap) = args.max_graph_results {
331 if graph_matches.len() >= cap {
332 break;
333 }
334 }
335 let row = {
336 let mut stmt = conn.prepare_cached(
337 "SELECT id, namespace, name, type, description, body, body_hash,
338 session_id, source, metadata, created_at, updated_at
339 FROM memories WHERE id=?1 AND deleted_at IS NULL",
340 )?;
341 stmt.query_row(rusqlite::params![graph_mem_id], |r| {
342 Ok(memories::MemoryRow {
343 id: r.get(0)?,
344 namespace: r.get(1)?,
345 name: r.get(2)?,
346 memory_type: r.get(3)?,
347 description: r.get(4)?,
348 body: r.get(5)?,
349 body_hash: r.get(6)?,
350 session_id: r.get(7)?,
351 source: r.get(8)?,
352 metadata: r.get(9)?,
353 created_at: r.get(10)?,
354 updated_at: r.get(11)?,
355 deleted_at: None,
356 })
357 })
358 .ok()
359 };
360 if let Some(row) = row {
361 let snippet: String = row.body.chars().take(300).collect();
362 let graph_distance = 1.0 - 1.0 / (hop as f32 + 1.0);
363 graph_matches.push(RecallItem {
364 memory_id: row.id,
365 name: row.name,
366 namespace: row.namespace,
367 memory_type: row.memory_type,
368 description: row.description,
369 snippet,
370 distance: graph_distance,
371 score: RecallItem::score_from_distance(graph_distance),
372 source: "graph".to_string(),
373 graph_depth: Some(hop),
374 });
375 }
376 }
377 }
378 }
379
380 if args.max_distance < 1.0 && !vec_degraded {
382 let has_relevant = direct_matches
383 .iter()
384 .any(|item| item.distance <= args.max_distance);
385 if !has_relevant {
386 return Err(AppError::NotFound(errors_msg::no_recall_results(
387 args.max_distance,
388 &query,
389 &namespace_for_graph,
390 )));
391 }
392 }
393
394 let results: Vec<RecallItem> = direct_matches
395 .iter()
396 .cloned()
397 .chain(graph_matches.iter().cloned())
398 .collect();
399
400 let warning = if vec_degraded {
401 Some(
402 "live query embedding unavailable; results are FTS5 BM25 only (semantic relevance reduced)"
403 .to_string(),
404 )
405 } else {
406 None
407 };
408
409 output::emit_json(&RecallResponse {
410 query,
411 k: args.k,
412 direct_matches,
413 graph_matches,
414 results,
415 elapsed_ms: start.elapsed().as_millis() as u64,
416 vec_degraded,
417 vec_error: vec_error.clone(),
418 warning,
419 backend_invoked,
420 vec_degraded_reason: if vec_degraded { vec_error } else { None },
421 })?;
422
423 Ok(())
424}
425
426#[cfg(test)]
427mod tests {
428 use crate::output::{RecallItem, RecallResponse};
429
430 fn make_item(name: &str, distance: f32, source: &str) -> RecallItem {
431 RecallItem {
432 memory_id: 1,
433 name: name.to_string(),
434 namespace: "global".to_string(),
435 memory_type: "fact".to_string(),
436 description: "desc".to_string(),
437 snippet: "snippet".to_string(),
438 distance,
439 score: RecallItem::score_from_distance(distance),
440 source: source.to_string(),
441 graph_depth: if source == "graph" { Some(0) } else { None },
442 }
443 }
444
445 #[test]
447 fn recall_item_score_is_present_and_finite_for_direct_match() {
448 let item = make_item("mem", 0.25, "direct");
449 let json = serde_json::to_value(&item).expect("serialization failed");
450 let score = json["score"].as_f64().expect("score must be a number");
451 assert!(
452 (0.0..=1.0).contains(&score),
453 "score must be in [0, 1], got {score}"
454 );
455 assert!(
456 (score - 0.75).abs() < 1e-6,
457 "score must equal 1 - distance for canonical case"
458 );
459 }
460
461 #[test]
462 fn recall_item_score_clamps_distance_outside_unit_range() {
463 assert_eq!(RecallItem::score_from_distance(2.0), 0.0);
465 assert_eq!(RecallItem::score_from_distance(-0.5), 1.0);
466 assert_eq!(RecallItem::score_from_distance(f32::NAN), 0.0);
467 }
468
469 #[test]
470 fn recall_response_serializes_required_fields() {
471 let resp = RecallResponse {
472 query: "rust memory".to_string(),
473 k: 5,
474 direct_matches: vec![make_item("mem-a", 0.12, "direct")],
475 graph_matches: vec![],
476 results: vec![make_item("mem-a", 0.12, "direct")],
477 elapsed_ms: 42,
478 vec_degraded: false,
479 vec_error: None,
480 warning: None,
481 backend_invoked: None,
482 vec_degraded_reason: None,
483 };
484
485 let json = serde_json::to_value(&resp).expect("serialization failed");
486 assert_eq!(json["query"], "rust memory");
487 assert_eq!(json["k"], 5);
488 assert_eq!(json["elapsed_ms"], 42u64);
489 assert!(json["direct_matches"].is_array());
490 assert!(json["graph_matches"].is_array());
491 assert!(json["results"].is_array());
492 }
493
494 #[test]
495 fn recall_item_serializes_renamed_type() {
496 let item = make_item("mem-test", 0.25, "direct");
497 let json = serde_json::to_value(&item).expect("serialization failed");
498
499 assert_eq!(json["type"], "fact");
501 assert_eq!(json["distance"], 0.25f32);
502 assert_eq!(json["source"], "direct");
503 }
504
505 #[test]
506 fn recall_response_results_contains_direct_and_graph() {
507 let direct = make_item("d-mem", 0.10, "direct");
508 let graph = make_item("g-mem", 0.0, "graph");
509
510 let resp = RecallResponse {
511 query: "query".to_string(),
512 k: 10,
513 direct_matches: vec![direct.clone()],
514 graph_matches: vec![graph.clone()],
515 results: vec![direct, graph],
516 elapsed_ms: 10,
517 vec_degraded: false,
518 vec_error: None,
519 warning: None,
520 backend_invoked: None,
521 vec_degraded_reason: None,
522 };
523
524 let json = serde_json::to_value(&resp).expect("serialization failed");
525 assert_eq!(json["direct_matches"].as_array().unwrap().len(), 1);
526 assert_eq!(json["graph_matches"].as_array().unwrap().len(), 1);
527 assert_eq!(json["results"].as_array().unwrap().len(), 2);
528 assert_eq!(json["results"][0]["source"], "direct");
529 assert_eq!(json["results"][1]["source"], "graph");
530 }
531
532 #[test]
533 fn recall_response_empty_serializes_empty_arrays() {
534 let resp = RecallResponse {
535 query: "nothing".to_string(),
536 k: 3,
537 direct_matches: vec![],
538 graph_matches: vec![],
539 results: vec![],
540 elapsed_ms: 1,
541 vec_degraded: false,
542 vec_error: None,
543 warning: None,
544 backend_invoked: None,
545 vec_degraded_reason: None,
546 };
547
548 let json = serde_json::to_value(&resp).expect("serialization failed");
549 assert_eq!(json["direct_matches"].as_array().unwrap().len(), 0);
550 assert_eq!(json["results"].as_array().unwrap().len(), 0);
551 }
552
553 #[test]
554 fn graph_matches_distance_uses_hop_count_proxy() {
555 let cases: &[(u32, f32)] = &[(0, 0.0), (1, 0.5), (2, 0.6667), (3, 0.75)];
561 for &(hop, expected) in cases {
562 let d = 1.0_f32 - 1.0 / (hop as f32 + 1.0);
563 assert!(
564 (d - expected).abs() < 0.001,
565 "hop={hop} expected={expected} got={d}"
566 );
567 }
568 }
569}