Skip to main content

rinne_graph/
store.rs

1//! SQLite-backed store: persist files, freshness checks, neighborhood queries.
2
3use std::collections::hash_map::DefaultHasher;
4use std::hash::{Hash, Hasher};
5use std::path::{Path, PathBuf};
6
7use rusqlite::Connection;
8
9use crate::extract::extract;
10use crate::model::{Neighborhood, Symbol, SymbolKind, SymbolRef};
11use crate::resolve::resolve_file;
12use crate::schema::init_graph_schema;
13use rinne_types::skip::source_lang;
14
15pub struct Store {
16    pub(crate) conn: Connection,
17    root: PathBuf,
18}
19
20impl Store {
21    pub fn open(db_path: &Path, root: &Path) -> rusqlite::Result<Store> {
22        let conn = Connection::open(db_path)?;
23        conn.execute_batch(
24            "PRAGMA journal_mode=WAL;
25             PRAGMA synchronous=NORMAL;",
26        )?;
27        conn.busy_timeout(std::time::Duration::from_secs(5))?;
28        // Wipe stale graph tables on a schema/extractor version bump so an upgraded
29        // binary re-extracts every file automatically (no manual re-index needed).
30        crate::schema::migrate_graph_if_stale(&conn)?;
31        init_graph_schema(&conn)?;
32        Ok(Store {
33            conn,
34            root: root.to_path_buf(),
35        })
36    }
37
38    /// Stable content hash for freshness comparison.
39    /// Uses DefaultHasher — deterministic within a build, sufficient for this use.
40    pub fn hash_of(source: &str) -> String {
41        let mut h = DefaultHasher::new();
42        source.hash(&mut h);
43        format!("{:016x}", h.finish())
44    }
45
46    /// Returns true if the stored hash for `path` matches `hash_of(source)`.
47    pub fn is_current(&self, path: &str, source: &str) -> bool {
48        let hash = Self::hash_of(source);
49        self.conn
50            .query_row(
51                "SELECT content_hash FROM graph_files WHERE path = ?1",
52                [path],
53                |row| row.get::<_, String>(0),
54            )
55            .map(|stored| stored == hash)
56            .unwrap_or(false)
57    }
58
59    /// Transactionally re-index a file: delete prior rows, extract+resolve, insert new rows.
60    /// No-ops for files with unsupported languages (upserts only the file row with lang='').
61    pub fn index_file(&self, path: &str, source: &str, mtime: i64) -> rusqlite::Result<()> {
62        let hash = Self::hash_of(source);
63        let lang = source_lang(path);
64
65        let tx = self.conn.unchecked_transaction()?;
66
67        // Delete prior edges for this file's symbols first (FK-style manual cascade).
68        tx.execute(
69            "DELETE FROM graph_edges WHERE src_symbol IN (SELECT id FROM graph_symbols WHERE file = ?1) \
70             OR dst_symbol IN (SELECT id FROM graph_symbols WHERE file = ?1)",
71            rusqlite::params![path],
72        )?;
73        tx.execute(
74            "DELETE FROM graph_symbols WHERE file = ?1",
75            rusqlite::params![path],
76        )?;
77
78        if let Some(lang_str) = lang {
79            if let Some((raw_symbols, raw_edges)) = extract(lang_str, source) {
80                // Insert each symbol, capturing its rowid by position. Distinct rows
81                // get distinct ids, so same-name defs in one file are not collapsed.
82                let mut ids: Vec<i64> = Vec::with_capacity(raw_symbols.len());
83                for rs in &raw_symbols {
84                    tx.execute(
85                        "INSERT INTO graph_symbols (file, name, kind, start_line, end_line, signature, container) \
86                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
87                        rusqlite::params![
88                            path,
89                            rs.name,
90                            rs.kind.as_str(),
91                            rs.start_line,
92                            rs.end_line,
93                            rs.signature,
94                            rs.container,
95                        ],
96                    )?;
97                    ids.push(tx.last_insert_rowid());
98                }
99
100                let (_, edges) = resolve_file(path, raw_symbols, raw_edges, |i| ids[i]);
101
102                for edge in &edges {
103                    tx.execute(
104                        "INSERT INTO graph_edges (src_symbol, dst_symbol, dst_name, kind) \
105                         VALUES (?1, ?2, ?3, ?4)",
106                        rusqlite::params![edge.src, edge.dst, edge.dst_name, edge.kind.as_str(),],
107                    )?;
108                }
109            }
110        }
111
112        let now = std::time::SystemTime::now()
113            .duration_since(std::time::UNIX_EPOCH)
114            .map(|d| d.as_secs() as i64)
115            .unwrap_or(0);
116
117        tx.execute(
118            "INSERT INTO graph_files (path, lang, content_hash, mtime, indexed_at)
119             VALUES (?1, ?2, ?3, ?4, ?5)
120             ON CONFLICT(path) DO UPDATE SET
121               lang         = excluded.lang,
122               content_hash = excluded.content_hash,
123               mtime        = excluded.mtime,
124               indexed_at   = excluded.indexed_at",
125            rusqlite::params![path, lang.unwrap_or(""), hash, mtime, now],
126        )?;
127
128        tx.commit()
129    }
130
131    /// Returns the definition + callers + callees + imports for the first symbol
132    /// matching `symbol_name`.
133    ///
134    /// When the same name is defined in more than one place this collapses to one
135    /// arbitrary match; prefer [`Store::neighborhood_all`] in that case.
136    pub fn neighborhood(&self, symbol_name: &str) -> Option<Neighborhood> {
137        self.neighborhood_all(symbol_name).into_iter().next()
138    }
139
140    /// Returns one [`Neighborhood`] per definition site matching `symbol_name`,
141    /// ordered by file then start line (deterministic). Empty when the name is
142    /// not indexed. This is the multi-result form that avoids the single-winner
143    /// collapse of [`Store::neighborhood`].
144    pub fn neighborhood_all(&self, symbol_name: &str) -> Vec<Neighborhood> {
145        // Every definition row for this name, in a stable order.
146        let defs: Vec<(i64, String, u32, u32)> = self
147            .conn
148            .prepare(
149                "SELECT id, file, start_line, COALESCE(end_line, start_line) \
150                 FROM graph_symbols WHERE name = ?1 ORDER BY file, start_line",
151            )
152            .and_then(|mut stmt| {
153                stmt.query_map([symbol_name], |row| {
154                    Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
155                })
156                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
157            })
158            .unwrap_or_default();
159
160        defs.into_iter()
161            .map(|(sym_id, file, start_line, end_line)| {
162                self.neighborhood_for(symbol_name, sym_id, file, start_line, end_line)
163            })
164            .collect()
165    }
166
167    /// Build the neighborhood for one specific definition row.
168    fn neighborhood_for(
169        &self,
170        symbol_name: &str,
171        sym_id: i64,
172        file: String,
173        start_line: u32,
174        end_line: u32,
175    ) -> Neighborhood {
176        let definition = SymbolRef {
177            name: symbol_name.to_string(),
178            file: file.clone(),
179            line: start_line,
180            end_line,
181        };
182
183        // Callers: symbols whose id is src_symbol of an edge with dst_symbol = sym_id.
184        let callers = self
185            .conn
186            .prepare(
187                "SELECT s.name, s.file, s.start_line, COALESCE(s.end_line, s.start_line)
188                 FROM graph_edges e
189                 JOIN graph_symbols s ON s.id = e.src_symbol
190                 WHERE e.dst_symbol = ?1 AND e.kind = 'calls'",
191            )
192            .and_then(|mut stmt| {
193                stmt.query_map([sym_id], |row| {
194                    Ok(SymbolRef {
195                        name: row.get(0)?,
196                        file: row.get(1)?,
197                        line: row.get(2)?,
198                        end_line: row.get(3)?,
199                    })
200                })
201                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
202            })
203            .unwrap_or_default();
204
205        // Callees: symbols whose id is dst_symbol of an edge with src_symbol = sym_id.
206        let callees = self
207            .conn
208            .prepare(
209                "SELECT s.name, s.file, s.start_line, COALESCE(s.end_line, s.start_line)
210                 FROM graph_edges e
211                 JOIN graph_symbols s ON s.id = e.dst_symbol
212                 WHERE e.src_symbol = ?1 AND e.kind = 'calls'",
213            )
214            .and_then(|mut stmt| {
215                stmt.query_map([sym_id], |row| {
216                    Ok(SymbolRef {
217                        name: row.get(0)?,
218                        file: row.get(1)?,
219                        line: row.get(2)?,
220                        end_line: row.get(3)?,
221                    })
222                })
223                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
224            })
225            .unwrap_or_default();
226
227        // Imports: edges of kind 'imports' where src_symbol = sym_id; dst may be unresolved.
228        // When dst_symbol is set, join on symbols; otherwise use dst_name best-effort.
229        let imports = self
230            .conn
231            .prepare(
232                "SELECT COALESCE(s.name, e.dst_name), COALESCE(s.file, ''), \
233                        COALESCE(s.start_line, 0), COALESCE(s.end_line, s.start_line, 0)
234                 FROM graph_edges e
235                 LEFT JOIN graph_symbols s ON s.id = e.dst_symbol
236                 WHERE e.src_symbol = ?1 AND e.kind = 'imports'",
237            )
238            .and_then(|mut stmt| {
239                stmt.query_map([sym_id], |row| {
240                    Ok(SymbolRef {
241                        name: row.get(0)?,
242                        file: row.get(1)?,
243                        line: row.get(2)?,
244                        end_line: row.get(3)?,
245                    })
246                })
247                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
248            })
249            .unwrap_or_default();
250
251        let stale = {
252            let abs = self.root.join(&definition.file);
253            match std::fs::read_to_string(&abs) {
254                Ok(contents) => {
255                    let cur = Self::hash_of(&contents);
256                    let stored: Option<String> = self
257                        .conn
258                        .query_row(
259                            "SELECT content_hash FROM graph_files WHERE path = ?1",
260                            [definition.file.as_str()],
261                            |r| r.get(0),
262                        )
263                        .ok();
264                    stored.map(|s| s != cur).unwrap_or(false)
265                }
266                Err(_) => false,
267            }
268        };
269
270        Neighborhood {
271            definition,
272            callers,
273            callees,
274            imports,
275            stale,
276        }
277    }
278
279    /// Returns the names of every symbol currently in the index.
280    pub fn symbol_names(&self) -> Vec<String> {
281        self.conn
282            .prepare("SELECT DISTINCT name FROM graph_symbols")
283            .and_then(|mut stmt| {
284                stmt.query_map([], |row| row.get(0))
285                    .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
286            })
287            .unwrap_or_default()
288    }
289
290    /// Returns the first symbol named `name` in `file`.
291    pub fn resolve_in_file(&self, file: &str, name: &str) -> Option<SymbolRef> {
292        self.conn
293            .query_row(
294                "SELECT name, file, start_line, COALESCE(end_line, start_line) \
295                 FROM graph_symbols WHERE file = ?1 AND name = ?2 LIMIT 1",
296                rusqlite::params![file, name],
297                |row| {
298                    Ok(SymbolRef {
299                        name: row.get(0)?,
300                        file: row.get(1)?,
301                        line: row.get(2)?,
302                        end_line: row.get(3)?,
303                    })
304                },
305            )
306            .ok()
307    }
308
309    /// Returns (files, symbols, edges) counts for `rinne graph stats`.
310    pub fn stats(&self) -> (usize, usize, usize) {
311        let count = |sql: &str| -> usize {
312            self.conn
313                .query_row(sql, [], |row| row.get::<_, i64>(0))
314                .unwrap_or(0) as usize
315        };
316        (
317            count("SELECT COUNT(*) FROM graph_files"),
318            count("SELECT COUNT(*) FROM graph_symbols"),
319            count("SELECT COUNT(*) FROM graph_edges"),
320        )
321    }
322
323    /// Returns all symbols defined in a given file.
324    pub fn symbols_in(&self, path: &str) -> Vec<Symbol> {
325        self.conn
326            .prepare(
327                "SELECT id, file, name, kind, start_line, end_line, signature, container
328                 FROM graph_symbols WHERE file = ?1",
329            )
330            .and_then(|mut stmt| {
331                stmt.query_map([path], |row| {
332                    let kind_str: String = row.get(3)?;
333                    let kind = SymbolKind::from_str(&kind_str).unwrap_or(SymbolKind::Function);
334                    Ok(Symbol {
335                        id: row.get(0)?,
336                        file: row.get(1)?,
337                        name: row.get(2)?,
338                        kind,
339                        start_line: row.get(4)?,
340                        end_line: row.get(5)?,
341                        signature: row.get(6)?,
342                        container: row.get(7)?,
343                    })
344                })
345                .and_then(|rows| rows.collect::<rusqlite::Result<Vec<_>>>())
346            })
347            .unwrap_or_default()
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    fn mem_store() -> Store {
356        let conn = rusqlite::Connection::open_in_memory().unwrap();
357        crate::schema::init_graph_schema(&conn).unwrap();
358        Store {
359            conn,
360            root: std::env::temp_dir(),
361        }
362    }
363
364    #[test]
365    fn index_then_query_neighborhood() {
366        let store = mem_store();
367        let src = "fn helper() {}\nfn main() { helper(); }\n";
368        store.index_file("src/main.rs", src, 0).unwrap();
369
370        let nb = store.neighborhood("helper").expect("helper indexed");
371        assert_eq!(nb.definition.name, "helper");
372        assert!(nb.callers.iter().any(|c| c.name == "main"));
373        assert!(!nb.stale);
374    }
375
376    #[test]
377    fn is_current_tracks_content_hash() {
378        let store = mem_store();
379        let src = "fn a() {}\n";
380        store.index_file("a.rs", src, 0).unwrap();
381        assert!(store.is_current("a.rs", src));
382        assert!(!store.is_current("a.rs", "fn a() {}\nfn b() {}\n"));
383    }
384
385    #[test]
386    fn reindex_replaces_prior_symbols() {
387        let store = mem_store();
388        store.index_file("a.rs", "fn a() {}\n", 0).unwrap();
389        store.index_file("a.rs", "fn c() {}\n", 1).unwrap();
390        assert!(store.neighborhood("a").is_none());
391        assert!(store.neighborhood("c").is_some());
392    }
393
394    #[test]
395    fn reindex_handles_path_with_quote() {
396        let store = mem_store();
397        let path = "weird'name.rs";
398        store.index_file(path, "fn first_sym() {}\n", 0).unwrap();
399        store.index_file(path, "fn second_sym() {}\n", 1).unwrap();
400        assert!(
401            store.neighborhood("first_sym").is_none(),
402            "old symbol must be gone after reindex"
403        );
404        assert!(
405            store.neighborhood("second_sym").is_some(),
406            "new symbol must exist after reindex"
407        );
408    }
409
410    // REPRODUCTION (Stage 1 bug): two symbols named `build` in different files.
411    // `neighborhood("build")` today returns exactly one arbitrary definition
412    // (WHERE name = ?1 LIMIT 1, no ORDER BY) and silently drops the other — so
413    // the assembler can anchor a worker's context on the WRONG `build`.
414    //
415    // This test asserts the *fix's* contract: given the caller's file hint, the
416    // store can resolve to the RIGHT `build`. It exercises `resolve_in_file`,
417    // which already filters by file and is the primitive Stage 1 wires into the
418    // assembler. It should PASS today (proving the primitive exists) — the gap is
419    // that `neighborhood` ignores it. See the companion `neighborhood`-level
420    // assertion below for the part that FAILS today.
421    #[test]
422    fn resolve_in_file_disambiguates_same_name_across_files() {
423        let store = mem_store();
424        store
425            .index_file(
426                "assembler.rs",
427                "fn build() {}\nfn assemble() { build(); }\n",
428                0,
429            )
430            .unwrap();
431        store
432            .index_file(
433                "blackboard.rs",
434                "fn build() {}\nfn open() { build(); }\n",
435                0,
436            )
437            .unwrap();
438
439        let in_assembler = store
440            .resolve_in_file("assembler.rs", "build")
441            .expect("build exists in assembler.rs");
442        assert_eq!(in_assembler.file, "assembler.rs");
443
444        let in_blackboard = store
445            .resolve_in_file("blackboard.rs", "build")
446            .expect("build exists in blackboard.rs");
447        assert_eq!(in_blackboard.file, "blackboard.rs");
448    }
449
450    // STAGE 1 FIX VERIFIED: with two `build` defs indexed, `neighborhood_all`
451    // surfaces BOTH definitions' files, ordered deterministically. The singular
452    // `neighborhood` still returns one (the first in order) for callers that want
453    // a single best-effort result.
454    #[test]
455    fn neighborhood_surfaces_all_same_name_definitions() {
456        let store = mem_store();
457        store
458            .index_file("assembler.rs", "fn build() {}\n", 0)
459            .unwrap();
460        store
461            .index_file("blackboard.rs", "fn build() {}\n", 0)
462            .unwrap();
463
464        let all = store.neighborhood_all("build");
465        let mut files: Vec<&str> = all.iter().map(|n| n.definition.file.as_str()).collect();
466        files.sort_unstable();
467        assert_eq!(
468            files,
469            vec!["assembler.rs", "blackboard.rs"],
470            "neighborhood_all must surface BOTH build definitions, not collapse to one"
471        );
472
473        // Deterministic order: ORDER BY file, start_line → assembler.rs first.
474        assert_eq!(all.first().unwrap().definition.file, "assembler.rs");
475
476        // Singular form still works, returning the first in order.
477        assert_eq!(
478            store.neighborhood("build").unwrap().definition.file,
479            "assembler.rs"
480        );
481    }
482
483    // ===== STAGE 2 (within-file duplicate-name collapse) =====
484    //
485    // `index_file` builds a `name_to_id` HashMap with last-write-wins
486    // (store.rs, "Last-write-wins for duplicate names within one file") and the
487    // resolver closure uses `unwrap_or(0)`. Two symbols with the SAME name in the
488    // SAME file therefore collapse: the first symbol's id is overwritten, so
489    // edges that should point at the first are mis-attributed to the second (or
490    // aliased to a bogus id). This is distinct from the Stage 1 cross-file case.
491    //
492    // Ignored until Stage 2: the fix is to key symbols by (name, start_line) or a
493    // real per-symbol id so same-name-same-file defs stay distinct.
494    // CORRECTED SCOPE: symbols never collapse — graph_symbols.id is AUTOINCREMENT,
495    // so distinct rows get distinct ids regardless of the name_to_id HashMap. The
496    // real Stage 2 defect is EDGE ATTRIBUTION: `name_to_id` is last-write-wins per
497    // file (store.rs), so a call to a name with two same-file definitions resolves
498    // to whichever won the map — both callers attach to ONE build, not each to its
499    // own. This test targets that edge property directly.
500    //
501    // `#[ignore]` with the real assertion below: it FAILS today (edges mis-attribute)
502    // and is the true Stage 2 red spec. The symbol-distinctness part is kept as a
503    // separate always-run assertion since it already holds.
504    #[test]
505    fn same_name_symbols_in_one_file_get_distinct_ids() {
506        let store = mem_store();
507        let src = "\
508fn build() {}
509mod second { pub fn build() {} }
510";
511        store.index_file("dup.rs", src, 0).unwrap();
512        let builds: Vec<_> = store
513            .symbols_in("dup.rs")
514            .into_iter()
515            .filter(|s| s.name == "build")
516            .collect();
517        // This ALREADY holds (AUTOINCREMENT) — proves symbols themselves don't collapse.
518        assert_eq!(builds.len(), 2, "both `build` symbols indexed");
519        assert_ne!(builds[0].id, builds[1].id, "distinct rows get distinct ids");
520    }
521
522    #[test]
523    fn same_name_defs_in_one_file_get_correct_edge_attribution() {
524        let store = mem_store();
525        // Two `build` in one file, each with its own exclusive caller.
526        let src = "\
527fn build() {}
528fn caller_one() { build(); }
529mod second { pub fn build() {} pub fn caller_two() { build(); } }
530";
531        store.index_file("dup.rs", src, 0).unwrap();
532
533        let builds: Vec<_> = store
534            .symbols_in("dup.rs")
535            .into_iter()
536            .filter(|s| s.name == "build")
537            .collect();
538        assert_eq!(builds.len(), 2);
539
540        // Each `build` should have exactly its own caller. Today the HashMap
541        // collapse routes both callers to one build (so one has 2 callers, the
542        // other 0) — this assertion catches that mis-attribution.
543        let nbs = store.neighborhood_all("build");
544        let caller_counts: Vec<usize> = nbs.iter().map(|n| n.callers.len()).collect();
545        assert!(
546            caller_counts.iter().all(|&c| c == 1),
547            "each same-file `build` must own exactly its caller, got caller counts {caller_counts:?} \
548             (last-write-wins mis-attribution)"
549        );
550    }
551
552    // ===== STAGE 3 (qualified identity via `container`) =====
553    //
554    // The STRUCTURAL fix: a symbol today is (file, name, kind) with NO container,
555    // so `ContextAssembler::build` and `Blackboard::build` are indistinguishable
556    // except by file — and within one file, not at all. Stage 3 adds a `container`
557    // column (enclosing impl/class/trait) so a symbol has a qualified identity.
558    //
559    // This test asserts the fix's contract: `symbols_in` surfaces a `container`
560    // for a method inside an `impl`. It FAILS/does-not-compile until the schema +
561    // extractor carry `container`, hence ignored and written against the future
562    // shape. Left as the executable spec for Stage 3.
563    #[test]
564    fn method_carries_its_impl_container() {
565        let store = mem_store();
566        // `build` is a method on `ContextAssembler`; its container must be recorded.
567        let src = "\
568struct ContextAssembler;
569impl ContextAssembler {
570    fn build(&self) {}
571}
572";
573        store.index_file("assembler.rs", src, 0).unwrap();
574
575        let build = store
576            .symbols_in("assembler.rs")
577            .into_iter()
578            .find(|s| s.name == "build")
579            .expect("build method indexed");
580
581        // Stage 3 contract: the method carries its enclosing impl type.
582        assert_eq!(
583            build.container.as_deref(),
584            Some("ContextAssembler"),
585            "method `build` must record its container `ContextAssembler`"
586        );
587        assert!(
588            build.signature.as_deref().unwrap_or("").contains("build"),
589            "placeholder: strengthen to assert container == \"ContextAssembler\" once \
590             the container column is added"
591        );
592    }
593
594    #[test]
595    fn neighborhood_reports_stale_when_file_changed_on_disk() {
596        let dir = std::env::temp_dir().join(format!("rinne-stale-{}", std::process::id()));
597        std::fs::create_dir_all(&dir).unwrap();
598        let file = dir.join("m.rs");
599        std::fs::write(&file, "fn helper() {}\nfn main() { helper(); }\n").unwrap();
600
601        let store = Store::open(&dir.join("state.db"), &dir).unwrap();
602        let src = std::fs::read_to_string(&file).unwrap();
603        store.index_file("m.rs", &src, 0).unwrap();
604
605        // Fresh: not stale.
606        assert!(!store.neighborhood("helper").unwrap().stale);
607
608        // Mutate the file on disk without reindexing.
609        std::fs::write(&file, "fn helper() {}\nfn main() { helper(); helper(); }\n").unwrap();
610        assert!(
611            store.neighborhood("helper").unwrap().stale,
612            "must report stale after on-disk edit"
613        );
614
615        let _ = std::fs::remove_dir_all(&dir);
616    }
617}