Skip to main content

talos_memory/
graph.rs

1//! Weighted associative memory graph (T43, MEM-008 Phase 1).
2//!
3//! Additive graph tables in the existing `talos-memory` SQLite store. Nodes
4//! represent memory elements; edges represent typed associations with weights.
5//! Retrieval is explicit and bounded — no automatic prompt injection (T31
6//! decision: default-off).
7
8use std::collections::{HashMap, HashSet};
9
10use chrono::{DateTime, Utc};
11use rusqlite::{Connection, OptionalExtension, params};
12use serde::{Deserialize, Serialize};
13
14use crate::MemoryStoreError;
15
16const DECAY_HALF_LIFE_DAYS: f64 = 7.0;
17const DEFAULT_MAX_HOPS: usize = 3;
18const DEFAULT_MIN_EDGE_WEIGHT: f64 = 0.3;
19const DEFAULT_FANOUT: usize = 10;
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct GraphNode {
23    pub id: String,
24    pub kind: String,
25    pub label: String,
26    pub impression_strength: f64,
27    pub weight: f64,
28    pub created_at: DateTime<Utc>,
29    pub last_accessed_at: DateTime<Utc>,
30    pub access_count: i64,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct GraphEdge {
35    pub source_id: String,
36    pub target_id: String,
37    pub relation_type: String,
38    pub weight: f64,
39    pub created_at: DateTime<Utc>,
40    pub last_reinforced_at: DateTime<Utc>,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct AssociationResult {
45    pub node: GraphNode,
46    pub score: f64,
47    pub path: Vec<String>,
48    pub hop_count: usize,
49}
50
51pub(crate) fn migrate_graph(conn: &Connection) -> Result<(), MemoryStoreError> {
52    conn.execute_batch(
53        r#"
54        CREATE TABLE IF NOT EXISTS memory_graph_nodes (
55            id TEXT PRIMARY KEY,
56            kind TEXT NOT NULL,
57            label TEXT NOT NULL,
58            impression_strength REAL NOT NULL DEFAULT 1.0,
59            weight REAL NOT NULL DEFAULT 1.0,
60            created_at TEXT NOT NULL,
61            last_accessed_at TEXT NOT NULL,
62            access_count INTEGER NOT NULL DEFAULT 0
63        );
64
65        CREATE TABLE IF NOT EXISTS memory_graph_edges (
66            source_id TEXT NOT NULL,
67            target_id TEXT NOT NULL,
68            relation_type TEXT NOT NULL,
69            weight REAL NOT NULL,
70            created_at TEXT NOT NULL,
71            last_reinforced_at TEXT NOT NULL,
72            PRIMARY KEY (source_id, target_id, relation_type),
73            FOREIGN KEY (source_id) REFERENCES memory_graph_nodes(id),
74            FOREIGN KEY (target_id) REFERENCES memory_graph_nodes(id)
75        );
76
77        CREATE INDEX IF NOT EXISTS idx_graph_edges_source
78            ON memory_graph_edges(source_id);
79        CREATE INDEX IF NOT EXISTS idx_graph_edges_target
80            ON memory_graph_edges(target_id);
81        "#,
82    )?;
83    Ok(())
84}
85
86pub(crate) fn upsert_node(conn: &Connection, node: &GraphNode) -> Result<(), MemoryStoreError> {
87    conn.execute(
88        "INSERT INTO memory_graph_nodes (id, kind, label, impression_strength, weight, created_at, last_accessed_at, access_count)
89         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
90         ON CONFLICT(id) DO UPDATE SET
91            label = excluded.label,
92            impression_strength = excluded.impression_strength,
93            weight = excluded.weight,
94            last_accessed_at = excluded.last_accessed_at,
95            access_count = excluded.access_count",
96        params![
97            node.id,
98            node.kind,
99            node.label,
100            node.impression_strength,
101            node.weight,
102            node.created_at.to_rfc3339(),
103            node.last_accessed_at.to_rfc3339(),
104            node.access_count,
105        ],
106    )?;
107    Ok(())
108}
109
110pub(crate) fn upsert_edge(conn: &Connection, edge: &GraphEdge) -> Result<(), MemoryStoreError> {
111    conn.execute(
112        "INSERT INTO memory_graph_edges (source_id, target_id, relation_type, weight, created_at, last_reinforced_at)
113         VALUES (?1, ?2, ?3, ?4, ?5, ?6)
114         ON CONFLICT(source_id, target_id, relation_type) DO UPDATE SET
115            weight = excluded.weight,
116            last_reinforced_at = excluded.last_reinforced_at",
117        params![
118            edge.source_id,
119            edge.target_id,
120            edge.relation_type,
121            edge.weight,
122            edge.created_at.to_rfc3339(),
123            edge.last_reinforced_at.to_rfc3339(),
124        ],
125    )?;
126    Ok(())
127}
128
129pub(crate) fn get_node(conn: &Connection, id: &str) -> Result<Option<GraphNode>, MemoryStoreError> {
130    let mut stmt = conn.prepare(
131        "SELECT id, kind, label, impression_strength, weight, created_at, last_accessed_at, access_count
132         FROM memory_graph_nodes WHERE id = ?1",
133    )?;
134    let node = stmt
135        .query_row(params![id], |row| {
136            Ok(GraphNode {
137                id: row.get(0)?,
138                kind: row.get(1)?,
139                label: row.get(2)?,
140                impression_strength: row.get(3)?,
141                weight: row.get(4)?,
142                created_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(5)?)
143                    .map(|dt| dt.with_timezone(&Utc))
144                    .unwrap_or_else(|_| Utc::now()),
145                last_accessed_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(6)?)
146                    .map(|dt| dt.with_timezone(&Utc))
147                    .unwrap_or_else(|_| Utc::now()),
148                access_count: row.get(7)?,
149            })
150        })
151        .optional()?;
152    Ok(node)
153}
154
155fn load_all_nodes(conn: &Connection) -> Result<HashMap<String, GraphNode>, MemoryStoreError> {
156    let mut stmt = conn.prepare(
157        "SELECT id, kind, label, impression_strength, weight, created_at, last_accessed_at, access_count
158         FROM memory_graph_nodes",
159    )?;
160    let rows = stmt.query_map([], |row| {
161        Ok(GraphNode {
162            id: row.get(0)?,
163            kind: row.get(1)?,
164            label: row.get(2)?,
165            impression_strength: row.get(3)?,
166            weight: row.get(4)?,
167            created_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(5)?)
168                .map(|dt| dt.with_timezone(&Utc))
169                .unwrap_or_else(|_| Utc::now()),
170            last_accessed_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(6)?)
171                .map(|dt| dt.with_timezone(&Utc))
172                .unwrap_or_else(|_| Utc::now()),
173            access_count: row.get(7)?,
174        })
175    })?;
176    let mut nodes = HashMap::new();
177    for row in rows {
178        let node = row?;
179        nodes.insert(node.id.clone(), node);
180    }
181    Ok(nodes)
182}
183
184fn load_all_edges(conn: &Connection) -> Result<Vec<GraphEdge>, MemoryStoreError> {
185    let mut stmt = conn.prepare(
186        "SELECT source_id, target_id, relation_type, weight, created_at, last_reinforced_at
187         FROM memory_graph_edges",
188    )?;
189    let rows = stmt.query_map([], |row| {
190        Ok(GraphEdge {
191            source_id: row.get(0)?,
192            target_id: row.get(1)?,
193            relation_type: row.get(2)?,
194            weight: row.get(3)?,
195            created_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(4)?)
196                .map(|dt| dt.with_timezone(&Utc))
197                .unwrap_or_else(|_| Utc::now()),
198            last_reinforced_at: DateTime::parse_from_rfc3339(&row.get::<_, String>(5)?)
199                .map(|dt| dt.with_timezone(&Utc))
200                .unwrap_or_else(|_| Utc::now()),
201        })
202    })?;
203    let mut edges = Vec::new();
204    for row in rows {
205        edges.push(row?);
206    }
207    Ok(edges)
208}
209
210fn recency_decay(last_accessed: DateTime<Utc>, now: DateTime<Utc>) -> f64 {
211    let elapsed = (now - last_accessed).num_seconds() as f64 / 86400.0;
212    if elapsed <= 0.0 {
213        return 1.0;
214    }
215    0.5_f64.powf(elapsed / DECAY_HALF_LIFE_DAYS)
216}
217
218pub(crate) fn recall_associative(
219    conn: &Connection,
220    seed_node_ids: &[&str],
221    max_hops: usize,
222    min_edge_weight: f64,
223    fanout: usize,
224    now: DateTime<Utc>,
225) -> Result<Vec<AssociationResult>, MemoryStoreError> {
226    if seed_node_ids.is_empty() {
227        return Ok(Vec::new());
228    }
229
230    let hops = if max_hops == 0 {
231        DEFAULT_MAX_HOPS
232    } else {
233        max_hops
234    };
235    let min_w = if min_edge_weight <= 0.0 {
236        DEFAULT_MIN_EDGE_WEIGHT
237    } else {
238        min_edge_weight
239    };
240    let fan = if fanout == 0 { DEFAULT_FANOUT } else { fanout };
241
242    let nodes = load_all_nodes(conn)?;
243    let edges = load_all_edges(conn)?;
244
245    let mut adjacency: HashMap<&str, Vec<&GraphEdge>> = HashMap::new();
246    for edge in &edges {
247        adjacency.entry(&edge.source_id).or_default().push(edge);
248    }
249
250    let mut visited: HashSet<String> = HashSet::new();
251    let mut results: Vec<AssociationResult> = Vec::new();
252
253    for seed_id in seed_node_ids {
254        if let Some(_seed_node) = nodes.get(*seed_id) {
255            bfs_step(
256                seed_id,
257                1.0,
258                &mut Vec::new(),
259                &nodes,
260                &adjacency,
261                &mut visited,
262                &mut results,
263                hops,
264                min_w,
265                fan,
266                now,
267            );
268        }
269    }
270
271    results.sort_by(|a, b| {
272        b.score
273            .partial_cmp(&a.score)
274            .unwrap_or(std::cmp::Ordering::Equal)
275    });
276    results.dedup_by(|a, b| a.node.id == b.node.id);
277    Ok(results)
278}
279
280#[allow(clippy::too_many_arguments)]
281fn bfs_step(
282    current_id: &str,
283    current_activation: f64,
284    path: &mut Vec<String>,
285    nodes: &HashMap<String, GraphNode>,
286    adjacency: &HashMap<&str, Vec<&GraphEdge>>,
287    visited: &mut HashSet<String>,
288    results: &mut Vec<AssociationResult>,
289    remaining_hops: usize,
290    min_edge_weight: f64,
291    fanout: usize,
292    now: DateTime<Utc>,
293) {
294    if remaining_hops == 0 {
295        return;
296    }
297    if visited.contains(current_id) {
298        return;
299    }
300    visited.insert(current_id.to_string());
301
302    let neighbors = match adjacency.get(current_id) {
303        Some(n) => n,
304        None => return,
305    };
306
307    let mut scored: Vec<(&&GraphEdge, f64)> = neighbors
308        .iter()
309        .filter(|e| e.weight >= min_edge_weight)
310        .filter_map(|edge| {
311            let target = nodes.get(&edge.target_id)?;
312            let decay = recency_decay(target.last_accessed_at, now);
313            let score = current_activation * edge.weight * target.impression_strength * decay;
314            Some((edge, score))
315        })
316        .collect();
317
318    scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
319    scored.truncate(fanout);
320
321    path.push(current_id.to_string());
322
323    for (edge, score) in &scored {
324        if visited.contains(&edge.target_id) {
325            continue;
326        }
327        if let Some(target_node) = nodes.get(&edge.target_id) {
328            results.push(AssociationResult {
329                node: target_node.clone(),
330                score: *score,
331                path: path.clone(),
332                hop_count: path.len(),
333            });
334            bfs_step(
335                &edge.target_id,
336                *score,
337                path,
338                nodes,
339                adjacency,
340                visited,
341                results,
342                remaining_hops - 1,
343                min_edge_weight,
344                fanout,
345                now,
346            );
347        }
348    }
349
350    path.pop();
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use crate::MemoryStore;
357
358    fn make_node(id: &str, label: &str, strength: f64) -> GraphNode {
359        let now = Utc::now();
360        GraphNode {
361            id: id.to_string(),
362            kind: "entity".to_string(),
363            label: label.to_string(),
364            impression_strength: strength,
365            weight: 1.0,
366            created_at: now,
367            last_accessed_at: now,
368            access_count: 0,
369        }
370    }
371
372    fn make_edge(source: &str, target: &str, relation: &str, weight: f64) -> GraphEdge {
373        let now = Utc::now();
374        GraphEdge {
375            source_id: source.to_string(),
376            target_id: target.to_string(),
377            relation_type: relation.to_string(),
378            weight,
379            created_at: now,
380            last_reinforced_at: now,
381        }
382    }
383
384    #[test]
385    fn schema_migration_creates_graph_tables() {
386        let store = MemoryStore::open_memory().expect("test operation should succeed");
387        let count: i64 = store
388            .conn
389            .query_row(
390                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name LIKE 'memory_graph_%'",
391                [],
392                |row| row.get(0),
393            )
394            .expect("test operation should succeed");
395        assert!(count >= 2);
396    }
397
398    #[test]
399    fn upsert_and_get_node() {
400        let store = MemoryStore::open_memory().expect("test operation should succeed");
401        let node = make_node("n1", "WEB-005", 0.9);
402        store
403            .graph_upsert_node(&node)
404            .expect("test operation should succeed");
405        let retrieved = store
406            .graph_get_node("n1")
407            .expect("test operation should succeed")
408            .expect("test operation should succeed");
409        assert_eq!(retrieved.label, "WEB-005");
410        assert!((retrieved.impression_strength - 0.9).abs() < 0.01);
411    }
412
413    #[test]
414    fn upsert_node_is_idempotent() {
415        let store = MemoryStore::open_memory().expect("test operation should succeed");
416        store
417            .graph_upsert_node(&make_node("n1", "A", 0.5))
418            .expect("test operation should succeed");
419        store
420            .graph_upsert_node(&make_node("n1", "A-updated", 0.8))
421            .expect("test operation should succeed");
422        let node = store
423            .graph_get_node("n1")
424            .expect("test operation should succeed")
425            .expect("test operation should succeed");
426        assert_eq!(node.label, "A-updated");
427        assert!((node.impression_strength - 0.8).abs() < 0.01);
428    }
429
430    #[test]
431    fn upsert_edge_is_idempotent() {
432        let store = MemoryStore::open_memory().expect("test operation should succeed");
433        store
434            .graph_upsert_node(&make_node("n1", "A", 1.0))
435            .expect("test operation should succeed");
436        store
437            .graph_upsert_node(&make_node("n2", "B", 1.0))
438            .expect("test operation should succeed");
439        store
440            .graph_upsert_edge(&make_edge("n1", "n2", "used_with", 0.5))
441            .expect("test operation should succeed");
442        store
443            .graph_upsert_edge(&make_edge("n1", "n2", "used_with", 0.9))
444            .expect("test operation should succeed");
445        let results = store
446            .graph_recall(&["n1"], 3, 0.3, 10)
447            .expect("test operation should succeed");
448        assert_eq!(results.len(), 1);
449        assert!((results[0].score - 0.9).abs() < 0.15);
450    }
451
452    #[test]
453    fn recall_returns_direct_neighbors_sorted_by_score() {
454        let store = MemoryStore::open_memory().expect("test operation should succeed");
455        store
456            .graph_upsert_node(&make_node("seed", "seed", 1.0))
457            .expect("test operation should succeed");
458        store
459            .graph_upsert_node(&make_node("a", "A", 0.8))
460            .expect("test operation should succeed");
461        store
462            .graph_upsert_node(&make_node("b", "B", 0.4))
463            .expect("test operation should succeed");
464        store
465            .graph_upsert_edge(&make_edge("seed", "a", "used_with", 0.9))
466            .expect("test operation should succeed");
467        store
468            .graph_upsert_edge(&make_edge("seed", "b", "used_with", 0.5))
469            .expect("test operation should succeed");
470        let results = store
471            .graph_recall(&["seed"], 3, 0.3, 10)
472            .expect("test operation should succeed");
473        assert_eq!(results.len(), 2);
474        assert!(results[0].score > results[1].score);
475        assert_eq!(results[0].node.id, "a");
476    }
477
478    #[test]
479    fn recall_multi_hop_traverses_graph() {
480        let store = MemoryStore::open_memory().expect("test operation should succeed");
481        store
482            .graph_upsert_node(&make_node("a", "A", 1.0))
483            .expect("test operation should succeed");
484        store
485            .graph_upsert_node(&make_node("b", "B", 1.0))
486            .expect("test operation should succeed");
487        store
488            .graph_upsert_node(&make_node("c", "C", 1.0))
489            .expect("test operation should succeed");
490        store
491            .graph_upsert_edge(&make_edge("a", "b", "used_with", 0.8))
492            .expect("test operation should succeed");
493        store
494            .graph_upsert_edge(&make_edge("b", "c", "used_with", 0.7))
495            .expect("test operation should succeed");
496        let results = store
497            .graph_recall(&["a"], 3, 0.3, 10)
498            .expect("test operation should succeed");
499        let ids: Vec<&str> = results.iter().map(|r| r.node.id.as_str()).collect();
500        assert!(ids.contains(&"b"));
501        assert!(ids.contains(&"c"));
502    }
503
504    #[test]
505    fn recall_respects_min_edge_weight() {
506        let store = MemoryStore::open_memory().expect("test operation should succeed");
507        store
508            .graph_upsert_node(&make_node("seed", "S", 1.0))
509            .expect("test operation should succeed");
510        store
511            .graph_upsert_node(&make_node("strong", "Strong", 1.0))
512            .expect("test operation should succeed");
513        store
514            .graph_upsert_node(&make_node("weak", "Weak", 1.0))
515            .expect("test operation should succeed");
516        store
517            .graph_upsert_edge(&make_edge("seed", "strong", "used_with", 0.8))
518            .expect("test operation should succeed");
519        store
520            .graph_upsert_edge(&make_edge("seed", "weak", "used_with", 0.1))
521            .expect("test operation should succeed");
522        let results = store
523            .graph_recall(&["seed"], 3, 0.3, 10)
524            .expect("test operation should succeed");
525        let ids: Vec<&str> = results.iter().map(|r| r.node.id.as_str()).collect();
526        assert!(ids.contains(&"strong"));
527        assert!(!ids.contains(&"weak"));
528    }
529
530    #[test]
531    fn recall_respects_max_hops() {
532        let store = MemoryStore::open_memory().expect("test operation should succeed");
533        store
534            .graph_upsert_node(&make_node("a", "A", 1.0))
535            .expect("test operation should succeed");
536        store
537            .graph_upsert_node(&make_node("b", "B", 1.0))
538            .expect("test operation should succeed");
539        store
540            .graph_upsert_node(&make_node("c", "C", 1.0))
541            .expect("test operation should succeed");
542        store
543            .graph_upsert_node(&make_node("d", "D", 1.0))
544            .expect("test operation should succeed");
545        store
546            .graph_upsert_edge(&make_edge("a", "b", "used_with", 0.9))
547            .expect("test operation should succeed");
548        store
549            .graph_upsert_edge(&make_edge("b", "c", "used_with", 0.9))
550            .expect("test operation should succeed");
551        store
552            .graph_upsert_edge(&make_edge("c", "d", "used_with", 0.9))
553            .expect("test operation should succeed");
554        let results = store
555            .graph_recall(&["a"], 2, 0.3, 10)
556            .expect("test operation should succeed");
557        let ids: Vec<&str> = results.iter().map(|r| r.node.id.as_str()).collect();
558        assert!(ids.contains(&"b"));
559        assert!(ids.contains(&"c"));
560        assert!(!ids.contains(&"d"));
561    }
562
563    #[test]
564    fn recall_empty_seeds_returns_empty() {
565        let store = MemoryStore::open_memory().expect("test operation should succeed");
566        let results = store
567            .graph_recall(&[], 3, 0.3, 10)
568            .expect("test operation should succeed");
569        assert!(results.is_empty());
570    }
571
572    #[test]
573    fn recall_deterministic_for_same_graph_state() {
574        let store1 = MemoryStore::open_memory().expect("test operation should succeed");
575        let store2 = MemoryStore::open_memory().expect("test operation should succeed");
576        for store in [&store1, &store2] {
577            store
578                .graph_upsert_node(&make_node("a", "A", 1.0))
579                .expect("test operation should succeed");
580            store
581                .graph_upsert_node(&make_node("b", "B", 0.8))
582                .expect("test operation should succeed");
583            store
584                .graph_upsert_node(&make_node("c", "C", 0.6))
585                .expect("test operation should succeed");
586            store
587                .graph_upsert_edge(&make_edge("a", "b", "used_with", 0.9))
588                .expect("test operation should succeed");
589            store
590                .graph_upsert_edge(&make_edge("a", "c", "used_with", 0.5))
591                .expect("test operation should succeed");
592            store
593                .graph_upsert_edge(&make_edge("b", "c", "used_with", 0.7))
594                .expect("test operation should succeed");
595        }
596        let r1 = store1
597            .graph_recall(&["a"], 3, 0.3, 10)
598            .expect("test operation should succeed");
599        let r2 = store2
600            .graph_recall(&["a"], 3, 0.3, 10)
601            .expect("test operation should succeed");
602        assert_eq!(r1.len(), r2.len());
603        for (a, b) in r1.iter().zip(r2.iter()) {
604            assert_eq!(a.node.id, b.node.id);
605            assert!((a.score - b.score).abs() < 0.001);
606        }
607    }
608
609    #[test]
610    fn recency_decay_decreases_over_time() {
611        let now = Utc::now();
612        let recent = now;
613        let old = now - chrono::Duration::days(7);
614        let ancient = now - chrono::Duration::days(30);
615        let d_recent = recency_decay(recent, now);
616        let d_old = recency_decay(old, now);
617        let d_ancient = recency_decay(ancient, now);
618        assert!(d_recent > d_old);
619        assert!(d_old > d_ancient);
620        assert!((d_recent - 1.0).abs() < 0.01);
621        assert!((d_old - 0.5).abs() < 0.01);
622    }
623}