1use std::path::Path;
16use std::sync::Mutex;
17
18use rusqlite::Connection;
19
20use crate::error::Result;
21use crate::graph::recall::smart_recall;
22use crate::graph::schema::{init_graph_schema, migrate_graph, schema_version};
23use crate::graph::search::{query_nodes, search_nodes};
24use crate::graph::store::{
25 append_edge, delete_edge, delete_node, edges_for_node, remove_edges_for_node, upsert_node,
26};
27use crate::graph::traversal::related_nodes;
28use crate::graph::types::{EdgeDirection, GraphEdge, GraphNode, ScoredNode};
29
30pub trait GraphBackend: Send + Sync {
36 fn upsert_node(&self, node: &GraphNode) -> Result<()>;
38 fn read_node(&self, id: &str) -> Result<Option<GraphNode>>;
40 fn delete_node(&self, id: &str) -> Result<bool>;
42 fn search_nodes(&self, query: &str, limit: usize) -> Result<Vec<GraphNode>>;
44 #[allow(clippy::too_many_arguments)]
46 fn query_nodes(
47 &self,
48 tag: Option<&str>,
49 node_type: Option<&str>,
50 project: Option<&str>,
51 limit: usize,
52 ) -> Result<Vec<GraphNode>>;
53 fn smart_recall(
56 &self,
57 project: Option<&str>,
58 hint: Option<&str>,
59 limit: usize,
60 ) -> Result<Vec<ScoredNode>>;
61 fn related_nodes(&self, start_id: &str, depth: usize) -> Result<Vec<String>>;
64 fn append_edge(&self, edge: &GraphEdge) -> Result<()>;
66 fn append_edges(&self, edges: &[GraphEdge]) -> Result<()> {
73 for edge in edges {
74 self.append_edge(edge)?;
75 }
76 Ok(())
77 }
78 fn edges_for_node_dir(
83 &self,
84 node_id: &str,
85 dir: EdgeDirection,
86 relation: Option<&str>,
87 ) -> Result<Vec<GraphEdge>> {
88 Ok(self
89 .edges_for_node(node_id)?
90 .into_iter()
91 .filter(|e| match dir {
92 EdgeDirection::Out => e.source == node_id,
93 EdgeDirection::In => e.target == node_id,
94 EdgeDirection::Both => true,
95 })
96 .filter(|e| relation.is_none_or(|r| e.relation == r))
97 .collect())
98 }
99 fn neighbors_weighted(
103 &self,
104 seed_ids: &[String],
105 dir: EdgeDirection,
106 relation: Option<&str>,
107 ) -> Result<Vec<(String, f64)>> {
108 let mut weights: std::collections::HashMap<String, f64> = std::collections::HashMap::new();
109 let seed_set: std::collections::HashSet<&str> =
110 seed_ids.iter().map(String::as_str).collect();
111 for seed in seed_ids {
112 for e in self.edges_for_node_dir(seed, dir, relation)? {
113 let other = if e.source == *seed {
114 &e.target
115 } else {
116 &e.source
117 };
118 if !seed_set.contains(other.as_str()) {
119 *weights.entry(other.clone()).or_default() += e.weight;
120 }
121 }
122 }
123 let mut result: Vec<(String, f64)> = weights.into_iter().collect();
124 result.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
125 Ok(result)
126 }
127 fn related_nodes_filtered(
131 &self,
132 start_id: &str,
133 depth: usize,
134 dir: EdgeDirection,
135 relation: Option<&str>,
136 ) -> Result<Vec<String>> {
137 if depth == 0 {
138 return Ok(vec![]);
139 }
140 let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
141 visited.insert(start_id.to_string());
142 let mut frontier: Vec<String> = vec![start_id.to_string()];
143 for _ in 0..depth {
144 let mut next: Vec<String> = Vec::new();
145 for node in &frontier {
146 for (nb, _) in self.neighbors_weighted(std::slice::from_ref(node), dir, relation)? {
147 if visited.insert(nb.clone()) {
148 next.push(nb);
149 }
150 }
151 }
152 if next.is_empty() {
153 break;
154 }
155 frontier = next;
156 }
157 visited.remove(start_id);
158 Ok(visited.into_iter().collect())
159 }
160 fn edges_for_node(&self, node_id: &str) -> Result<Vec<GraphEdge>>;
162 fn delete_edge(&self, id: &str) -> Result<bool>;
164 fn remove_edges_for_node(&self, node_id: &str) -> Result<()>;
166
167 fn current_version(&self) -> Result<u32>;
169 fn migrate(&self) -> Result<u32>;
172}
173
174pub struct SqliteGraph {
179 conn: Mutex<Connection>,
180}
181
182impl SqliteGraph {
183 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
185 let conn = open_with_schema(path.as_ref())?;
186 Ok(Self {
187 conn: Mutex::new(conn),
188 })
189 }
190
191 pub fn open_in_memory() -> Result<Self> {
193 let conn = Connection::open_in_memory().map_err(store_err)?;
194 init_graph_schema(&conn)?;
195 let current = schema_version(&conn)?;
196 migrate_graph(&conn, current)?;
197 Ok(Self {
198 conn: Mutex::new(conn),
199 })
200 }
201
202 fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
204 self.conn.lock().unwrap_or_else(|e| e.into_inner())
205 }
206}
207
208fn open_with_schema(path: &Path) -> Result<Connection> {
210 let conn = Connection::open(path).map_err(store_err)?;
211 init_graph_schema(&conn)?;
212 let current = schema_version(&conn)?;
213 migrate_graph(&conn, current)?;
214 Ok(conn)
215}
216
217fn store_err(e: rusqlite::Error) -> crate::error::KernelError {
218 crate::error::KernelError::Store(e.to_string())
219}
220
221impl GraphBackend for SqliteGraph {
222 fn upsert_node(&self, node: &GraphNode) -> Result<()> {
223 let c = self.lock();
224 upsert_node(&c, node)
225 }
226
227 fn read_node(&self, id: &str) -> Result<Option<GraphNode>> {
228 let c = self.lock();
229 crate::graph::store::read_node(&c, id)
230 }
231
232 fn delete_node(&self, id: &str) -> Result<bool> {
233 let c = self.lock();
234 delete_node(&c, id)
235 }
236
237 fn search_nodes(&self, query: &str, limit: usize) -> Result<Vec<GraphNode>> {
238 let c = self.lock();
239 search_nodes(&c, query, limit)
240 }
241
242 fn query_nodes(
243 &self,
244 tag: Option<&str>,
245 node_type: Option<&str>,
246 project: Option<&str>,
247 limit: usize,
248 ) -> Result<Vec<GraphNode>> {
249 let c = self.lock();
250 query_nodes(&c, tag, node_type, project, limit)
251 }
252
253 fn smart_recall(
254 &self,
255 project: Option<&str>,
256 hint: Option<&str>,
257 limit: usize,
258 ) -> Result<Vec<ScoredNode>> {
259 let c = self.lock();
260 smart_recall(&c, project, hint, limit)
261 }
262
263 fn related_nodes(&self, start_id: &str, depth: usize) -> Result<Vec<String>> {
264 let c = self.lock();
265 Ok(related_nodes(&c, start_id, depth))
266 }
267
268 fn append_edge(&self, edge: &GraphEdge) -> Result<()> {
269 let c = self.lock();
270 append_edge(&c, edge)
271 }
272
273 fn append_edges(&self, edges: &[GraphEdge]) -> Result<()> {
274 let c = self.lock();
275 crate::graph::store::append_edges(&c, edges)
276 }
277
278 fn edges_for_node_dir(
279 &self,
280 node_id: &str,
281 dir: EdgeDirection,
282 relation: Option<&str>,
283 ) -> Result<Vec<GraphEdge>> {
284 let c = self.lock();
285 crate::graph::store::edges_for_node_dir(&c, node_id, dir, relation)
286 }
287
288 fn neighbors_weighted(
289 &self,
290 seed_ids: &[String],
291 dir: EdgeDirection,
292 relation: Option<&str>,
293 ) -> Result<Vec<(String, f64)>> {
294 let c = self.lock();
295 Ok(crate::graph::traversal::neighbors_weighted(
296 &c, seed_ids, dir, relation,
297 ))
298 }
299
300 fn edges_for_node(&self, node_id: &str) -> Result<Vec<GraphEdge>> {
301 let c = self.lock();
302 edges_for_node(&c, node_id)
303 }
304
305 fn delete_edge(&self, id: &str) -> Result<bool> {
306 let c = self.lock();
307 delete_edge(&c, id)
308 }
309
310 fn remove_edges_for_node(&self, node_id: &str) -> Result<()> {
311 let c = self.lock();
312 remove_edges_for_node(&c, node_id)
313 }
314
315 fn current_version(&self) -> Result<u32> {
316 let c = self.lock();
317 schema_version(&c)
318 }
319
320 fn migrate(&self) -> Result<u32> {
321 let c = self.lock();
322 let current = schema_version(&c)?;
323 migrate_graph(&c, current)
324 }
325}
326
327#[cfg(feature = "graph-cjk")]
329impl SqliteGraph {
330 pub fn search_nodes_cjk(&self, query: &str, limit: usize) -> Result<Vec<GraphNode>> {
335 let c = self.lock();
336 crate::graph::cjk::search_nodes_cjk(&c, query, limit)
337 }
338
339 pub fn segment_cjk(text: &str) -> String {
342 crate::graph::cjk::segment_cjk(text)
343 }
344}
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349
350 fn sample_node(id: &str) -> GraphNode {
351 GraphNode {
352 id: id.to_string(),
353 node_type: "concept".to_string(),
354 title: format!("Node {id}"),
355 body: "graph backend test body".to_string(),
356 tags: vec!["backend".to_string()],
357 projects: vec![],
358 agents: vec![],
359 created: "2026-01-01T00:00:00Z".to_string(),
360 updated: "2026-01-01T00:00:00Z".to_string(),
361 importance: 0.5,
362 access_count: 0,
363 accessed_at: String::new(),
364 }
365 }
366
367 #[test]
370 fn dyn_backend_round_trips_node() {
371 let backend: Box<dyn GraphBackend> = Box::new(SqliteGraph::open_in_memory().unwrap());
372 assert!(backend.read_node("n1").unwrap().is_none());
373 backend.upsert_node(&sample_node("n1")).unwrap();
374 let loaded = backend.read_node("n1").unwrap().unwrap();
375 assert_eq!(loaded.title, "Node n1");
376 assert_eq!(loaded.tags, vec!["backend".to_string()]);
377 assert!(backend.delete_node("n1").unwrap());
378 assert!(backend.read_node("n1").unwrap().is_none());
379 }
380
381 #[test]
383 fn fresh_backend_reports_current_version() {
384 let backend = SqliteGraph::open_in_memory().unwrap();
385 assert_eq!(
386 backend.current_version().unwrap(),
387 crate::graph::schema::GRAPH_SCHEMA_VERSION
388 );
389 }
390
391 #[test]
393 fn backend_search_finds_node() {
394 let backend = SqliteGraph::open_in_memory().unwrap();
395 backend.upsert_node(&sample_node("rust")).unwrap();
396 let hits = backend.search_nodes("graph backend", 10).unwrap();
397 assert_eq!(hits.len(), 1);
398 assert_eq!(hits[0].id, "rust");
399 }
400
401 #[test]
403 fn backend_smart_recall_finds_relevant() {
404 let backend = SqliteGraph::open_in_memory().unwrap();
405 let mut n = sample_node("rust");
406 n.body = "rust ownership borrow checker".to_string();
407 backend.upsert_node(&n).unwrap();
408 let recalled = backend.smart_recall(None, Some("ownership"), 5).unwrap();
409 assert!(recalled.iter().any(|s| s.node.id == "rust"));
410 }
411
412 #[test]
414 fn backend_related_nodes_traverses_edges() {
415 let backend = SqliteGraph::open_in_memory().unwrap();
416 backend.upsert_node(&sample_node("a")).unwrap();
417 backend.upsert_node(&sample_node("b")).unwrap();
418 backend
419 .append_edge(&GraphEdge {
420 id: "e1".into(),
421 source: "a".into(),
422 target: "b".into(),
423 relation: "related".into(),
424 weight: 1.0,
425 ts: "2026-01-01T00:00:00Z".into(),
426 })
427 .unwrap();
428 let related = backend.related_nodes("a", 2).unwrap();
429 assert!(related.contains(&"b".to_string()));
430 }
431
432 #[test]
435 fn dyn_backend_batch_and_filtered_edges() {
436 let backend: Box<dyn GraphBackend> = Box::new(SqliteGraph::open_in_memory().unwrap());
437 backend
438 .append_edges(&[
439 GraphEdge {
440 id: "e1".into(),
441 source: "a".into(),
442 target: "b".into(),
443 relation: "cites".into(),
444 weight: 1.0,
445 ts: "t".into(),
446 },
447 GraphEdge {
448 id: "e2".into(),
449 source: "c".into(),
450 target: "a".into(),
451 relation: "cites".into(),
452 weight: 1.0,
453 ts: "t".into(),
454 },
455 GraphEdge {
456 id: "e3".into(),
457 source: "a".into(),
458 target: "d".into(),
459 relation: "see_also".into(),
460 weight: 1.0,
461 ts: "t".into(),
462 },
463 ])
464 .unwrap();
465 assert_eq!(
467 backend
468 .edges_for_node_dir("a", EdgeDirection::Out, None)
469 .unwrap()
470 .len(),
471 2
472 );
473 let nbs = backend
475 .neighbors_weighted(&["a".to_string()], EdgeDirection::Out, Some("cites"))
476 .unwrap();
477 let ids: Vec<&str> = nbs.iter().map(|(id, _)| id.as_str()).collect();
478 assert_eq!(ids, vec!["b"]);
479 let rel = backend
481 .related_nodes_filtered("a", 2, EdgeDirection::Out, None)
482 .unwrap();
483 assert!(rel.contains(&"b".to_string()));
484 assert!(rel.contains(&"d".to_string()));
485 }
486}