petgraph-live 0.2.0

Generic generation-keyed graph cache, disk snapshot, and graph algorithms for petgraph 0.8
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
#[cfg(feature = "snapshot")]
#[test]
fn test_config_defaults() {
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat};
    use std::path::PathBuf;
    let cfg = SnapshotConfig {
        dir: PathBuf::from("/tmp/test-snapshots"),
        name: "mygraph".to_string(),
        key: Some("abc123".to_string()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    assert_eq!(cfg.keep, 3);
    assert_eq!(cfg.key.as_deref(), Some("abc123"));
}

#[cfg(feature = "snapshot")]
#[test]
fn test_sanitize_key() {
    use petgraph_live::snapshot::sanitize_key;
    assert_eq!(sanitize_key("abc123"), Ok("abc123".to_string()));
    assert_eq!(sanitize_key("a/b c"), Ok("a_b_c".to_string()));
    assert!(sanitize_key("   ").is_err());
}

#[cfg(feature = "snapshot")]
#[test]
fn test_config_serde_roundtrip() {
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat};
    use std::path::PathBuf;
    let cfg = SnapshotConfig {
        dir: PathBuf::from("/tmp"),
        name: "g".into(),
        key: Some("should-be-skipped".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 5,
    };
    let json = serde_json::to_string(&cfg).unwrap();
    let back: SnapshotConfig = serde_json::from_str(&json).unwrap();
    assert_eq!(back.name, "g");
    assert_eq!(back.keep, 5);
    assert_eq!(back.key, None);
}

#[cfg(feature = "snapshot")]
#[test]
fn test_meta_new() {
    use petgraph_live::snapshot::{Compression, SnapshotFormat, SnapshotMeta};
    let meta = SnapshotMeta::new("sha123", SnapshotFormat::Bincode, Compression::None, 10, 5);
    assert_eq!(meta.node_count, 10);
    assert_eq!(meta.edge_count, 5);
    assert_eq!(meta.key, "sha123");
    assert!(!meta.petgraph_live_version.is_empty());
}

#[cfg(feature = "snapshot")]
#[test]
fn test_error_display() {
    use petgraph_live::snapshot::SnapshotError;
    let e = SnapshotError::KeyNotFound {
        key: "sha_abc".into(),
    };
    assert!(e.to_string().contains("sha_abc"));
    let e2 = SnapshotError::InvalidKey("   ".into());
    assert!(e2.to_string().contains("invalid key"));
    assert!(
        SnapshotError::NoSnapshotFound
            .to_string()
            .contains("no snapshot")
    );
}

#[cfg(feature = "snapshot")]
#[test]
fn test_rotation_keep_3() {
    use petgraph_live::snapshot::rotation::{keep_n, list_snapshot_files};
    use std::{
        fs,
        time::{Duration, SystemTime},
    };
    let dir = tempfile::tempdir().unwrap();
    for i in 1u64..=5 {
        let fname = format!("mygraph-key{}.snap", i);
        let path = dir.path().join(&fname);
        fs::write(&path, b"data").unwrap();
        let mtime = SystemTime::UNIX_EPOCH + Duration::from_secs(i * 1000);
        filetime::set_file_mtime(&path, filetime::FileTime::from_system_time(mtime)).unwrap();
    }
    let files = list_snapshot_files(dir.path(), "mygraph").unwrap();
    assert_eq!(files.len(), 5);
    keep_n(dir.path(), "mygraph", 3).unwrap();
    let remaining = list_snapshot_files(dir.path(), "mygraph").unwrap();
    assert_eq!(remaining.len(), 3);
    for i in 3u64..=5 {
        assert!(dir.path().join(format!("mygraph-key{}.snap", i)).exists());
    }
}

#[cfg(feature = "snapshot")]
#[test]
fn test_save_creates_file() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, save};
    let dir = tempfile::tempdir().unwrap();
    let cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("sha1abc".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    let mut graph: Graph<(), ()> = Graph::new();
    graph.add_node(());
    save(&cfg, &graph).unwrap();
    let entries: Vec<_> = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();
    assert_eq!(entries.len(), 1);
    let name = entries[0].file_name().to_string_lossy().into_owned();
    assert_eq!(name, "g-sha1abc.snap");
}

#[cfg(feature = "snapshot")]
#[test]
fn test_save_same_key_idempotent() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, save};
    let dir = tempfile::tempdir().unwrap();
    let cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    let graph: Graph<(), ()> = Graph::new();
    save(&cfg, &graph).unwrap();
    save(&cfg, &graph).unwrap();
    let count = std::fs::read_dir(dir.path()).unwrap().count();
    assert_eq!(count, 1);
}

#[cfg(feature = "snapshot")]
#[test]
fn test_save_load_roundtrip_bincode() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, load, save};
    let dir = tempfile::tempdir().unwrap();
    let cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    let mut graph: Graph<String, ()> = Graph::new();
    graph.add_node("a".into());
    graph.add_node("b".into());
    graph.add_node("c".into());
    save(&cfg, &graph).unwrap();
    let loaded: Graph<String, ()> = load(&cfg).unwrap().unwrap();
    assert_eq!(loaded.node_count(), 3);
}

#[cfg(feature = "snapshot")]
#[test]
fn test_save_load_roundtrip_json() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, load, save};
    let dir = tempfile::tempdir().unwrap();
    let cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Json,
        compression: Compression::None,
        keep: 3,
    };
    let mut graph: Graph<String, ()> = Graph::new();
    graph.add_node("a".to_string());
    graph.add_node("b".to_string());
    graph.add_node("c".to_string());
    save(&cfg, &graph).unwrap();
    let loaded: Graph<String, ()> = load(&cfg).unwrap().unwrap();
    assert_eq!(loaded.node_count(), 3);
}

#[cfg(feature = "snapshot")]
#[test]
fn test_load_key_not_found() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{
        Compression, SnapshotConfig, SnapshotError, SnapshotFormat, load, save,
    };
    let dir = tempfile::tempdir().unwrap();
    let mut cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    let graph: Graph<(), ()> = Graph::new();
    save(&cfg, &graph).unwrap();
    cfg.key = Some("v2".into());
    let result: Result<Option<Graph<(), ()>>, _> = load(&cfg);
    assert!(matches!(result, Err(SnapshotError::KeyNotFound { .. })));
}

#[cfg(feature = "snapshot")]
#[test]
fn test_load_no_snapshot_returns_none() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{
        Compression, SnapshotConfig, SnapshotError, SnapshotFormat, load,
    };
    let dir = tempfile::tempdir().unwrap();
    // key=Some, empty dir → KeyNotFound
    let cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    let result: Result<Option<Graph<(), ()>>, _> = load(&cfg);
    assert!(matches!(result, Err(SnapshotError::KeyNotFound { .. })));
    // key=None, empty dir → Ok(None)
    let mut cfg2 = cfg.clone();
    cfg2.key = None;
    let result2: Result<Option<Graph<(), ()>>, _> = load(&cfg2);
    assert!(matches!(result2, Ok(None)));
}

#[cfg(feature = "snapshot")]
#[test]
fn test_load_none_key_returns_most_recent() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, load, save};
    use std::{thread, time::Duration};
    let dir = tempfile::tempdir().unwrap();
    let mut cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 10,
    };
    let mut g1: Graph<u32, ()> = Graph::new();
    g1.add_node(1);
    save(&cfg, &g1).unwrap();
    thread::sleep(Duration::from_millis(10));
    cfg.key = Some("v2".into());
    let mut g2: Graph<u32, ()> = Graph::new();
    g2.add_node(1);
    g2.add_node(2);
    save(&cfg, &g2).unwrap();
    cfg.key = None;
    let loaded: Graph<u32, ()> = load(&cfg).unwrap().unwrap();
    assert_eq!(loaded.node_count(), 2);
}

#[cfg(feature = "snapshot")]
#[test]
fn test_load_or_build_falls_back_on_empty() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{
        Compression, SnapshotConfig, SnapshotFormat, load, load_or_build,
    };
    let dir = tempfile::tempdir().unwrap();
    let cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    let mut called = false;
    let g: Graph<u32, ()> = load_or_build(&cfg, || {
        called = true;
        let mut g = Graph::new();
        g.add_node(42u32);
        Ok(g)
    })
    .unwrap();
    assert!(called);
    assert_eq!(g.node_count(), 1);
    // file saved → can load now
    let loaded: Graph<u32, ()> = load(&cfg).unwrap().unwrap();
    assert_eq!(loaded.node_count(), 1);
}

#[cfg(feature = "snapshot")]
#[test]
fn test_load_or_build_falls_back_on_key_not_found() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{
        Compression, SnapshotConfig, SnapshotFormat, load, load_or_build, save,
    };
    let dir = tempfile::tempdir().unwrap();
    let mut cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 10,
    };
    let g1: Graph<u32, ()> = Graph::new();
    save(&cfg, &g1).unwrap();
    cfg.key = Some("v2".into());
    let mut build_called = false;
    let _g: Graph<u32, ()> = load_or_build(&cfg, || {
        build_called = true;
        let mut g = Graph::new();
        g.add_node(99u32);
        Ok(g)
    })
    .unwrap();
    assert!(build_called);
    // v1 still present
    cfg.key = Some("v1".into());
    let v1: Graph<u32, ()> = load(&cfg).unwrap().unwrap();
    assert_eq!(v1.node_count(), 0);
}

#[cfg(feature = "snapshot")]
#[test]
fn test_inspect_reads_meta_without_graph() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, inspect, save};
    let dir = tempfile::tempdir().unwrap();
    let cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("sha1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    let mut graph: Graph<u32, ()> = Graph::new();
    graph.add_node(1);
    graph.add_node(2);
    save(&cfg, &graph).unwrap();
    let meta = inspect(&cfg).unwrap().unwrap();
    assert_eq!(meta.node_count, 2);
    assert_eq!(meta.key, "sha1");
}

#[cfg(feature = "snapshot")]
#[test]
fn test_inspect_none_key_most_recent() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, inspect, save};
    use std::{thread, time::Duration};
    let dir = tempfile::tempdir().unwrap();
    let mut cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("v1".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 10,
    };
    let g1: Graph<u32, ()> = Graph::new();
    save(&cfg, &g1).unwrap();
    thread::sleep(Duration::from_millis(10));
    cfg.key = Some("v2".into());
    let mut g2: Graph<u32, ()> = Graph::new();
    g2.add_node(1);
    save(&cfg, &g2).unwrap();
    cfg.key = None;
    let meta = inspect(&cfg).unwrap().unwrap();
    assert_eq!(meta.key, "v2");
}

#[cfg(feature = "snapshot")]
#[test]
fn test_list_sorted_oldest_first() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, list, save};
    use std::{thread, time::Duration};
    let dir = tempfile::tempdir().unwrap();
    let cfg_base = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: None,
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 10,
    };
    let g: Graph<u32, ()> = Graph::new();
    for key in &["k1", "k2", "k3"] {
        let mut cfg = cfg_base.clone();
        cfg.key = Some(key.to_string());
        save(&cfg, &g).unwrap();
        thread::sleep(Duration::from_millis(10));
    }
    let entries = list(&cfg_base).unwrap();
    assert_eq!(entries.len(), 3);
    assert_eq!(entries[0].1.key, "k1");
    assert_eq!(entries[2].1.key, "k3");
}

#[cfg(feature = "snapshot")]
#[test]
fn test_purge_deletes_all() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, purge, save};
    let dir = tempfile::tempdir().unwrap();
    let cfg_base = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: None,
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 10,
    };
    let g: Graph<u32, ()> = Graph::new();
    for key in &["a", "b", "c", "d"] {
        let mut cfg = cfg_base.clone();
        cfg.key = Some(key.to_string());
        save(&cfg, &g).unwrap();
    }
    let count = purge(&cfg_base).unwrap();
    assert_eq!(count, 4);
    assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
}

#[cfg(feature = "snapshot")]
#[test]
fn test_rotation_save_5_keep_3() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, list, save};
    use std::{thread, time::Duration};
    let dir = tempfile::tempdir().unwrap();
    let cfg_base = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: None,
        format: SnapshotFormat::Bincode,
        compression: Compression::None,
        keep: 3,
    };
    let g: Graph<u32, ()> = Graph::new();
    for i in 1u32..=5 {
        let mut cfg = cfg_base.clone();
        cfg.key = Some(format!("key{}", i));
        save(&cfg, &g).unwrap();
        thread::sleep(Duration::from_millis(10));
    }
    let entries = list(&cfg_base).unwrap();
    assert_eq!(entries.len(), 3);
    // newest 3 retained: key3, key4, key5
    let keys: Vec<&str> = entries.iter().map(|(_, m)| m.key.as_str()).collect();
    assert!(keys.contains(&"key3"));
    assert!(keys.contains(&"key4"));
    assert!(keys.contains(&"key5"));
}

#[cfg(all(feature = "snapshot", feature = "snapshot-zstd"))]
#[test]
fn test_zstd_roundtrip() {
    use petgraph::Graph;
    use petgraph_live::snapshot::{Compression, SnapshotConfig, SnapshotFormat, load, save};
    let dir = tempfile::tempdir().unwrap();
    let cfg = SnapshotConfig {
        dir: dir.path().to_path_buf(),
        name: "g".into(),
        key: Some("zstd_key".into()),
        format: SnapshotFormat::Bincode,
        compression: Compression::Zstd { level: 3 },
        keep: 3,
    };
    let mut graph: Graph<u32, ()> = Graph::new();
    for i in 0..100 {
        graph.add_node(i);
    }
    save(&cfg, &graph).unwrap();
    // verify file ends with .snap.zst
    let files: Vec<_> = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();
    assert_eq!(files.len(), 1);
    assert!(
        files[0]
            .file_name()
            .to_string_lossy()
            .ends_with(".snap.zst")
    );
    let loaded: Graph<u32, ()> = load(&cfg).unwrap().unwrap();
    assert_eq!(loaded.node_count(), 100);
}