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}
97
98#[tracing::instrument(skip_all, level = "debug", name = "recall")]
99pub fn run(args: RecallArgs) -> Result<(), AppError> {
100    let start = std::time::Instant::now();
101    let _ = args.format;
102    tracing::debug!(target: "recall", query = %args.query, k = args.k, "searching");
103
104    // G20: reject graph-specific flags when --no-graph is active
105    if args.no_graph {
106        if args.max_hops != 2 {
107            return Err(AppError::Validation(
108                "--max-hops has no effect with --no-graph; remove one".to_string(),
109            ));
110        }
111        if (args.min_weight - 0.3).abs() > f64::EPSILON {
112            return Err(AppError::Validation(
113                "--min-weight has no effect with --no-graph; remove one".to_string(),
114            ));
115        }
116    }
117
118    if args.query.trim().is_empty() {
119        return Err(AppError::Validation(crate::i18n::validation::empty_query()));
120    }
121    // Resolve the list of namespaces to search:
122    // - empty vec  => all namespaces (sentinel used by knn_search)
123    // - single vec => one namespace (default or --namespace value)
124    let namespaces: Vec<String> = if args.all_namespaces {
125        Vec::new()
126    } else {
127        vec![crate::namespace::resolve_namespace(
128            args.namespace.as_deref(),
129        )?]
130    };
131    // Single namespace string used for graph traversal and error messages.
132    let namespace_for_graph = namespaces
133        .first()
134        .cloned()
135        .unwrap_or_else(|| "global".to_string());
136    let paths = AppPaths::resolve(args.db.as_deref())?;
137
138    crate::storage::connection::ensure_db_ready(&paths)?;
139
140    output::emit_progress_i18n(
141        "Computing query embedding...",
142        "Calculando embedding da consulta...",
143    );
144    let embedding = crate::embedder::embed_query_local(&paths.models, &args.query)?;
145
146    let conn = open_ro(&paths.db)?;
147
148    let memory_type_str = args.r#type.map(|t| t.as_str());
149    // When --precise is set, lift the -k cap so every match is returned; the
150    // max_distance filter below will trim irrelevant results instead.
151    let effective_k = if args.precise { 100_000 } else { args.k };
152    let knn_results =
153        memories::knn_search(&conn, &embedding, &namespaces, memory_type_str, effective_k)?;
154
155    let mut direct_matches = Vec::with_capacity(effective_k);
156    let mut memory_ids: Vec<i64> = Vec::with_capacity(effective_k);
157    for (memory_id, distance) in knn_results {
158        let row = {
159            let mut stmt = conn.prepare_cached(
160                "SELECT id, namespace, name, type, description, body, body_hash,
161                        session_id, source, metadata, created_at, updated_at
162                 FROM memories WHERE id=?1 AND deleted_at IS NULL",
163            )?;
164            stmt.query_row(rusqlite::params![memory_id], |r| {
165                Ok(memories::MemoryRow {
166                    id: r.get(0)?,
167                    namespace: r.get(1)?,
168                    name: r.get(2)?,
169                    memory_type: r.get(3)?,
170                    description: r.get(4)?,
171                    body: r.get(5)?,
172                    body_hash: r.get(6)?,
173                    session_id: r.get(7)?,
174                    source: r.get(8)?,
175                    metadata: r.get(9)?,
176                    created_at: r.get(10)?,
177                    updated_at: r.get(11)?,
178                    deleted_at: None,
179                })
180            })
181            .ok()
182        };
183        if let Some(row) = row {
184            let snippet: String = row.body.chars().take(300).collect();
185            direct_matches.push(RecallItem {
186                memory_id: row.id,
187                name: row.name,
188                namespace: row.namespace,
189                memory_type: row.memory_type,
190                description: row.description,
191                snippet,
192                distance,
193                score: RecallItem::score_from_distance(distance),
194                source: "direct".to_string(),
195                // Direct vector matches do not have a graph depth; rely on `distance`.
196                graph_depth: None,
197            });
198            memory_ids.push(memory_id);
199        }
200    }
201
202    let mut graph_matches = Vec::with_capacity(8);
203    if !args.no_graph {
204        let entity_knn = entities::knn_search(&conn, &embedding, &namespace_for_graph, 5)?;
205        let entity_ids: Vec<i64> = entity_knn.iter().map(|(id, _)| *id).collect();
206
207        let all_seed_ids: Vec<i64> = memory_ids
208            .iter()
209            .chain(entity_ids.iter())
210            .copied()
211            .collect();
212
213        if !all_seed_ids.is_empty() {
214            let graph_memory_ids = traverse_from_memories_with_hops(
215                &conn,
216                &all_seed_ids,
217                &namespace_for_graph,
218                args.min_weight,
219                args.max_hops,
220            )?;
221
222            for (graph_mem_id, hop) in graph_memory_ids {
223                // v1.0.23: respect the optional cap on graph results so dense
224                // neighbourhoods do not flood the response unintentionally.
225                if let Some(cap) = args.max_graph_results {
226                    if graph_matches.len() >= cap {
227                        break;
228                    }
229                }
230                let row = {
231                    let mut stmt = conn.prepare_cached(
232                        "SELECT id, namespace, name, type, description, body, body_hash,
233                                session_id, source, metadata, created_at, updated_at
234                         FROM memories WHERE id=?1 AND deleted_at IS NULL",
235                    )?;
236                    stmt.query_row(rusqlite::params![graph_mem_id], |r| {
237                        Ok(memories::MemoryRow {
238                            id: r.get(0)?,
239                            namespace: r.get(1)?,
240                            name: r.get(2)?,
241                            memory_type: r.get(3)?,
242                            description: r.get(4)?,
243                            body: r.get(5)?,
244                            body_hash: r.get(6)?,
245                            session_id: r.get(7)?,
246                            source: r.get(8)?,
247                            metadata: r.get(9)?,
248                            created_at: r.get(10)?,
249                            updated_at: r.get(11)?,
250                            deleted_at: None,
251                        })
252                    })
253                    .ok()
254                };
255                if let Some(row) = row {
256                    let snippet: String = row.body.chars().take(300).collect();
257                    // Compute approximate distance from graph hop count.
258                    // WARNING: graph_distance is a hop-count proxy, NOT real cosine distance.
259                    // For confident ranking, prefer the `graph_depth` field (set to Some(hop)
260                    // below). Real cosine distance for graph matches would require
261                    // re-embedding (200-500ms latency) and is reserved for v1.0.28.
262                    let graph_distance = 1.0 - 1.0 / (hop as f32 + 1.0);
263                    graph_matches.push(RecallItem {
264                        memory_id: row.id,
265                        name: row.name,
266                        namespace: row.namespace,
267                        memory_type: row.memory_type,
268                        description: row.description,
269                        snippet,
270                        distance: graph_distance,
271                        score: RecallItem::score_from_distance(graph_distance),
272                        source: "graph".to_string(),
273                        graph_depth: Some(hop),
274                    });
275                }
276            }
277        }
278    }
279
280    // Filtrar por max_distance se < 1.0 (ativado). Se nenhum hit dentro do threshold, exit 4.
281    if args.max_distance < 1.0 {
282        let has_relevant = direct_matches
283            .iter()
284            .any(|item| item.distance <= args.max_distance);
285        if !has_relevant {
286            return Err(AppError::NotFound(errors_msg::no_recall_results(
287                args.max_distance,
288                &args.query,
289                &namespace_for_graph,
290            )));
291        }
292    }
293
294    let results: Vec<RecallItem> = direct_matches
295        .iter()
296        .cloned()
297        .chain(graph_matches.iter().cloned())
298        .collect();
299
300    output::emit_json(&RecallResponse {
301        query: args.query,
302        k: args.k,
303        direct_matches,
304        graph_matches,
305        results,
306        elapsed_ms: start.elapsed().as_millis() as u64,
307    })?;
308
309    Ok(())
310}
311
312#[cfg(test)]
313mod tests {
314    use crate::output::{RecallItem, RecallResponse};
315
316    fn make_item(name: &str, distance: f32, source: &str) -> RecallItem {
317        RecallItem {
318            memory_id: 1,
319            name: name.to_string(),
320            namespace: "global".to_string(),
321            memory_type: "fact".to_string(),
322            description: "desc".to_string(),
323            snippet: "snippet".to_string(),
324            distance,
325            score: RecallItem::score_from_distance(distance),
326            source: source.to_string(),
327            graph_depth: if source == "graph" { Some(0) } else { None },
328        }
329    }
330
331    // Bug M-A5: every RecallItem carries a non-null cosine similarity score.
332    #[test]
333    fn recall_item_score_is_present_and_finite_for_direct_match() {
334        let item = make_item("mem", 0.25, "direct");
335        let json = serde_json::to_value(&item).expect("serialization failed");
336        let score = json["score"].as_f64().expect("score must be a number");
337        assert!(
338            (0.0..=1.0).contains(&score),
339            "score must be in [0, 1], got {score}"
340        );
341        assert!(
342            (score - 0.75).abs() < 1e-6,
343            "score must equal 1 - distance for canonical case"
344        );
345    }
346
347    #[test]
348    fn recall_item_score_clamps_distance_outside_unit_range() {
349        // Pathological distances must not yield score outside [0, 1] or NaN.
350        assert_eq!(RecallItem::score_from_distance(2.0), 0.0);
351        assert_eq!(RecallItem::score_from_distance(-0.5), 1.0);
352        assert_eq!(RecallItem::score_from_distance(f32::NAN), 0.0);
353    }
354
355    #[test]
356    fn recall_response_serializes_required_fields() {
357        let resp = RecallResponse {
358            query: "rust memory".to_string(),
359            k: 5,
360            direct_matches: vec![make_item("mem-a", 0.12, "direct")],
361            graph_matches: vec![],
362            results: vec![make_item("mem-a", 0.12, "direct")],
363            elapsed_ms: 42,
364        };
365
366        let json = serde_json::to_value(&resp).expect("serialization failed");
367        assert_eq!(json["query"], "rust memory");
368        assert_eq!(json["k"], 5);
369        assert_eq!(json["elapsed_ms"], 42u64);
370        assert!(json["direct_matches"].is_array());
371        assert!(json["graph_matches"].is_array());
372        assert!(json["results"].is_array());
373    }
374
375    #[test]
376    fn recall_item_serializes_renamed_type() {
377        let item = make_item("mem-test", 0.25, "direct");
378        let json = serde_json::to_value(&item).expect("serialization failed");
379
380        // The memory_type field is renamed to "type" in JSON
381        assert_eq!(json["type"], "fact");
382        assert_eq!(json["distance"], 0.25f32);
383        assert_eq!(json["source"], "direct");
384    }
385
386    #[test]
387    fn recall_response_results_contains_direct_and_graph() {
388        let direct = make_item("d-mem", 0.10, "direct");
389        let graph = make_item("g-mem", 0.0, "graph");
390
391        let resp = RecallResponse {
392            query: "query".to_string(),
393            k: 10,
394            direct_matches: vec![direct.clone()],
395            graph_matches: vec![graph.clone()],
396            results: vec![direct, graph],
397            elapsed_ms: 10,
398        };
399
400        let json = serde_json::to_value(&resp).expect("serialization failed");
401        assert_eq!(json["direct_matches"].as_array().unwrap().len(), 1);
402        assert_eq!(json["graph_matches"].as_array().unwrap().len(), 1);
403        assert_eq!(json["results"].as_array().unwrap().len(), 2);
404        assert_eq!(json["results"][0]["source"], "direct");
405        assert_eq!(json["results"][1]["source"], "graph");
406    }
407
408    #[test]
409    fn recall_response_empty_serializes_empty_arrays() {
410        let resp = RecallResponse {
411            query: "nothing".to_string(),
412            k: 3,
413            direct_matches: vec![],
414            graph_matches: vec![],
415            results: vec![],
416            elapsed_ms: 1,
417        };
418
419        let json = serde_json::to_value(&resp).expect("serialization failed");
420        assert_eq!(json["direct_matches"].as_array().unwrap().len(), 0);
421        assert_eq!(json["results"].as_array().unwrap().len(), 0);
422    }
423
424    #[test]
425    fn graph_matches_distance_uses_hop_count_proxy() {
426        // Verify the hop-count proxy formula: 1.0 - 1.0 / (hop + 1.0)
427        // hop=0 → 0.0 (seed-level entity, identity distance)
428        // hop=1 → 0.5
429        // hop=2 → ≈ 0.667
430        // hop=3 → 0.75
431        let cases: &[(u32, f32)] = &[(0, 0.0), (1, 0.5), (2, 0.6667), (3, 0.75)];
432        for &(hop, expected) in cases {
433            let d = 1.0_f32 - 1.0 / (hop as f32 + 1.0);
434            assert!(
435                (d - expected).abs() < 0.001,
436                "hop={hop} expected={expected} got={d}"
437            );
438        }
439    }
440}