Skip to main content

lean_ctx/core/property_graph/
mod.rs

1//! Property Graph Engine — SQLite-backed code knowledge graph.
2//!
3//! Stores nodes (File, Symbol, Module) and edges (imports, calls, defines,
4//! exports) extracted by `deep_queries` + `import_resolver`.  Provides
5//! efficient traversal queries for impact analysis, architecture discovery,
6//! and graph-driven context loading.
7
8mod cross_source;
9mod edge;
10pub mod file_catalog;
11mod meta;
12pub mod node;
13mod path_id;
14mod queries;
15mod schema;
16pub mod semantic_cache;
17pub(crate) mod served;
18pub mod snapshot;
19mod sync;
20
21pub use edge::{Edge, EdgeKind};
22pub use file_catalog::FileCatalogEntry;
23pub use meta::{PropertyGraphMetaV1, load_meta, load_meta_from_dir, meta_path, write_meta};
24pub use node::{Node, NodeKind};
25pub use queries::{
26    DependencyChain, GraphQuery, ImpactResult, Served, edge_weight, file_connectivity,
27    related_files,
28};
29pub use semantic_cache::CachedResolution;
30pub use served::GraphSource;
31pub use sync::{mirror_index, parse_symbol_metadata, populate_from_project_index};
32
33use rusqlite::Connection;
34use std::path::{Path, PathBuf};
35
36/// Resolve the directory for graph.db and graph.meta.json.
37///
38/// Uses `$LEAN_CTX_DATA_DIR/graphs/<project_hash>/` (consistent with
39/// `ProjectIndex::index_dir`).  Falls back to `<project>/.lean-ctx/`
40/// only when the global data directory cannot be resolved.
41pub fn graph_dir(project_root: &str) -> PathBuf {
42    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
43        let normalized = crate::core::graph_index::normalize_project_root(project_root);
44        let hash = crate::core::project_hash::hash_project_root(&normalized);
45        data_dir.join("graphs").join(hash)
46    } else {
47        Path::new(project_root).join(".lean-ctx")
48    }
49}
50
51/// Transparently migrate graph.db and graph.meta.json from the old
52/// per-project `.lean-ctx/` directory to the new `$DATA_DIR/graphs/` path.
53fn migrate_if_needed(project_root: &str, new_dir: &Path) {
54    let old_dir = Path::new(project_root).join(".lean-ctx");
55    if old_dir == new_dir {
56        return;
57    }
58    for file in &["graph.db", "graph.meta.json"] {
59        let old = old_dir.join(file);
60        let new = new_dir.join(file);
61        if old.exists()
62            && !new.exists()
63            && std::fs::rename(&old, &new).is_err()
64            && std::fs::copy(&old, &new).is_ok()
65        {
66            let _ = std::fs::remove_file(&old);
67        }
68    }
69}
70
71/// Property-graph engine generation. Bump whenever edge extraction changes
72/// (e.g. the `type_ref` edges that connect C#/Java same-namespace consumers to
73/// their definers, GH #398) so an existing graph built by an older engine is
74/// transparently rebuilt on the next query instead of being served without the
75/// new edges. Graphs whose `graph.meta.json` predates this stamp deserialize to
76/// engine version `0`, so the first query after an upgrade rebuilds once.
77///
78/// History:
79/// - `2`: `type_ref` edges added to the `ctx_impact` builder (v3.8.3).
80/// - `3`: `type_ref` edges moved into the durable `graph_index` mirror so a
81///   background reindex can no longer wipe the C# blast radius (GH #398); every
82///   graph stamped by an engine that predates the mirror fix must rebuild.
83/// - `4`: same-package `type_ref` edges extended to Go (directory-scoped) and
84///   Kotlin (GH #398 bug class); graphs built before they existed must rebuild.
85/// - `5`: PropertyGraph file paths use interned IDs; pre-ID databases rebuild.
86/// - `6`: `calls` edges carry typed evidence and are no longer guessed (the
87///   `ctx_impact` builder bound ambiguous callees to the alphabetically first
88///   definition); graphs holding unannotated guessed edges must rebuild.
89/// - `7`: `calls` edges bind only within the caller's language family (a Rust
90///   call no longer lands on a same-named shell function); graphs holding
91///   such cross-language edges must rebuild.
92/// - `8`: path calls (`crate::config_io::write(..)`) bind to the file their
93///   own module path names; graphs built without those `calls` edges must
94///   rebuild.
95/// - `9`: Rust `import`/`module` edges come from the structural module-tree
96///   resolver (gh-2269), in the index mirror and the `ctx_impact` builder
97///   alike; graphs holding the old string-guessed Rust edges must rebuild.
98pub const GRAPH_ENGINE_VERSION: u32 = 9;
99
100/// `true` when the persisted graph was built by another engine generation than
101/// [`GRAPH_ENGINE_VERSION`] — older, NEWER, or before the version stamp existed
102/// (missing or unreadable meta) — and must therefore be rebuilt before its
103/// edges can be trusted. A newer stamp is what an installation finds after a
104/// rollback to an earlier release: that graph holds edges this engine's rules
105/// did not produce and cannot interpret, so it is rebuilt, not read. Callers
106/// pair this with a node-count check: an empty graph is rebuilt regardless; a
107/// non-empty graph of another generation is rebuilt by this gate.
108pub fn engine_outdated(project_root: &str) -> bool {
109    load_meta(project_root).is_none_or(|m| m.engine_version != GRAPH_ENGINE_VERSION)
110}
111
112/// How long a status read waits for a graph another process holds locked.
113const STORED_COUNTS_BUSY: std::time::Duration = std::time::Duration::from_millis(250);
114
115/// Row counts of a persisted graph, read for status reporting only.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub struct StoredCounts {
118    /// Rows of the file catalog: the files the graph index holds.
119    pub files: u64,
120    /// Rows of the node table.
121    pub nodes: u64,
122}
123
124/// What `project_root`'s persisted graph holds, without serving anything
125/// from it (#2179). Status readers (`doctor`, `index status`) used to
126/// rebuild the whole index through the serving surface just to count its
127/// files — a source check per catalogued file — and to open the store
128/// through [`CodeGraph::open`], which migrates and creates schema. This
129/// opens the existing `graph.db` only (never creates it), reads no schema
130/// it would change (`query_only`), and waits at most `STORED_COUNTS_BUSY`
131/// for a lock another process holds: `None` when there is no graph, its
132/// schema is not this engine's, or it stays busy.
133pub fn stored_counts(project_root: &str) -> Option<StoredCounts> {
134    let db_path = graph_dir(project_root).join("graph.db");
135    if !db_path.is_file() {
136        return None;
137    }
138    stored_counts_at(&db_path, STORED_COUNTS_BUSY)
139}
140
141fn stored_counts_at(db_path: &Path, busy: std::time::Duration) -> Option<StoredCounts> {
142    use rusqlite::OpenFlags;
143    let conn = Connection::open_with_flags(
144        db_path,
145        OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX,
146    )
147    .ok()?;
148    conn.busy_timeout(busy).ok()?;
149    conn.execute_batch("PRAGMA query_only = ON;").ok()?;
150    let count = |table: &str| {
151        conn.query_row(&format!("SELECT count(*) FROM {table}"), [], |row| {
152            row.get::<_, i64>(0)
153        })
154        .ok()
155        .and_then(|n| u64::try_from(n).ok())
156    };
157    Some(StoredCounts {
158        files: count("file_catalog")?,
159        nodes: count("nodes")?,
160    })
161}
162
163/// Whether an open error is a transient SQLite lock (BUSY/LOCKED) that a brief
164/// retry can clear — notably the `PRAGMA journal_mode=WAL` and initial-DDL races
165/// that SQLite reports *without* invoking the busy handler (so `busy_timeout`
166/// does not cover them).
167fn is_transient_lock(err: &anyhow::Error) -> bool {
168    use rusqlite::ErrorCode;
169    if let Some(rusqlite::Error::SqliteFailure(e, _)) = err.downcast_ref::<rusqlite::Error>()
170        && matches!(e.code, ErrorCode::DatabaseBusy | ErrorCode::DatabaseLocked)
171    {
172        return true;
173    }
174    // The schema initializer may surface the same condition wrapped; match the
175    // full error chain's text as a fallback.
176    let msg = format!("{err:#}").to_ascii_lowercase();
177    msg.contains("database is locked") || msg.contains("table is locked")
178}
179
180pub struct CodeGraph {
181    conn: Connection,
182    db_path: PathBuf,
183    /// Serve-time source check of a graph opened for a project root
184    /// (`served`, G04); `None` for an in-memory graph.
185    gate: Option<served::GraphGate>,
186}
187
188impl CodeGraph {
189    pub fn open(project_root: &str) -> anyhow::Result<Self> {
190        let db_dir = graph_dir(project_root);
191        std::fs::create_dir_all(&db_dir)?;
192        migrate_if_needed(project_root, &db_dir);
193        let db_path = db_dir.join("graph.db");
194
195        // Concurrent opens race on `PRAGMA journal_mode=WAL` and the initial DDL,
196        // which SQLite reports as SQLITE_BUSY without invoking the busy handler
197        // (`busy_timeout` therefore does not apply). Deeper addon integration can
198        // have a gateway ingest thread and the main session's graph build open
199        // the same db at once (#1102); retry briefly so neither silently loses
200        // its writes. Once WAL is recorded in the file header, opens stop racing.
201        const MAX_ATTEMPTS: u32 = 12;
202        let mut attempt = 0;
203        loop {
204            attempt += 1;
205            match Self::try_open(&db_path) {
206                Ok(mut graph) => {
207                    graph.gate = Some(served::GraphGate::for_root(project_root));
208                    return Ok(graph);
209                }
210                Err(e) if attempt < MAX_ATTEMPTS && is_transient_lock(&e) => {
211                    std::thread::sleep(std::time::Duration::from_millis(40 * u64::from(attempt)));
212                }
213                Err(e) => return Err(e),
214            }
215        }
216    }
217
218    /// One open attempt: connect, register the busy handler, ensure the schema.
219    fn try_open(db_path: &Path) -> anyhow::Result<Self> {
220        let conn = Connection::open(db_path)?;
221        conn.busy_timeout(std::time::Duration::from_secs(5))?;
222        schema::initialize(&conn)?;
223        Ok(Self {
224            conn,
225            db_path: db_path.to_path_buf(),
226            gate: None,
227        })
228    }
229
230    pub fn open_in_memory() -> anyhow::Result<Self> {
231        let conn = Connection::open_in_memory()?;
232        schema::initialize(&conn)?;
233        Ok(Self {
234            conn,
235            db_path: PathBuf::from(":memory:"),
236            gate: None,
237        })
238    }
239
240    pub fn db_path(&self) -> &Path {
241        &self.db_path
242    }
243
244    pub fn connection(&self) -> &Connection {
245        &self.conn
246    }
247
248    pub fn upsert_node(&self, node: &Node) -> anyhow::Result<i64> {
249        node::upsert(&self.conn, node)
250    }
251
252    pub fn upsert_edge(&self, edge: &Edge) -> anyhow::Result<()> {
253        edge::upsert(&self.conn, edge)
254    }
255
256    pub fn get_node_by_path(&self, file_path: &str) -> anyhow::Result<Option<Node>> {
257        node::get_by_path(&self.conn, file_path)
258    }
259
260    pub fn get_node_by_symbol(&self, name: &str, file_path: &str) -> anyhow::Result<Option<Node>> {
261        node::get_by_symbol(&self.conn, name, file_path)
262    }
263
264    pub fn remove_file_nodes(&self, file_path: &str) -> anyhow::Result<()> {
265        node::remove_by_file(&self.conn, file_path)
266    }
267
268    pub fn edges_from(&self, node_id: i64) -> anyhow::Result<Vec<Edge>> {
269        edge::from_node(&self.conn, node_id)
270    }
271
272    pub fn edges_to(&self, node_id: i64) -> anyhow::Result<Vec<Edge>> {
273        edge::to_node(&self.conn, node_id)
274    }
275
276    // The five queries below run under this graph's serve-time source check
277    // (`served`, G04): a file that is not served now is neither returned nor
278    // walked through, and contributes no weight, count or rank slot.
279
280    pub fn dependents(&self, file_path: &str) -> anyhow::Result<Vec<String>> {
281        Ok(self.served_neighbours(file_path, queries::dependents(&self.conn, file_path)?))
282    }
283
284    pub fn dependencies(&self, file_path: &str) -> anyhow::Result<Vec<String>> {
285        Ok(self.served_neighbours(file_path, queries::dependencies(&self.conn, file_path)?))
286    }
287
288    pub fn impact_analysis(
289        &self,
290        file_path: &str,
291        max_depth: usize,
292    ) -> anyhow::Result<ImpactResult> {
293        queries::impact_analysis(&self.conn, file_path, max_depth, &|path: &str| {
294            self.serves_file(path)
295        })
296    }
297
298    pub fn dependency_chain(
299        &self,
300        from: &str,
301        to: &str,
302    ) -> anyhow::Result<Option<DependencyChain>> {
303        queries::dependency_chain(&self.conn, from, to, &|path: &str| self.serves_file(path))
304    }
305
306    pub fn related_files(
307        &self,
308        file_path: &str,
309        limit: usize,
310    ) -> anyhow::Result<Vec<(String, f64)>> {
311        queries::related_files(&self.conn, file_path, limit, &|path: &str| {
312            self.serves_file(path)
313        })
314    }
315
316    pub fn file_connectivity(
317        &self,
318        file_path: &str,
319    ) -> anyhow::Result<std::collections::HashMap<String, (usize, usize)>> {
320        queries::file_connectivity(&self.conn, file_path, &|path: &str| self.serves_file(path))
321    }
322
323    pub fn node_count(&self) -> anyhow::Result<usize> {
324        node::count(&self.conn)
325    }
326
327    pub fn edge_count(&self) -> anyhow::Result<usize> {
328        edge::count(&self.conn)
329    }
330
331    /// Cached semantic answer for a call site, if the caller is unchanged and
332    /// every file the answer derives from — the caller and each target — is
333    /// served now (`semantic_cache::lookup_served`, G04). A withheld answer
334    /// is a miss: the backend is asked again.
335    pub fn semantic_lookup(
336        &self,
337        site: semantic_cache::SiteKey<'_>,
338        caller_hash: &str,
339    ) -> anyhow::Result<Option<CachedResolution>> {
340        semantic_cache::lookup_served(&self.conn, site, caller_hash, |file| self.serves_file(file))
341    }
342
343    /// Keeps a semantic answer when its persisted text passes storage
344    /// admission under `admission` — one policy snapshot per enrichment run,
345    /// taken where the run starts, not per row. `Ok(false)`: admission
346    /// refused the row and nothing was written.
347    pub fn semantic_store(
348        &self,
349        site: semantic_cache::SiteKey<'_>,
350        caller_hash: &str,
351        value: &CachedResolution,
352        admission: &crate::core::context_admission::stores::StoreAdmission,
353    ) -> anyhow::Result<bool> {
354        semantic_cache::store_admitted(&self.conn, site, caller_hash, value, admission)
355    }
356
357    /// Whether a semantic backend has answered for this graph at all.
358    pub fn has_semantic_answers(&self) -> anyhow::Result<bool> {
359        semantic_cache::any(&self.conn)
360    }
361
362    /// Removes cached answers for vanished or changed caller files.
363    pub fn semantic_prune(
364        &self,
365        live_hashes: &std::collections::HashMap<String, String>,
366    ) -> anyhow::Result<usize> {
367        semantic_cache::prune(&self.conn, live_hashes)
368    }
369
370    /// File→file edges of `kind` with their metadata, as
371    /// `(source path, target path, metadata)` — sorted for determinism.
372    pub fn file_edges_of_kind(
373        &self,
374        kind: &EdgeKind,
375    ) -> anyhow::Result<Vec<(String, String, Option<String>)>> {
376        edge::file_edges_of_kind(&self.conn, kind)
377    }
378
379    /// Upserts an edge carrying typed evidence. The incoming producer's
380    /// contribution replaces only its own earlier one; other producers'
381    /// contributions on the same edge are kept
382    /// ([`crate::core::semantic::EdgeEvidence::merge`]).
383    pub fn upsert_edge_with_evidence(
384        &self,
385        source_id: i64,
386        target_id: i64,
387        kind: &EdgeKind,
388        evidence: &crate::core::semantic::EdgeEvidence,
389    ) -> anyhow::Result<()> {
390        use crate::core::semantic::EdgeEvidence;
391        self.atomically(|| {
392            let existing = edge::metadata_of(&self.conn, source_id, target_id, kind)?;
393            let merged = EdgeEvidence::merge(
394                EdgeEvidence::from_metadata(existing.as_deref()),
395                evidence.clone(),
396            );
397            edge::upsert(
398                &self.conn,
399                &Edge::new(source_id, target_id, kind.clone()).with_metadata(&merged.to_metadata()),
400            )
401        })
402    }
403
404    /// Runs a read-modify-write as one unit. Another process (daemon vs. MCP
405    /// server) may update the same edge concurrently; `BEGIN IMMEDIATE` takes
406    /// the write lock before the read, so no contribution is lost. Inside an
407    /// outer transaction that one already provides atomicity.
408    fn atomically<T>(&self, f: impl FnOnce() -> anyhow::Result<T>) -> anyhow::Result<T> {
409        if !self.conn.is_autocommit() {
410            return f();
411        }
412        self.conn.execute_batch("BEGIN IMMEDIATE")?;
413        let outcome = f().and_then(|value| {
414            self.conn.execute_batch("COMMIT")?;
415            Ok(value)
416        });
417        // A failed body *or* a failed COMMIT must not leave the connection
418        // inside a transaction: the next call would see !is_autocommit, skip
419        // BEGIN and never commit, while holding the writer lock.
420        if outcome.is_err() && !self.conn.is_autocommit() {
421            let _ = self.conn.execute_batch("ROLLBACK");
422        }
423        outcome
424    }
425
426    /// Withdraws `origin`'s contribution from the file→file edge
427    /// `source → target`: the edge is deleted only when no other producer
428    /// still derives it. Edges without typed evidence are left untouched.
429    pub fn withdraw_file_edge(
430        &self,
431        source: &str,
432        target: &str,
433        kind: &EdgeKind,
434        origin: crate::core::semantic::EvidenceOrigin,
435    ) -> anyhow::Result<()> {
436        use crate::core::semantic::EdgeEvidence;
437        let (Some(s), Some(t)) = (
438            self.get_node_by_path(source)?.and_then(|n| n.id),
439            self.get_node_by_path(target)?.and_then(|n| n.id),
440        ) else {
441            return Ok(());
442        };
443        self.atomically(|| {
444            let existing = edge::metadata_of(&self.conn, s, t, kind)?;
445            let Some(evidence) = EdgeEvidence::from_metadata(existing.as_deref()) else {
446                return Ok(());
447            };
448            if !evidence.has(origin) {
449                return Ok(());
450            }
451            match evidence.without(origin) {
452                Some(rest) => edge::upsert(
453                    &self.conn,
454                    &Edge::new(s, t, kind.clone()).with_metadata(&rest.to_metadata()),
455                ),
456                None => edge::remove_file_edge(&self.conn, source, target, kind),
457            }
458        })
459    }
460
461    /// Persist a cross-source edge (code file ↔ external source URI) into the
462    /// dedicated `cross_source_edges` table. Keeps the higher weight on conflict
463    /// so repeated provider ingests don't downgrade an established link (#682).
464    pub fn upsert_cross_source_edge(
465        &self,
466        from: &str,
467        to: &str,
468        kind: &str,
469        weight: f32,
470    ) -> anyhow::Result<()> {
471        cross_source::upsert(&self.conn, from, to, kind, weight)
472    }
473
474    /// All cross-source edges as `IndexEdge`s, ready for `cross_source_hints`.
475    pub fn all_cross_source_edges(&self) -> Vec<crate::core::graph_index::IndexEdge> {
476        cross_source::all(&self.conn).unwrap_or_default()
477    }
478
479    pub fn cross_source_edge_count(&self) -> anyhow::Result<usize> {
480        cross_source::count(&self.conn)
481    }
482
483    /// Delete every cross-source edge of a given `kind`. Used by the code-health
484    /// fabric to replace its `health_hotspot` edges on each pass so resolved
485    /// hotspots never persist as stale hints. Returns the number removed.
486    pub fn delete_cross_source_edges_by_kind(&self, kind: &str) -> anyhow::Result<usize> {
487        cross_source::delete_by_kind(&self.conn, kind)
488    }
489
490    /// Delete every cross-source edge with an end under the URI `prefix`
491    /// (both directions), so a re-indexed source replaces its own edges.
492    pub fn delete_cross_source_edges_with_uri_prefix(&self, prefix: &str) -> anyhow::Result<usize> {
493        cross_source::delete_with_uri_prefix(&self.conn, prefix)
494    }
495
496    pub fn clear(&self) -> anyhow::Result<()> {
497        self.conn.execute_batch(
498            "DELETE FROM edges; DELETE FROM nodes; DELETE FROM file_catalog; DELETE FROM paths; \
499             DELETE FROM cross_source_edges;",
500        )?;
501        Ok(())
502    }
503
504    /// Clear only the code graph (nodes, edges, file catalog), preserving
505    /// provider `cross_source_edges`. Used by the graph_index→PG mirror (#682.1)
506    /// so rebuilding the code graph never drops lateral provider hints, which
507    /// live in their own table and are repopulated on a separate ingest cycle.
508    pub fn clear_code_graph(&self) -> anyhow::Result<()> {
509        self.conn.execute_batch(
510            "DELETE FROM edges; DELETE FROM nodes; DELETE FROM file_catalog; DELETE FROM paths;",
511        )?;
512        Ok(())
513    }
514
515    pub fn upsert_file_catalog(&self, entry: &FileCatalogEntry) -> anyhow::Result<()> {
516        file_catalog::upsert(&self.conn, entry)
517    }
518
519    pub fn get_file_catalog(&self, path: &str) -> anyhow::Result<Option<FileCatalogEntry>> {
520        file_catalog::get(&self.conn, path)
521    }
522
523    pub fn file_catalog_count(&self) -> anyhow::Result<usize> {
524        file_catalog::count(&self.conn)
525    }
526
527    pub fn file_catalog_paths(&self) -> anyhow::Result<Vec<String>> {
528        file_catalog::all_paths(&self.conn)
529    }
530
531    pub fn find_symbols(
532        &self,
533        name: &str,
534        file_filter: Option<&str>,
535        kind_filter: Option<&str>,
536    ) -> anyhow::Result<Vec<Node>> {
537        node::find_symbols(&self.conn, name, file_filter, kind_filter)
538    }
539
540    /// Files that define a symbol named exactly `name` (GH #398 symbol-name
541    /// `ctx_impact analyze` fallback). Backed by `node::resolve_symbol_def_files`.
542    pub fn resolve_symbol_def_files(&self, name: &str) -> anyhow::Result<Vec<String>> {
543        node::resolve_symbol_def_files(&self.conn, name)
544    }
545
546    pub fn symbol_count(&self) -> anyhow::Result<usize> {
547        node::symbol_count(&self.conn)
548    }
549
550    /// Count of `file` nodes (accurate on both builder paths). Backed by
551    /// `node::file_count`.
552    pub fn file_node_count(&self) -> anyhow::Result<usize> {
553        node::file_count(&self.conn)
554    }
555
556    /// Every symbol node with its line span (unfiltered). Backend for the
557    /// call-graph symbol table after the `graph_index` teardown (#696).
558    pub fn all_symbols(&self) -> anyhow::Result<Vec<Node>> {
559        node::all_symbols(&self.conn)
560    }
561
562    pub fn all_edges_flat(&self) -> anyhow::Result<Vec<(String, String, String, f64)>> {
563        node::all_edges_flat(&self.conn)
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570    use crate::core::data_dir::test_env_lock;
571
572    fn test_graph() -> CodeGraph {
573        CodeGraph::open_in_memory().unwrap()
574    }
575
576    #[test]
577    fn create_and_query_nodes() {
578        let g = test_graph();
579
580        let id = g.upsert_node(&Node::file("src/main.rs")).unwrap();
581        assert!(id > 0);
582
583        let found = g.get_node_by_path("src/main.rs").unwrap();
584        assert!(found.is_some());
585        assert_eq!(found.unwrap().file_path, "src/main.rs");
586    }
587
588    #[test]
589    fn create_and_query_edges() {
590        let g = test_graph();
591
592        let a = g.upsert_node(&Node::file("src/a.rs")).unwrap();
593        let b = g.upsert_node(&Node::file("src/b.rs")).unwrap();
594
595        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
596
597        let from_a = g.edges_from(a).unwrap();
598        assert_eq!(from_a.len(), 1);
599        assert_eq!(from_a[0].target_id, b);
600
601        let to_b = g.edges_to(b).unwrap();
602        assert_eq!(to_b.len(), 1);
603        assert_eq!(to_b[0].source_id, a);
604    }
605
606    #[test]
607    fn dependents_query() {
608        let g = test_graph();
609
610        let main = g.upsert_node(&Node::file("src/main.rs")).unwrap();
611        let lib = g.upsert_node(&Node::file("src/lib.rs")).unwrap();
612        let utils = g.upsert_node(&Node::file("src/utils.rs")).unwrap();
613
614        g.upsert_edge(&Edge::new(main, lib, EdgeKind::Imports))
615            .unwrap();
616        g.upsert_edge(&Edge::new(utils, lib, EdgeKind::Imports))
617            .unwrap();
618
619        let deps = g.dependents("src/lib.rs").unwrap();
620        assert_eq!(deps.len(), 2);
621        assert!(deps.contains(&"src/main.rs".to_string()));
622        assert!(deps.contains(&"src/utils.rs".to_string()));
623    }
624
625    #[test]
626    fn dependencies_query() {
627        let g = test_graph();
628
629        let main = g.upsert_node(&Node::file("src/main.rs")).unwrap();
630        let lib = g.upsert_node(&Node::file("src/lib.rs")).unwrap();
631        let config = g.upsert_node(&Node::file("src/config.rs")).unwrap();
632
633        g.upsert_edge(&Edge::new(main, lib, EdgeKind::Imports))
634            .unwrap();
635        g.upsert_edge(&Edge::new(main, config, EdgeKind::Imports))
636            .unwrap();
637
638        let deps = g.dependencies("src/main.rs").unwrap();
639        assert_eq!(deps.len(), 2);
640    }
641
642    #[test]
643    #[allow(clippy::many_single_char_names)] // graph test nodes: a, b, c, d, e
644    fn impact_analysis_depth() {
645        let g = test_graph();
646
647        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
648        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
649        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
650        let d = g.upsert_node(&Node::file("d.rs")).unwrap();
651
652        g.upsert_edge(&Edge::new(b, a, EdgeKind::Imports)).unwrap();
653        g.upsert_edge(&Edge::new(c, b, EdgeKind::Imports)).unwrap();
654        g.upsert_edge(&Edge::new(d, c, EdgeKind::Imports)).unwrap();
655
656        let impact = g.impact_analysis("a.rs", 2).unwrap();
657        assert!(impact.affected_files.contains(&"b.rs".to_string()));
658        assert!(impact.affected_files.contains(&"c.rs".to_string()));
659        assert!(!impact.affected_files.contains(&"d.rs".to_string()));
660
661        let deep = g.impact_analysis("a.rs", 10).unwrap();
662        assert!(deep.affected_files.contains(&"d.rs".to_string()));
663    }
664
665    /// Weighted propagation is exact and separates name-match-only reach:
666    /// a heavier path found later still propagates, and a guess on a pair
667    /// never lends its weight to that pair's evidence-backed edge.
668    #[test]
669    #[allow(clippy::many_single_char_names)] // graph test nodes
670    fn impact_propagates_the_heaviest_path_and_marks_guess_only_reach() {
671        use crate::core::semantic::{EdgeEvidence, EvidenceGrade, EvidenceOrigin};
672        let g = test_graph();
673        let id = |p: &str| g.upsert_node(&Node::file(p)).unwrap();
674        let (a, b, c, x, y, z) = (id("a"), id("b"), id("c"), id("x"), id("y"), id("z"));
675        let edge = |from, to, kind| g.upsert_edge(&Edge::new(from, to, kind)).unwrap();
676        // b → a: a name-match call guess (0.8 × 0.5 = 0.4) plus a fact
677        // (sibling, 0.25); c → b: co-change (0.35). Over all edges c gets
678        // 0.4 × 0.35 = 0.14, over facts only 0.25 × 0.35 < 0.1.
679        let guess = EdgeEvidence::new(
680            EvidenceGrade::HeuristicStructural,
681            EvidenceOrigin::Enrichment,
682            None,
683            1,
684        );
685        g.upsert_edge_with_evidence(b, a, &EdgeKind::Calls, &guess)
686            .unwrap();
687        edge(b, a, EdgeKind::Sibling);
688        edge(c, b, EdgeKind::Cochange);
689        // x is first reached lightly (sibling, 0.25), then fully via y at
690        // depth 2; only the full weight carries on to z (0.35).
691        edge(x, a, EdgeKind::Sibling);
692        edge(y, a, EdgeKind::Imports);
693        edge(x, y, EdgeKind::Imports);
694        edge(z, x, EdgeKind::Cochange);
695
696        let impact = g.impact_analysis("a", 5).unwrap();
697        assert_eq!(impact.affected_files, ["b", "c", "x", "y", "z"]);
698        assert_eq!(impact.weak_files, ["c"]);
699        assert_eq!(impact.max_depth_reached, 3);
700    }
701
702    #[test]
703    fn upsert_idempotent() {
704        let g = test_graph();
705
706        let id1 = g.upsert_node(&Node::file("src/main.rs")).unwrap();
707        let id2 = g.upsert_node(&Node::file("src/main.rs")).unwrap();
708        assert_eq!(id1, id2);
709        assert_eq!(g.node_count().unwrap(), 1);
710    }
711
712    #[test]
713    fn remove_file_cascades() {
714        let g = test_graph();
715
716        let a = g.upsert_node(&Node::file("src/a.rs")).unwrap();
717        let b = g.upsert_node(&Node::file("src/b.rs")).unwrap();
718        let sym = g
719            .upsert_node(&Node::symbol("MyStruct", "src/a.rs", NodeKind::Symbol))
720            .unwrap();
721
722        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
723        g.upsert_edge(&Edge::new(sym, b, EdgeKind::Calls)).unwrap();
724
725        g.remove_file_nodes("src/a.rs").unwrap();
726
727        assert!(g.get_node_by_path("src/a.rs").unwrap().is_none());
728        assert_eq!(g.edge_count().unwrap(), 0);
729    }
730
731    #[test]
732    fn dependency_chain_found() {
733        let g = test_graph();
734
735        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
736        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
737        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
738
739        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
740        g.upsert_edge(&Edge::new(b, c, EdgeKind::Imports)).unwrap();
741
742        let chain = g.dependency_chain("a.rs", "c.rs").unwrap();
743        assert!(chain.is_some());
744        let chain = chain.unwrap();
745        assert_eq!(chain.path, vec!["a.rs", "b.rs", "c.rs"]);
746    }
747
748    #[test]
749    fn counts() {
750        let g = test_graph();
751        assert_eq!(g.node_count().unwrap(), 0);
752        assert_eq!(g.edge_count().unwrap(), 0);
753
754        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
755        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
756        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
757
758        assert_eq!(g.node_count().unwrap(), 2);
759        assert_eq!(g.edge_count().unwrap(), 1);
760    }
761
762    #[test]
763    fn multi_edge_dependents() {
764        let g = test_graph();
765
766        let a = g.upsert_node(&Node::file("src/a.rs")).unwrap();
767        let b = g.upsert_node(&Node::file("src/b.rs")).unwrap();
768        let c = g.upsert_node(&Node::file("src/c.rs")).unwrap();
769
770        g.upsert_edge(&Edge::new(b, a, EdgeKind::Imports)).unwrap();
771        g.upsert_edge(&Edge::new(c, a, EdgeKind::Calls)).unwrap();
772
773        let deps = g.dependents("src/a.rs").unwrap();
774        assert_eq!(deps.len(), 2);
775        assert!(deps.contains(&"src/b.rs".to_string()));
776        assert!(deps.contains(&"src/c.rs".to_string()));
777    }
778
779    #[test]
780    fn multi_edge_impact_analysis() {
781        let g = test_graph();
782
783        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
784        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
785        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
786
787        g.upsert_edge(&Edge::new(b, a, EdgeKind::Imports)).unwrap();
788        g.upsert_edge(&Edge::new(c, b, EdgeKind::Calls)).unwrap();
789
790        let impact = g.impact_analysis("a.rs", 10).unwrap();
791        assert!(impact.affected_files.contains(&"b.rs".to_string()));
792        assert!(impact.affected_files.contains(&"c.rs".to_string()));
793    }
794
795    #[test]
796    fn related_files_scored() {
797        let g = test_graph();
798
799        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
800        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
801        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
802
803        g.upsert_edge(&Edge::new(a, b, EdgeKind::Imports)).unwrap();
804        g.upsert_edge(&Edge::new(a, b, EdgeKind::Calls)).unwrap();
805        g.upsert_edge(&Edge::new(a, c, EdgeKind::TypeRef)).unwrap();
806
807        let related = g.related_files("a.rs", 10).unwrap();
808        assert_eq!(related.len(), 2);
809        let b_score = related.iter().find(|(p, _)| p == "b.rs").unwrap().1;
810        let c_score = related.iter().find(|(p, _)| p == "c.rs").unwrap().1;
811        assert!(
812            b_score > c_score,
813            "b.rs has imports+calls, should rank higher than c.rs with type_ref"
814        );
815    }
816
817    /// The same call relationship stored at file and symbol granularity must
818    /// count once (at its strongest evidence), and a name-only guess must not
819    /// outrank a verified relationship.
820    #[test]
821    fn related_files_counts_each_relationship_once_weighted_by_evidence() {
822        use crate::core::semantic::{EdgeEvidence, EvidenceGrade, EvidenceOrigin};
823        let g = test_graph();
824        let a = g.upsert_node(&Node::file("a.rs")).unwrap();
825        let b = g.upsert_node(&Node::file("b.rs")).unwrap();
826        let c = g.upsert_node(&Node::file("c.rs")).unwrap();
827        let evidence = |grade| EdgeEvidence::new(grade, EvidenceOrigin::Enrichment, None, 1);
828
829        // a→b: one verified call, also mirrored by three symbol→symbol edges.
830        g.upsert_edge_with_evidence(
831            a,
832            b,
833            &EdgeKind::Calls,
834            &evidence(EvidenceGrade::VerifiedSemantic),
835        )
836        .unwrap();
837        for i in 0..3 {
838            let caller = g
839                .upsert_node(&Node::symbol(&format!("f{i}"), "a.rs", NodeKind::Symbol))
840                .unwrap();
841            let callee = g
842                .upsert_node(&Node::symbol(&format!("g{i}"), "b.rs", NodeKind::Symbol))
843                .unwrap();
844            g.upsert_edge_with_evidence(
845                caller,
846                callee,
847                &EdgeKind::Calls,
848                &evidence(EvidenceGrade::ResolvedStructural),
849            )
850            .unwrap();
851        }
852        // a→c: a heuristic name match only.
853        g.upsert_edge_with_evidence(
854            a,
855            c,
856            &EdgeKind::Calls,
857            &evidence(EvidenceGrade::HeuristicStructural),
858        )
859        .unwrap();
860
861        let related = g.related_files("a.rs", 10).unwrap();
862        let score = |p: &str| related.iter().find(|(f, _)| f == p).unwrap().1;
863        assert!(
864            (score("b.rs") - edge_weight("calls")).abs() < 1e-9,
865            "counted once"
866        );
867        assert!(score("b.rs") > score("c.rs"), "verified outranks heuristic");
868    }
869
870    #[test]
871    fn graph_dir_uses_data_dir_when_set() {
872        let tmp = tempfile::tempdir().unwrap();
873        let project = tmp.path().join("myproject");
874        std::fs::create_dir_all(&project).unwrap();
875
876        let data_dir = tmp.path().join("data");
877        std::fs::create_dir_all(&data_dir).unwrap();
878
879        let _guard = test_env_lock();
880        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.to_str().unwrap());
881
882        let dir = graph_dir(project.to_str().unwrap());
883        assert!(dir.starts_with(&data_dir));
884        assert!(dir.to_string_lossy().contains("graphs"));
885
886        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
887    }
888
889    #[test]
890    fn graph_dir_returns_consistent_hash_dir() {
891        let tmp = tempfile::tempdir().unwrap();
892        let project = tmp.path().join("hash_project");
893        std::fs::create_dir_all(&project).unwrap();
894
895        let data_dir = tmp.path().join("data2");
896        std::fs::create_dir_all(&data_dir).unwrap();
897
898        let _guard = test_env_lock();
899        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.to_str().unwrap());
900
901        let dir1 = graph_dir(project.to_str().unwrap());
902        let dir2 = graph_dir(project.to_str().unwrap());
903        assert_eq!(dir1, dir2, "graph_dir should be deterministic");
904        assert!(dir1.to_string_lossy().contains("graphs"));
905
906        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
907    }
908
909    #[test]
910    fn migration_moves_old_files() {
911        let tmp = tempfile::tempdir().unwrap();
912        let project = tmp.path().join("migtest");
913        let old_dir = project.join(".lean-ctx");
914        std::fs::create_dir_all(&old_dir).unwrap();
915        std::fs::write(old_dir.join("graph.db"), b"old-db-content").unwrap();
916        std::fs::write(old_dir.join("graph.meta.json"), b"old-meta").unwrap();
917
918        let new_dir = tmp.path().join("newloc");
919        std::fs::create_dir_all(&new_dir).unwrap();
920
921        migrate_if_needed(project.to_str().unwrap(), &new_dir);
922
923        assert!(new_dir.join("graph.db").exists());
924        assert!(new_dir.join("graph.meta.json").exists());
925        assert!(!old_dir.join("graph.db").exists());
926        assert!(!old_dir.join("graph.meta.json").exists());
927        assert_eq!(
928            std::fs::read_to_string(new_dir.join("graph.db")).unwrap(),
929            "old-db-content"
930        );
931    }
932
933    #[test]
934    fn migration_skips_when_new_exists() {
935        let tmp = tempfile::tempdir().unwrap();
936        let project = tmp.path().join("skiptest");
937        let old_dir = project.join(".lean-ctx");
938        std::fs::create_dir_all(&old_dir).unwrap();
939        std::fs::write(old_dir.join("graph.db"), b"old").unwrap();
940
941        let new_dir = tmp.path().join("newloc2");
942        std::fs::create_dir_all(&new_dir).unwrap();
943        std::fs::write(new_dir.join("graph.db"), b"already-there").unwrap();
944
945        migrate_if_needed(project.to_str().unwrap(), &new_dir);
946
947        assert_eq!(
948            std::fs::read_to_string(new_dir.join("graph.db")).unwrap(),
949            "already-there"
950        );
951        assert!(old_dir.join("graph.db").exists());
952    }
953
954    #[test]
955    fn open_with_data_dir() {
956        let tmp = tempfile::tempdir().unwrap();
957        let project = tmp.path().join("opentest");
958        std::fs::create_dir_all(&project).unwrap();
959
960        let data_dir = tmp.path().join("xdata");
961        std::fs::create_dir_all(&data_dir).unwrap();
962
963        let _guard = test_env_lock();
964        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.to_str().unwrap());
965
966        let g = CodeGraph::open(project.to_str().unwrap()).unwrap();
967        assert!(g.db_path().starts_with(&data_dir));
968        assert!(g.db_path().to_string_lossy().contains("graph.db"));
969
970        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
971    }
972
973    #[test]
974    fn meta_path_uses_graph_dir() {
975        let tmp = tempfile::tempdir().unwrap();
976        let project = tmp.path().join("metatest");
977        std::fs::create_dir_all(&project).unwrap();
978
979        let data_dir = tmp.path().join("mdata");
980        std::fs::create_dir_all(&data_dir).unwrap();
981
982        let _guard = test_env_lock();
983        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.to_str().unwrap());
984
985        let mp = meta::meta_path(project.to_str().unwrap());
986        assert!(mp.starts_with(&data_dir));
987        assert!(mp.to_string_lossy().contains("graph.meta.json"));
988
989        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
990    }
991
992    #[test]
993    fn engine_outdated_flags_old_and_missing_meta() {
994        let _iso = crate::core::data_dir::isolated_data_dir();
995        let proj = tempfile::tempdir().unwrap();
996        let root = proj.path().to_str().unwrap();
997
998        // No meta on disk yet -> outdated (an unbuilt graph forces a build).
999        assert!(engine_outdated(root), "missing meta must read as outdated");
1000
1001        // Meta from an engine generation before the version stamp -> outdated.
1002        let mut meta = PropertyGraphMetaV1 {
1003            built_at: "2026-01-01T00:00:00Z".to_string(),
1004            engine_version: 0,
1005            ..Default::default()
1006        };
1007        write_meta(root, &meta).unwrap();
1008        assert!(
1009            engine_outdated(root),
1010            "engine_version 0 must read as outdated"
1011        );
1012
1013        // Meta stamped with the current engine -> up to date.
1014        meta.engine_version = GRAPH_ENGINE_VERSION;
1015        write_meta(root, &meta).unwrap();
1016        assert!(
1017            !engine_outdated(root),
1018            "current engine_version must read as up to date"
1019        );
1020
1021        // Meta stamped by a later engine (the state after a rollback) -> rebuilt.
1022        meta.engine_version = GRAPH_ENGINE_VERSION + 1;
1023        write_meta(root, &meta).unwrap();
1024        assert!(
1025            engine_outdated(root),
1026            "a graph of a newer engine must not be read by this one"
1027        );
1028    }
1029
1030    fn catalog_entry(path: &str) -> FileCatalogEntry {
1031        FileCatalogEntry {
1032            path: path.to_string(),
1033            hash: format!("hash-{path}"),
1034            language: "rs".to_string(),
1035            line_count: 1,
1036            token_count: 1,
1037            exports: Vec::new(),
1038            summary: String::new(),
1039        }
1040    }
1041
1042    /// #2179: a status read counts what the store holds, never creates a
1043    /// graph that is not there.
1044    #[test]
1045    fn stored_counts_reads_rows_and_never_creates_a_graph() {
1046        let _iso = crate::core::data_dir::isolated_data_dir();
1047        let proj = tempfile::tempdir().unwrap();
1048        let root = proj.path().to_str().unwrap();
1049
1050        assert_eq!(stored_counts(root), None);
1051        assert!(
1052            !graph_dir(root).join("graph.db").exists(),
1053            "a status read must not create graph.db"
1054        );
1055
1056        let g = CodeGraph::open(root).unwrap();
1057        g.upsert_file_catalog(&catalog_entry("src/a.rs")).unwrap();
1058        g.upsert_file_catalog(&catalog_entry("src/b.rs")).unwrap();
1059        g.upsert_node(&Node::file("src/a.rs")).unwrap();
1060        drop(g);
1061
1062        assert_eq!(
1063            stored_counts(root),
1064            Some(StoredCounts { files: 2, nodes: 1 })
1065        );
1066    }
1067
1068    /// #2179: a graph another process holds locked is answered within the
1069    /// busy bound instead of waited out.
1070    #[test]
1071    fn stored_counts_gives_up_on_a_held_graph_within_its_bound() {
1072        let dir = tempfile::tempdir().unwrap();
1073        let db = dir.path().join("graph.db");
1074        {
1075            let conn = Connection::open(&db).unwrap();
1076            schema::initialize(&conn).unwrap();
1077        }
1078        assert_eq!(
1079            stored_counts_at(&db, STORED_COUNTS_BUSY),
1080            Some(StoredCounts { files: 0, nodes: 0 })
1081        );
1082
1083        let holder = Connection::open(&db).unwrap();
1084        holder
1085            .execute_batch(
1086                "PRAGMA locking_mode = EXCLUSIVE;
1087                 BEGIN EXCLUSIVE;
1088                 INSERT INTO paths(path) VALUES ('held');",
1089            )
1090            .unwrap();
1091
1092        let started = std::time::Instant::now();
1093        let busy = std::time::Duration::from_millis(100);
1094        assert_eq!(stored_counts_at(&db, busy), None, "a held graph is busy");
1095        assert!(
1096            started.elapsed() < std::time::Duration::from_secs(5),
1097            "waited {:?} on a held graph",
1098            started.elapsed()
1099        );
1100        holder.execute_batch("ROLLBACK;").unwrap();
1101    }
1102
1103    /// #2179: reading a graph of an older schema reports nothing and leaves
1104    /// it as it is; `CodeGraph::open` would drop its tables.
1105    #[test]
1106    fn stored_counts_leaves_a_legacy_schema_untouched() {
1107        let dir = tempfile::tempdir().unwrap();
1108        let db = dir.path().join("graph.db");
1109        {
1110            let conn = Connection::open(&db).unwrap();
1111            conn.execute_batch(
1112                "CREATE TABLE nodes (id INTEGER PRIMARY KEY, file_path TEXT);
1113                 INSERT INTO nodes(file_path) VALUES ('src/a.rs');",
1114            )
1115            .unwrap();
1116        }
1117        assert_eq!(stored_counts_at(&db, STORED_COUNTS_BUSY), None);
1118        let conn = Connection::open(&db).unwrap();
1119        let kept: i64 = conn
1120            .query_row("SELECT count(*) FROM nodes", [], |r| r.get(0))
1121            .unwrap();
1122        assert_eq!(kept, 1, "the legacy table must survive a status read");
1123    }
1124}