Skip to main content

sqlite_graphrag/commands/
recall.rs

1//! Handler for the `recall` CLI subcommand.
2
3use 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/// Arguments for the `recall` subcommand.
14///
15/// When `--namespace` is omitted the query runs against the `global` namespace,
16/// which is the default namespace used by `remember` when no `--namespace` flag
17/// is provided. Pass an explicit `--namespace` value to search a different
18/// isolated namespace.
19#[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    /// Maximum number of direct vector matches to return.
42    ///
43    /// Note: this flag controls only `direct_matches`. Graph traversal results
44    /// (`graph_matches`) are unbounded by default; use `--max-graph-results` to
45    /// cap them independently. The `results` field aggregates both lists.
46    /// Validated to the inclusive range `1..=4096` (the upper bound matches
47    /// `sqlite-vec`'s knn limit; out-of-range values are rejected at parse time).
48    #[arg(short = 'k', long, aliases = ["limit", "top-k"], default_value = "10", value_parser = crate::parsers::parse_k_range)]
49    pub k: usize,
50    /// Filter by memory.type. Note: distinct from graph entity_type
51    /// (project/tool/person/file/concept/incident/decision/memory/dashboard/issue_tracker/organization/location/date)
52    /// used in --entities-file.
53    #[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    /// Disable -k cap and return all direct matches without truncation.
60    ///
61    /// When set, the `-k`/`--k` flag is ignored for `direct_matches` and the
62    /// response includes every match above the distance threshold. Useful when
63    /// callers need the complete set rather than a top-N preview.
64    #[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    /// Cap the size of `graph_matches` to at most N entries.
71    ///
72    /// Defaults to unbounded (`None`) so existing pipelines see the same shape
73    /// as in v1.0.22 and earlier. Set this when a query touches a dense graph
74    /// neighbourhood and the caller only needs a top-N preview. Added in v1.0.23.
75    #[arg(long, value_name = "N")]
76    pub max_graph_results: Option<usize>,
77    /// Filter results by maximum distance. Results with distance greater than this value
78    /// are excluded. If all matches exceed this threshold, the command exits with code 4
79    /// (`not found`) per the documented public contract.
80    /// Default `1.0` disables the filter and preserves the top-k behavior.
81    #[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    /// Accept `--json` as a no-op because output is already JSON by default.
88    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
89    pub json: bool,
90    /// Search across all namespaces instead of a single namespace.
91    ///
92    /// Cannot be combined with `--namespace`. When set, the query runs against
93    /// every namespace and results include a `namespace` field to identify origin.
94    #[arg(long, conflicts_with = "namespace")]
95    pub all_namespaces: bool,
96    /// G58 (v1.0.80): skip the live query embedding and use FTS5 BM25 +
97    /// LIKE prefix exclusively. Useful in CI/CD with tight OAuth quota and
98    /// in deterministic regression tests that need stable ranking.
99    #[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    // G20: reject graph-specific flags when --no-graph is active
113    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    // Resolve the list of namespaces to search:
130    // - empty vec  => all namespaces (sentinel used by knn_search)
131    // - single vec => one namespace (default or --namespace value)
132    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    // Single namespace string used for graph traversal and error messages.
140    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    // G58 (v1.0.80): when the live embedding fails (timeout, OAuth contention,
154    // rate limit, missing CLI), fall back to FTS5 BM25 + LIKE prefix and
155    // surface the degradation through `vec_degraded` + `vec_error` + `warning`
156    // on the response envelope. The `--fallback-fts-only` flag forces the
157    // skip without even attempting the embedding subprocess.
158    // v1.0.84 (ADR-0042): tuple de 4 elementos. `backend_invoked` carrega
159    // o discriminador do backend que efetivamente invocou o LLM (ou `None`
160    // quando o caller pediu `--fallback-fts-only` e nunca chamou o subprocesso).
161    let (embedding, vec_degraded, vec_error, backend_invoked) = if args.fallback_fts_only {
162        (
163            None,
164            true,
165            Some("fallback_fts_only requested".to_string()),
166            None,
167        )
168    } else {
169        // v1.0.82 (GAP-003): forward --llm-backend to embed_with_fallback.
170        // v1.0.84 (ADR-0042): extrai o backend que efetivamente invocou o
171        // LLM para popular `backend_invoked` no envelope de resposta.
172        // v1.0.85 (G58 / ADR-0043): retry determinístico em OAuthQuota
173        // (codex ↔ claude) e backoff 750ms em SlotExhausted antes de
174        // aceitar a degradação para FTS5-puro.
175        match crate::embedder::try_embed_query_with_deterministic_fallback(
176            &paths.models,
177            &args.query,
178            Some(llm_backend),
179        ) {
180            Ok((v, backend)) => (Some(v), false, None, Some(backend.as_str())),
181            Err(reason) => {
182                let msg = reason.to_string();
183                tracing::warn!(target: "recall", fallback_reason = %msg, reason_code = %reason.reason_code(), "live embedding failed; falling back to FTS5");
184                (None, true, Some(msg), None)
185            }
186        }
187    };
188
189    let memory_type_str = args.r#type.map(|t| t.as_str());
190    // When --precise is set, lift the -k cap so every match is returned; the
191    // max_distance filter below will trim irrelevant results instead.
192    let effective_k = if args.precise { 100_000 } else { args.k };
193
194    // G58: if the embedding is unavailable, route the entire direct path
195    // through FTS5 BM25 + LIKE prefix. Graph traversal is suppressed because
196    // it depends on the KNN results to seed the expansion; without the
197    // embedding, no seed exists.
198    let (direct_matches, memory_ids): (Vec<RecallItem>, Vec<i64>) =
199        if let Some(emb) = embedding.as_ref() {
200            let knn_results =
201                memories::knn_search(&conn, emb, &namespaces, memory_type_str, effective_k)?;
202            let mut items: Vec<RecallItem> = Vec::with_capacity(knn_results.len());
203            let mut memory_ids: Vec<i64> = Vec::with_capacity(knn_results.len());
204            for (memory_id, distance) in knn_results {
205                let row = {
206                    let mut stmt = conn.prepare_cached(
207                        "SELECT id, namespace, name, type, description, body, body_hash,
208                            session_id, source, metadata, created_at, updated_at
209                     FROM memories WHERE id=?1 AND deleted_at IS NULL",
210                    )?;
211                    stmt.query_row(rusqlite::params![memory_id], |r| {
212                        Ok(memories::MemoryRow {
213                            id: r.get(0)?,
214                            namespace: r.get(1)?,
215                            name: r.get(2)?,
216                            memory_type: r.get(3)?,
217                            description: r.get(4)?,
218                            body: r.get(5)?,
219                            body_hash: r.get(6)?,
220                            session_id: r.get(7)?,
221                            source: r.get(8)?,
222                            metadata: r.get(9)?,
223                            created_at: r.get(10)?,
224                            updated_at: r.get(11)?,
225                            deleted_at: None,
226                        })
227                    })
228                    .ok()
229                };
230                if let Some(row) = row {
231                    let snippet: String = row.body.chars().take(300).collect();
232                    items.push(RecallItem {
233                        memory_id: row.id,
234                        name: row.name,
235                        namespace: row.namespace,
236                        memory_type: row.memory_type,
237                        description: row.description,
238                        snippet,
239                        distance,
240                        score: RecallItem::score_from_distance(distance),
241                        source: "direct".to_string(),
242                        graph_depth: None,
243                    });
244                    memory_ids.push(memory_id);
245                }
246            }
247            (items, memory_ids)
248        } else {
249            // FTS5 BM25 + LIKE prefix fallback path. The same `fts_search` helper
250            // is used as in `hybrid-search`; distance is approximated by
251            // 1.0 / (rank + 1) so the score is in (0, 1] and comparable to the
252            // vector path's `1.0 - distance`. Note: only the FIRST effective_k
253            // results are kept to preserve the top-N contract.
254            let fts_rows = memories::fts_search(
255                &conn,
256                &args.query,
257                &namespace_for_graph,
258                memory_type_str,
259                effective_k,
260            )?;
261            let mut items: Vec<RecallItem> = Vec::with_capacity(fts_rows.len());
262            for (rank, row) in fts_rows.into_iter().enumerate() {
263                let dist = 1.0 - 1.0 / (rank as f32 + 1.0);
264                let snippet: String = row.body.chars().take(300).collect();
265                items.push(RecallItem {
266                    memory_id: row.id,
267                    name: row.name,
268                    namespace: row.namespace,
269                    memory_type: row.memory_type,
270                    description: row.description,
271                    snippet,
272                    distance: dist,
273                    score: RecallItem::score_from_distance(dist),
274                    source: "fts_fallback".to_string(),
275                    graph_depth: None,
276                });
277            }
278            (items, Vec::new())
279        };
280
281    let mut graph_matches = Vec::with_capacity(8);
282    if let Some(emb) = (!args.no_graph).then_some(()).and(embedding.as_ref()) {
283        let entity_knn = entities::knn_search(&conn, emb, &namespace_for_graph, 5)?;
284        let entity_ids: Vec<i64> = entity_knn.iter().map(|(id, _)| *id).collect();
285
286        let all_seed_ids: Vec<i64> = memory_ids
287            .iter()
288            .chain(entity_ids.iter())
289            .copied()
290            .collect();
291
292        if !all_seed_ids.is_empty() {
293            let graph_memory_ids = traverse_from_memories_with_hops(
294                &conn,
295                &all_seed_ids,
296                &namespace_for_graph,
297                args.min_weight,
298                args.max_hops,
299            )?;
300
301            for (graph_mem_id, hop) in graph_memory_ids {
302                // v1.0.23: respect the optional cap on graph results so dense
303                // neighbourhoods do not flood the response unintentionally.
304                if let Some(cap) = args.max_graph_results {
305                    if graph_matches.len() >= cap {
306                        break;
307                    }
308                }
309                let row = {
310                    let mut stmt = conn.prepare_cached(
311                        "SELECT id, namespace, name, type, description, body, body_hash,
312                                session_id, source, metadata, created_at, updated_at
313                         FROM memories WHERE id=?1 AND deleted_at IS NULL",
314                    )?;
315                    stmt.query_row(rusqlite::params![graph_mem_id], |r| {
316                        Ok(memories::MemoryRow {
317                            id: r.get(0)?,
318                            namespace: r.get(1)?,
319                            name: r.get(2)?,
320                            memory_type: r.get(3)?,
321                            description: r.get(4)?,
322                            body: r.get(5)?,
323                            body_hash: r.get(6)?,
324                            session_id: r.get(7)?,
325                            source: r.get(8)?,
326                            metadata: r.get(9)?,
327                            created_at: r.get(10)?,
328                            updated_at: r.get(11)?,
329                            deleted_at: None,
330                        })
331                    })
332                    .ok()
333                };
334                if let Some(row) = row {
335                    let snippet: String = row.body.chars().take(300).collect();
336                    let graph_distance = 1.0 - 1.0 / (hop as f32 + 1.0);
337                    graph_matches.push(RecallItem {
338                        memory_id: row.id,
339                        name: row.name,
340                        namespace: row.namespace,
341                        memory_type: row.memory_type,
342                        description: row.description,
343                        snippet,
344                        distance: graph_distance,
345                        score: RecallItem::score_from_distance(graph_distance),
346                        source: "graph".to_string(),
347                        graph_depth: Some(hop),
348                    });
349                }
350            }
351        }
352    }
353
354    // Filtrar por max_distance se < 1.0 (ativado). Se nenhum hit dentro do threshold, exit 4.
355    if args.max_distance < 1.0 && !vec_degraded {
356        let has_relevant = direct_matches
357            .iter()
358            .any(|item| item.distance <= args.max_distance);
359        if !has_relevant {
360            return Err(AppError::NotFound(errors_msg::no_recall_results(
361                args.max_distance,
362                &args.query,
363                &namespace_for_graph,
364            )));
365        }
366    }
367
368    let results: Vec<RecallItem> = direct_matches
369        .iter()
370        .cloned()
371        .chain(graph_matches.iter().cloned())
372        .collect();
373
374    let warning = if vec_degraded {
375        Some(
376            "live query embedding unavailable; results are FTS5 BM25 only (semantic relevance reduced)"
377                .to_string(),
378        )
379    } else {
380        None
381    };
382
383    output::emit_json(&RecallResponse {
384        query: args.query,
385        k: args.k,
386        direct_matches,
387        graph_matches,
388        results,
389        elapsed_ms: start.elapsed().as_millis() as u64,
390        vec_degraded,
391        vec_error: vec_error.clone(),
392        warning,
393        backend_invoked,
394        vec_degraded_reason: if vec_degraded { vec_error } else { None },
395    })?;
396
397    Ok(())
398}
399
400#[cfg(test)]
401mod tests {
402    use crate::output::{RecallItem, RecallResponse};
403
404    fn make_item(name: &str, distance: f32, source: &str) -> RecallItem {
405        RecallItem {
406            memory_id: 1,
407            name: name.to_string(),
408            namespace: "global".to_string(),
409            memory_type: "fact".to_string(),
410            description: "desc".to_string(),
411            snippet: "snippet".to_string(),
412            distance,
413            score: RecallItem::score_from_distance(distance),
414            source: source.to_string(),
415            graph_depth: if source == "graph" { Some(0) } else { None },
416        }
417    }
418
419    // Bug M-A5: every RecallItem carries a non-null cosine similarity score.
420    #[test]
421    fn recall_item_score_is_present_and_finite_for_direct_match() {
422        let item = make_item("mem", 0.25, "direct");
423        let json = serde_json::to_value(&item).expect("serialization failed");
424        let score = json["score"].as_f64().expect("score must be a number");
425        assert!(
426            (0.0..=1.0).contains(&score),
427            "score must be in [0, 1], got {score}"
428        );
429        assert!(
430            (score - 0.75).abs() < 1e-6,
431            "score must equal 1 - distance for canonical case"
432        );
433    }
434
435    #[test]
436    fn recall_item_score_clamps_distance_outside_unit_range() {
437        // Pathological distances must not yield score outside [0, 1] or NaN.
438        assert_eq!(RecallItem::score_from_distance(2.0), 0.0);
439        assert_eq!(RecallItem::score_from_distance(-0.5), 1.0);
440        assert_eq!(RecallItem::score_from_distance(f32::NAN), 0.0);
441    }
442
443    #[test]
444    fn recall_response_serializes_required_fields() {
445        let resp = RecallResponse {
446            query: "rust memory".to_string(),
447            k: 5,
448            direct_matches: vec![make_item("mem-a", 0.12, "direct")],
449            graph_matches: vec![],
450            results: vec![make_item("mem-a", 0.12, "direct")],
451            elapsed_ms: 42,
452            vec_degraded: false,
453            vec_error: None,
454            warning: None,
455            backend_invoked: None,
456            vec_degraded_reason: None,
457        };
458
459        let json = serde_json::to_value(&resp).expect("serialization failed");
460        assert_eq!(json["query"], "rust memory");
461        assert_eq!(json["k"], 5);
462        assert_eq!(json["elapsed_ms"], 42u64);
463        assert!(json["direct_matches"].is_array());
464        assert!(json["graph_matches"].is_array());
465        assert!(json["results"].is_array());
466    }
467
468    #[test]
469    fn recall_item_serializes_renamed_type() {
470        let item = make_item("mem-test", 0.25, "direct");
471        let json = serde_json::to_value(&item).expect("serialization failed");
472
473        // The memory_type field is renamed to "type" in JSON
474        assert_eq!(json["type"], "fact");
475        assert_eq!(json["distance"], 0.25f32);
476        assert_eq!(json["source"], "direct");
477    }
478
479    #[test]
480    fn recall_response_results_contains_direct_and_graph() {
481        let direct = make_item("d-mem", 0.10, "direct");
482        let graph = make_item("g-mem", 0.0, "graph");
483
484        let resp = RecallResponse {
485            query: "query".to_string(),
486            k: 10,
487            direct_matches: vec![direct.clone()],
488            graph_matches: vec![graph.clone()],
489            results: vec![direct, graph],
490            elapsed_ms: 10,
491            vec_degraded: false,
492            vec_error: None,
493            warning: None,
494            backend_invoked: None,
495            vec_degraded_reason: None,
496        };
497
498        let json = serde_json::to_value(&resp).expect("serialization failed");
499        assert_eq!(json["direct_matches"].as_array().unwrap().len(), 1);
500        assert_eq!(json["graph_matches"].as_array().unwrap().len(), 1);
501        assert_eq!(json["results"].as_array().unwrap().len(), 2);
502        assert_eq!(json["results"][0]["source"], "direct");
503        assert_eq!(json["results"][1]["source"], "graph");
504    }
505
506    #[test]
507    fn recall_response_empty_serializes_empty_arrays() {
508        let resp = RecallResponse {
509            query: "nothing".to_string(),
510            k: 3,
511            direct_matches: vec![],
512            graph_matches: vec![],
513            results: vec![],
514            elapsed_ms: 1,
515            vec_degraded: false,
516            vec_error: None,
517            warning: None,
518            backend_invoked: None,
519            vec_degraded_reason: None,
520        };
521
522        let json = serde_json::to_value(&resp).expect("serialization failed");
523        assert_eq!(json["direct_matches"].as_array().unwrap().len(), 0);
524        assert_eq!(json["results"].as_array().unwrap().len(), 0);
525    }
526
527    #[test]
528    fn graph_matches_distance_uses_hop_count_proxy() {
529        // Verify the hop-count proxy formula: 1.0 - 1.0 / (hop + 1.0)
530        // hop=0 → 0.0 (seed-level entity, identity distance)
531        // hop=1 → 0.5
532        // hop=2 → ≈ 0.667
533        // hop=3 → 0.75
534        let cases: &[(u32, f32)] = &[(0, 0.0), (1, 0.5), (2, 0.6667), (3, 0.75)];
535        for &(hop, expected) in cases {
536            let d = 1.0_f32 - 1.0 / (hop as f32 + 1.0);
537            assert!(
538                (d - expected).abs() < 0.001,
539                "hop={hop} expected={expected} got={d}"
540            );
541        }
542    }
543}