Skip to main content

mentedb_graph/
csr.rs

1//! Compressed Sparse Row/Column graph storage with delta log for incremental updates.
2
3use ahash::HashMap;
4use mentedb_core::edge::{EdgeType, MemoryEdge};
5use mentedb_core::error::{MenteError, MenteResult};
6use mentedb_core::types::{MemoryId, Timestamp};
7use serde::{Deserialize, Serialize};
8
9/// Compact edge data stored in CSR/CSC arrays.
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11pub struct StoredEdge {
12    /// The relationship type.
13    pub edge_type: EdgeType,
14    /// Edge weight (0.0 to 1.0).
15    pub weight: f32,
16    /// When this edge was created.
17    pub created_at: Timestamp,
18    /// When this relationship became valid. None = since creation.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub valid_from: Option<Timestamp>,
21    /// When this relationship stopped being valid. None = still valid.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub valid_until: Option<Timestamp>,
24    /// Semantic label for the relationship (e.g. "owns", "attends").
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub label: Option<String>,
27}
28
29impl StoredEdge {
30    /// Converts a [`MemoryEdge`] into a compact stored representation.
31    pub fn from_memory_edge(edge: &MemoryEdge) -> Self {
32        Self {
33            edge_type: edge.edge_type,
34            weight: edge.weight,
35            created_at: edge.created_at,
36            valid_from: edge.valid_from,
37            valid_until: edge.valid_until,
38            label: edge.label.clone(),
39        }
40    }
41
42    /// Returns true if this edge is temporally valid at the given timestamp.
43    pub fn is_valid_at(&self, at: Timestamp) -> bool {
44        let from = self.valid_from.unwrap_or(0);
45        match self.valid_until {
46            Some(until) => at >= from && at < until,
47            None => at >= from,
48        }
49    }
50
51    /// Returns true if this edge has been invalidated.
52    pub fn is_invalidated(&self) -> bool {
53        self.valid_until.is_some()
54    }
55}
56
57/// A pending edge in the delta log before compaction into CSR.
58#[derive(Debug, Clone, Serialize, Deserialize)]
59struct DeltaEdge {
60    source_idx: u32,
61    target_idx: u32,
62    data: StoredEdge,
63}
64
65/// Compressed Sparse Row storage for one direction (outgoing or incoming).
66#[derive(Debug, Clone, Default, Serialize, Deserialize)]
67struct CompressedStorage {
68    /// Length = num_nodes + 1. row_offsets[i]..row_offsets[i+1] gives the range in col_indices/edge_data.
69    row_offsets: Vec<u32>,
70    /// Column indices (target node for CSR, source node for CSC).
71    col_indices: Vec<u32>,
72    /// Edge metadata parallel to col_indices.
73    edge_data: Vec<StoredEdge>,
74}
75
76impl CompressedStorage {
77    #[allow(dead_code)]
78    fn new(num_nodes: usize) -> Self {
79        Self {
80            row_offsets: vec![0; num_nodes + 1],
81            col_indices: Vec::new(),
82            edge_data: Vec::new(),
83        }
84    }
85
86    /// Get neighbors and edge data for a given row index.
87    fn neighbors(&self, row: u32) -> &[u32] {
88        let row = row as usize;
89        if row + 1 >= self.row_offsets.len() {
90            return &[];
91        }
92        let start = self.row_offsets[row] as usize;
93        let end = self.row_offsets[row + 1] as usize;
94        &self.col_indices[start..end]
95    }
96
97    fn edge_data_for(&self, row: u32) -> &[StoredEdge] {
98        let row = row as usize;
99        if row + 1 >= self.row_offsets.len() {
100            return &[];
101        }
102        let start = self.row_offsets[row] as usize;
103        let end = self.row_offsets[row + 1] as usize;
104        &self.edge_data[start..end]
105    }
106}
107
108/// Bidirectional graph with CSR (outgoing) and CSC (incoming) plus a delta log.
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct CsrGraph {
111    /// Maps MemoryId -> internal u32 index.
112    id_to_idx: HashMap<MemoryId, u32>,
113    /// Maps internal u32 index -> MemoryId.
114    idx_to_id: Vec<MemoryId>,
115
116    /// CSR for outgoing edges.
117    csr: CompressedStorage,
118    /// CSC for incoming edges.
119    csc: CompressedStorage,
120
121    /// Recent edges not yet merged into the compressed storage.
122    delta_edges: Vec<DeltaEdge>,
123    /// Edges marked for removal (source_idx, target_idx).
124    removed_edges: Vec<(u32, u32)>,
125}
126
127impl CsrGraph {
128    /// Creates a new empty CSR graph.
129    pub fn new() -> Self {
130        Self {
131            id_to_idx: HashMap::default(),
132            idx_to_id: Vec::new(),
133            csr: CompressedStorage::default(),
134            csc: CompressedStorage::default(),
135            delta_edges: Vec::new(),
136            removed_edges: Vec::new(),
137        }
138    }
139
140    /// Register a node. Returns its internal index.
141    pub fn add_node(&mut self, id: MemoryId) -> u32 {
142        if let Some(&idx) = self.id_to_idx.get(&id) {
143            return idx;
144        }
145        let idx = self.idx_to_id.len() as u32;
146        self.id_to_idx.insert(id, idx);
147        self.idx_to_id.push(id);
148        idx
149    }
150
151    /// Remove a node and all its edges.
152    pub fn remove_node(&mut self, id: MemoryId) {
153        let Some(&idx) = self.id_to_idx.get(&id) else {
154            return;
155        };
156        // Mark all outgoing and incoming edges for removal
157        for &neighbor in self.csr.neighbors(idx) {
158            self.removed_edges.push((idx, neighbor));
159        }
160        for &neighbor in self.csc.neighbors(idx) {
161            self.removed_edges.push((neighbor, idx));
162        }
163        // Also remove from delta
164        self.delta_edges
165            .retain(|e| e.source_idx != idx && e.target_idx != idx);
166        self.id_to_idx.remove(&id);
167    }
168
169    /// Add an edge to the delta log.
170    ///
171    /// Deduplicates: if a currently-valid edge with the same source, target,
172    /// and type already exists (in CSR or the delta log), the graph is left
173    /// unchanged. Write inference and pipeline passes may infer the same
174    /// relationship more than once; parallel duplicates carry no information.
175    pub fn add_edge(&mut self, edge: &MemoryEdge) {
176        let source_idx = self.add_node(edge.source);
177        let target_idx = self.add_node(edge.target);
178
179        let duplicate = self.outgoing_by_idx(source_idx).into_iter().any(|(t, e)| {
180            t == edge.target && e.edge_type == edge.edge_type && e.valid_until.is_none()
181        });
182        if duplicate {
183            return;
184        }
185
186        self.delta_edges.push(DeltaEdge {
187            source_idx,
188            target_idx,
189            data: StoredEdge::from_memory_edge(edge),
190        });
191    }
192
193    /// Strengthen an edge by incrementing its weight (Hebbian learning).
194    ///
195    /// Updates the existing edge rather than appending a parallel duplicate:
196    /// a delta edge is bumped in place; a compressed (CSR) edge is marked
197    /// removed and replaced with a delta override, so compaction keeps
198    /// exactly one copy.
199    pub fn strengthen_edge(&mut self, source: MemoryId, target: MemoryId, delta: f32) {
200        let (Some(&source_idx), Some(&target_idx)) =
201            (self.id_to_idx.get(&source), self.id_to_idx.get(&target))
202        else {
203            return;
204        };
205
206        // Bump an existing delta edge in place.
207        if let Some(existing) = self
208            .delta_edges
209            .iter_mut()
210            .find(|e| e.source_idx == source_idx && e.target_idx == target_idx)
211        {
212            existing.data.weight = (existing.data.weight + delta).min(1.0);
213            return;
214        }
215
216        // Edge lives in compressed storage: suppress the CSR copy and push a
217        // delta override. Removed-edge filtering only applies to compressed
218        // edges, so the override remains visible.
219        if let Some((_, stored)) = self
220            .outgoing_by_idx(source_idx)
221            .into_iter()
222            .find(|(id, _)| *id == target)
223        {
224            let new_weight = (stored.weight + delta).min(1.0);
225            self.removed_edges.push((source_idx, target_idx));
226            self.delta_edges.push(DeltaEdge {
227                source_idx,
228                target_idx,
229                data: StoredEdge {
230                    weight: new_weight,
231                    ..stored
232                },
233            });
234        }
235    }
236
237    /// Mark an edge for removal.
238    pub fn remove_edge(&mut self, source: MemoryId, target: MemoryId) {
239        let (Some(&src_idx), Some(&tgt_idx)) =
240            (self.id_to_idx.get(&source), self.id_to_idx.get(&target))
241        else {
242            return;
243        };
244        self.removed_edges.push((src_idx, tgt_idx));
245        self.delta_edges
246            .retain(|e| !(e.source_idx == src_idx && e.target_idx == tgt_idx));
247    }
248
249    /// Remove every edge whose type is in `types`, preserving all other edges,
250    /// including edges of a different type between the same pair. Returns the
251    /// number of edges removed.
252    ///
253    /// The removal model suppresses a compressed edge at pair granularity, so
254    /// when a suppressed pair also carries a non-matching edge, that sibling is
255    /// re-added to the delta log to keep it. Callers should `compact()` after to
256    /// materialize the result into both CSR and CSC. This is a one-time cleanup
257    /// primitive (used to purge conflict edges the old write-time heuristic
258    /// created at ~0% precision), not a hot path.
259    pub fn remove_edges_of_types(&mut self, types: &[EdgeType]) -> usize {
260        let matches = |et: EdgeType| types.contains(&et);
261        let mut removed = 0usize;
262
263        // Delta edges: drop matching ones directly.
264        let before = self.delta_edges.len();
265        self.delta_edges.retain(|e| !matches(e.data.edge_type));
266        removed += before - self.delta_edges.len();
267
268        // Compressed edges: suppress matching ones. Suppression is pair level,
269        // so restore any non-matching sibling of a suppressed pair via delta.
270        let mut restore: Vec<DeltaEdge> = Vec::new();
271        let n = self.idx_to_id.len() as u32;
272        for src_idx in 0..n {
273            let row: Vec<(u32, StoredEdge)> = {
274                let neighbors = self.csr.neighbors(src_idx);
275                let edges = self.csr.edge_data_for(src_idx);
276                let mut v = Vec::new();
277                for (i, &t) in neighbors.iter().enumerate() {
278                    if !self.is_removed(src_idx, t) {
279                        v.push((t, edges[i].clone()));
280                    }
281                }
282                v
283            };
284            let matched_pairs: std::collections::HashSet<u32> = row
285                .iter()
286                .filter(|(_, e)| matches(e.edge_type))
287                .map(|(t, _)| *t)
288                .collect();
289            if matched_pairs.is_empty() {
290                continue;
291            }
292            for &tgt_idx in &matched_pairs {
293                self.removed_edges.push((src_idx, tgt_idx));
294            }
295            for (tgt_idx, e) in row {
296                if !matched_pairs.contains(&tgt_idx) {
297                    continue;
298                }
299                if matches(e.edge_type) {
300                    removed += 1;
301                } else {
302                    restore.push(DeltaEdge {
303                        source_idx: src_idx,
304                        target_idx: tgt_idx,
305                        data: e,
306                    });
307                }
308            }
309        }
310        self.delta_edges.extend(restore);
311        removed
312    }
313
314    /// Get all outgoing edges from a node (CSR + delta, minus removed).
315    pub fn outgoing(&self, id: MemoryId) -> Vec<(MemoryId, StoredEdge)> {
316        let Some(&idx) = self.id_to_idx.get(&id) else {
317            return Vec::new();
318        };
319        self.outgoing_by_idx(idx)
320    }
321
322    /// Get outgoing edges that are temporally valid at the given timestamp.
323    pub fn outgoing_valid_at(&self, id: MemoryId, at: Timestamp) -> Vec<(MemoryId, StoredEdge)> {
324        self.outgoing(id)
325            .into_iter()
326            .filter(|(_, e)| e.is_valid_at(at))
327            .collect()
328    }
329
330    pub(crate) fn outgoing_by_idx(&self, idx: u32) -> Vec<(MemoryId, StoredEdge)> {
331        let mut results = Vec::new();
332
333        // From compressed storage
334        let neighbors = self.csr.neighbors(idx);
335        let edges = self.csr.edge_data_for(idx);
336        for (i, &neighbor) in neighbors.iter().enumerate() {
337            if !self.is_removed(idx, neighbor)
338                && let Some(&id) = self.idx_to_id.get(neighbor as usize)
339            {
340                results.push((id, edges[i].clone()));
341            }
342        }
343
344        // From delta
345        for delta in &self.delta_edges {
346            if delta.source_idx == idx
347                && let Some(&id) = self.idx_to_id.get(delta.target_idx as usize)
348            {
349                results.push((id, delta.data.clone()));
350            }
351        }
352
353        results
354    }
355
356    /// Get all incoming edges to a node (CSC + delta, minus removed).
357    pub fn incoming(&self, id: MemoryId) -> Vec<(MemoryId, StoredEdge)> {
358        let Some(&idx) = self.id_to_idx.get(&id) else {
359            return Vec::new();
360        };
361        self.incoming_by_idx(idx)
362    }
363
364    /// Get incoming edges that are temporally valid at the given timestamp.
365    pub fn incoming_valid_at(&self, id: MemoryId, at: Timestamp) -> Vec<(MemoryId, StoredEdge)> {
366        self.incoming(id)
367            .into_iter()
368            .filter(|(_, e)| e.is_valid_at(at))
369            .collect()
370    }
371
372    pub(crate) fn incoming_by_idx(&self, idx: u32) -> Vec<(MemoryId, StoredEdge)> {
373        let mut results = Vec::new();
374
375        // From compressed storage (CSC)
376        let neighbors = self.csc.neighbors(idx);
377        let edges = self.csc.edge_data_for(idx);
378        for (i, &neighbor) in neighbors.iter().enumerate() {
379            if !self.is_removed(neighbor, idx)
380                && let Some(&id) = self.idx_to_id.get(neighbor as usize)
381            {
382                results.push((id, edges[i].clone()));
383            }
384        }
385
386        // From delta
387        for delta in &self.delta_edges {
388            if delta.target_idx == idx
389                && let Some(&id) = self.idx_to_id.get(delta.source_idx as usize)
390            {
391                results.push((id, delta.data.clone()));
392            }
393        }
394
395        results
396    }
397
398    /// Check if a node exists in the graph.
399    pub fn contains_node(&self, id: MemoryId) -> bool {
400        self.id_to_idx.contains_key(&id)
401    }
402
403    /// Number of registered nodes.
404    pub fn node_count(&self) -> usize {
405        self.idx_to_id.len()
406    }
407
408    /// Resolve a MemoryId to its internal index.
409    pub(crate) fn get_idx(&self, id: MemoryId) -> Option<u32> {
410        self.id_to_idx.get(&id).copied()
411    }
412
413    /// Resolve an internal index to its MemoryId.
414    #[allow(dead_code)]
415    pub(crate) fn get_id(&self, idx: u32) -> Option<MemoryId> {
416        self.idx_to_id.get(idx as usize).copied()
417    }
418
419    /// All registered node IDs.
420    pub fn node_ids(&self) -> &[MemoryId] {
421        &self.idx_to_id
422    }
423
424    fn is_removed(&self, source: u32, target: u32) -> bool {
425        self.removed_edges
426            .iter()
427            .any(|&(s, t)| s == source && t == target)
428    }
429
430    /// Merge all delta edges and removals into the compressed CSR/CSC storage.
431    pub fn compact(&mut self) {
432        let num_nodes = self.idx_to_id.len();
433
434        // Collect all edges: existing (minus removed) + delta
435        let mut all_edges: Vec<(u32, u32, StoredEdge)> = Vec::new();
436
437        // Existing CSR edges
438        for row in 0..num_nodes {
439            let row = row as u32;
440            let neighbors = self.csr.neighbors(row);
441            let edges = self.csr.edge_data_for(row);
442            for (i, &col) in neighbors.iter().enumerate() {
443                if !self.is_removed(row, col) {
444                    all_edges.push((row, col, edges[i].clone()));
445                }
446            }
447        }
448
449        // Delta edges
450        for delta in &self.delta_edges {
451            all_edges.push((delta.source_idx, delta.target_idx, delta.data.clone()));
452        }
453
454        // Build CSR (sorted by source)
455        self.csr = Self::build_compressed(&all_edges, num_nodes, false);
456
457        // Build CSC (sorted by target)
458        self.csc = Self::build_compressed(&all_edges, num_nodes, true);
459
460        self.delta_edges.clear();
461        self.removed_edges.clear();
462    }
463
464    fn build_compressed(
465        edges: &[(u32, u32, StoredEdge)],
466        num_nodes: usize,
467        transpose: bool,
468    ) -> CompressedStorage {
469        // Count edges per row
470        let mut counts = vec![0u32; num_nodes];
471        for &(src, tgt, ref _data) in edges {
472            let row = if transpose { tgt } else { src };
473            if (row as usize) < num_nodes {
474                counts[row as usize] += 1;
475            }
476        }
477
478        // Build offsets via prefix sum
479        let mut row_offsets = vec![0u32; num_nodes + 1];
480        for i in 0..num_nodes {
481            row_offsets[i + 1] = row_offsets[i] + counts[i];
482        }
483
484        let total = row_offsets[num_nodes] as usize;
485        let mut col_indices = vec![0u32; total];
486        let mut edge_data = vec![
487            StoredEdge {
488                edge_type: EdgeType::Related,
489                weight: 0.0,
490                created_at: 0,
491                valid_from: None,
492                valid_until: None,
493                label: None,
494            };
495            total
496        ];
497
498        // Fill using write cursors
499        let mut cursors = row_offsets[..num_nodes].to_vec();
500        for &(src, tgt, ref data) in edges {
501            let (row, col) = if transpose { (tgt, src) } else { (src, tgt) };
502            if (row as usize) < num_nodes {
503                let pos = cursors[row as usize] as usize;
504                col_indices[pos] = col;
505                edge_data[pos] = data.clone();
506                cursors[row as usize] += 1;
507            }
508        }
509
510        CompressedStorage {
511            row_offsets,
512            col_indices,
513            edge_data,
514        }
515    }
516    /// Save the graph snapshot to a file.
517    pub fn save(&self, path: &std::path::Path) -> MenteResult<()> {
518        let data =
519            serde_json::to_vec(self).map_err(|e| MenteError::Serialization(e.to_string()))?;
520        // Atomic snapshot: write to a temp file, fsync, then rename over the
521        // old snapshot so a crash mid-save never leaves a truncated graph.
522        let tmp_path = path.with_extension("json.tmp");
523        {
524            use std::io::Write;
525            let mut file = std::fs::File::create(&tmp_path)?;
526            file.write_all(&data)?;
527            file.sync_data()?;
528        }
529        std::fs::rename(&tmp_path, path)?;
530        Ok(())
531    }
532
533    /// Load the graph from a file.
534    pub fn load(path: &std::path::Path) -> MenteResult<Self> {
535        let data = std::fs::read(path)?;
536        let graph: Self =
537            serde_json::from_slice(&data).map_err(|e| MenteError::Serialization(e.to_string()))?;
538        Ok(graph)
539    }
540}
541
542impl Default for CsrGraph {
543    fn default() -> Self {
544        Self::new()
545    }
546}
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551
552    fn make_edge(src: MemoryId, tgt: MemoryId, etype: EdgeType) -> MemoryEdge {
553        MemoryEdge {
554            source: src,
555            target: tgt,
556            edge_type: etype,
557            weight: 0.8,
558            created_at: 1000,
559            valid_from: None,
560            valid_until: None,
561            label: None,
562        }
563    }
564
565    #[test]
566    fn test_add_node_idempotent() {
567        let mut g = CsrGraph::new();
568        let id = MemoryId::new();
569        let idx1 = g.add_node(id);
570        let idx2 = g.add_node(id);
571        assert_eq!(idx1, idx2);
572        assert_eq!(g.node_count(), 1);
573    }
574
575    #[test]
576    fn test_add_and_query_edges() {
577        let mut g = CsrGraph::new();
578        let a = MemoryId::new();
579        let b = MemoryId::new();
580        let c = MemoryId::new();
581
582        g.add_edge(&make_edge(a, b, EdgeType::Caused));
583        g.add_edge(&make_edge(a, c, EdgeType::Related));
584
585        let out = g.outgoing(a);
586        assert_eq!(out.len(), 2);
587
588        let inc_b = g.incoming(b);
589        assert_eq!(inc_b.len(), 1);
590        assert_eq!(inc_b[0].0, a);
591    }
592
593    #[test]
594    fn test_remove_edge() {
595        let mut g = CsrGraph::new();
596        let a = MemoryId::new();
597        let b = MemoryId::new();
598
599        g.add_edge(&make_edge(a, b, EdgeType::Caused));
600        assert_eq!(g.outgoing(a).len(), 1);
601
602        g.remove_edge(a, b);
603        assert_eq!(g.outgoing(a).len(), 0);
604    }
605
606    #[test]
607    fn test_remove_edges_of_types_preserves_siblings() {
608        let mut g = CsrGraph::new();
609        let a = MemoryId::new();
610        let b = MemoryId::new();
611        let c = MemoryId::new();
612
613        // a->b carries BOTH a Supersedes and a Related edge (the collateral
614        // case: pair-level suppression must not drop the Related sibling).
615        g.add_edge(&make_edge(a, b, EdgeType::Supersedes));
616        g.add_edge(&make_edge(a, b, EdgeType::Related));
617        // a->c is a lone Contradicts edge.
618        g.add_edge(&make_edge(a, c, EdgeType::Contradicts));
619        // b->c is unrelated and must survive.
620        g.add_edge(&make_edge(b, c, EdgeType::Caused));
621
622        // Compact first so the targets live in compressed storage, exercising
623        // the suppress-pair + restore-sibling path rather than delta retain.
624        g.compact();
625
626        let removed = g.remove_edges_of_types(&[EdgeType::Contradicts, EdgeType::Supersedes]);
627        g.compact();
628        assert_eq!(removed, 2, "one Supersedes + one Contradicts");
629
630        // a->b: Supersedes gone, Related preserved.
631        let ab: Vec<_> = g.outgoing(a).into_iter().filter(|(t, _)| *t == b).collect();
632        assert_eq!(ab.len(), 1);
633        assert_eq!(ab[0].1.edge_type, EdgeType::Related);
634
635        // a->c contradiction gone entirely.
636        assert!(g.outgoing(a).into_iter().all(|(t, _)| t != c));
637
638        // Unrelated edge intact; incoming reflects the cleanup (only b->c left).
639        assert_eq!(g.outgoing(b).len(), 1);
640        let inc_c = g.incoming(c);
641        assert_eq!(inc_c.len(), 1);
642        assert_eq!(inc_c[0].0, b);
643    }
644
645    #[test]
646    fn test_compact() {
647        let mut g = CsrGraph::new();
648        let a = MemoryId::new();
649        let b = MemoryId::new();
650        let c = MemoryId::new();
651
652        g.add_edge(&make_edge(a, b, EdgeType::Caused));
653        g.add_edge(&make_edge(b, c, EdgeType::Before));
654        g.compact();
655
656        let out_a = g.outgoing(a);
657        assert_eq!(out_a.len(), 1);
658        assert_eq!(out_a[0].0, b);
659
660        let inc_c = g.incoming(c);
661        assert_eq!(inc_c.len(), 1);
662        assert_eq!(inc_c[0].0, b);
663    }
664
665    #[test]
666    fn test_compact_with_removals() {
667        let mut g = CsrGraph::new();
668        let a = MemoryId::new();
669        let b = MemoryId::new();
670        let c = MemoryId::new();
671
672        g.add_edge(&make_edge(a, b, EdgeType::Caused));
673        g.add_edge(&make_edge(a, c, EdgeType::Related));
674        g.compact();
675
676        g.remove_edge(a, b);
677        g.compact();
678
679        let out = g.outgoing(a);
680        assert_eq!(out.len(), 1);
681        assert_eq!(out[0].0, c);
682    }
683
684    #[test]
685    fn test_remove_node_cleans_id_to_idx() {
686        let mut g = CsrGraph::new();
687        let a = MemoryId::new();
688        let b = MemoryId::new();
689
690        g.add_edge(&make_edge(a, b, EdgeType::Caused));
691        assert!(g.contains_node(a));
692        assert!(g.contains_node(b));
693
694        g.remove_node(a);
695        assert!(
696            !g.contains_node(a),
697            "removed node should not be in id_to_idx"
698        );
699        assert!(g.contains_node(b), "unrelated node should still exist");
700
701        // Edges involving the removed node should be gone
702        assert!(g.outgoing(a).is_empty());
703        assert!(g.incoming(b).is_empty());
704    }
705
706    #[test]
707    fn test_remove_node_then_readd() {
708        let mut g = CsrGraph::new();
709        let a = MemoryId::new();
710        let b = MemoryId::new();
711        let c = MemoryId::new();
712
713        g.add_edge(&make_edge(a, b, EdgeType::Caused));
714        g.remove_node(a);
715
716        // Re-adding the same ID should get a fresh index
717        g.add_edge(&make_edge(a, c, EdgeType::Related));
718        assert!(g.contains_node(a));
719        let out = g.outgoing(a);
720        assert_eq!(out.len(), 1);
721        assert_eq!(out[0].0, c);
722    }
723}