sqlitegraph 2.2.2

Embedded graph database with full ACID transactions, HNSW vector search, dual backend support, and comprehensive graph algorithms library
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
//! Forensic instrumentation test for V3 backend
//!
//! This test isolates single operations and measures the internal work
//! performed by the V3 backend to identify amplification issues.
//!
//! Run with:
//! cargo test --features native-v3,v3-forensics v3_forensics -- --nocapture

#[cfg(feature = "v3-forensics")]
use sqlitegraph::backend::native::v3::forensics::FORENSIC_COUNTERS;

// ============================================================================
// WRITE PATH SCENARIOS
// ============================================================================

#[test]
#[cfg(feature = "v3-forensics")]
#[ignore] // Run explicitly with cargo test --ignored
fn forensic_insert_node_into_empty_db() {
    println!("\n═══════════════════════════════════════════════════════════");
    println!("          SCENARIO: Insert 1 node into EMPTY DB            ");
    println!("═══════════════════════════════════════════════════════════\n");

    FORENSIC_COUNTERS.reset();

    let temp = TempDir::new().unwrap();
    let backend = V3Backend::create(temp.path().join("v3.db")).unwrap();

    let before = FORENSIC_COUNTERS.snapshot();

    // Single insert operation
    let node = NodeSpec {
        kind: "TestNode".to_string(),
        name: "test".to_string(),
        file_path: None,
        data: serde_json::json!({"test": "data"}),
    };
    let _node_id = backend.insert_node(node).unwrap();

    let after = FORENSIC_COUNTERS.snapshot();
    let delta = before.diff(&after);

    delta.print_report();

    // Assert we have reasonable counts
    assert_eq!(delta.logical_insert_node_calls, 1);
    println!("Expected: 1 logical insert_node call\n");

    // Check for pathological sync patterns
    if delta.sync_data_count > 5 {
        println!(
            "⚠️  WARNING: Excessive sync_data() calls: {}",
            delta.sync_data_count
        );
    }
    if delta.sync_all_count > 5 {
        println!(
            "⚠️  WARNING: Excessive sync_all() calls: {}",
            delta.sync_all_count
        );
    }
}

#[test]
#[cfg(feature = "v3-forensics")]
#[ignore]
fn forensic_insert_node_after_100_nodes() {
    println!("\n═══════════════════════════════════════════════════════════");
    println!("       SCENARIO: Insert 1 node after 100 existing nodes     ");
    println!("═══════════════════════════════════════════════════════════\n");

    let temp = TempDir::new().unwrap();
    let backend = V3Backend::create(temp.path().join("v3.db")).unwrap();

    // Pre-populate with 100 nodes
    for i in 0..100 {
        let node = NodeSpec {
            kind: "TestNode".to_string(),
            name: format!("node_{}", i),
            file_path: None,
            data: serde_json::json!({"id": i}),
        };
        backend.insert_node(node).unwrap();
    }

    FORENSIC_COUNTERS.reset();
    let before = FORENSIC_COUNTERS.snapshot();

    // Single insert after 100 nodes
    let node = NodeSpec {
        kind: "TestNode".to_string(),
        name: "node_after_100".to_string(),
        file_path: None,
        data: serde_json::json!({"test": "data"}),
    };
    let _node_id = backend.insert_node(node).unwrap();

    let after = FORENSIC_COUNTERS.snapshot();
    let delta = before.diff(&after);

    delta.print_report();

    assert_eq!(delta.logical_insert_node_calls, 1);

    // Check for amplification as DB grows
    if delta.page_write_count > 10 {
        println!(
            "⚠️  WARNING: High page write count for single insert: {}",
            delta.page_write_count
        );
    }
}

#[test]
#[cfg(feature = "v3-forensics")]
#[ignore]
fn forensic_insert_node_after_10k_nodes() {
    println!("\n═══════════════════════════════════════════════════════════");
    println!("      SCENARIO: Insert 1 node after 10K existing nodes       ");
    println!("═══════════════════════════════════════════════════════════\n");

    let temp = TempDir::new().unwrap();
    let backend = V3Backend::create(temp.path().join("v3.db")).unwrap();

    // Pre-populate with 10K nodes
    for i in 0..10_000 {
        let node = NodeSpec {
            kind: "TestNode".to_string(),
            name: format!("node_{}", i),
            file_path: None,
            data: serde_json::json!({"id": i}),
        };
        backend.insert_node(node).unwrap();
    }

    FORENSIC_COUNTERS.reset();
    let before = FORENSIC_COUNTERS.snapshot();

    // Single insert after 10K nodes
    let node = NodeSpec {
        kind: "TestNode".to_string(),
        name: "node_after_10k".to_string(),
        file_path: None,
        data: serde_json::json!({"test": "data"}),
    };
    let _node_id = backend.insert_node(node).unwrap();

    let after = FORENSIC_COUNTERS.snapshot();
    let delta = before.diff(&after);

    delta.print_report();

    assert_eq!(delta.logical_insert_node_calls, 1);

    // Critical check for amplification in larger DB
    if delta.btree_insert_calls > 1 {
        println!(
            "⚠️  WARNING: Multiple B+Tree inserts for single node insert: {}",
            delta.btree_insert_calls
        );
    }
}

#[test]
#[cfg(feature = "v3-forensics")]
#[ignore]
fn forensic_insert_edge() {
    println!("\n═══════════════════════════════════════════════════════════");
    println!("            SCENARIO: Insert 1 edge                          ");
    println!("═══════════════════════════════════════════════════════════\n");

    let temp = TempDir::new().unwrap();
    let backend = V3Backend::create(temp.path().join("v3.db")).unwrap();

    // Create two nodes first
    let n1 = backend
        .insert_node(NodeSpec {
            kind: "TestNode".to_string(),
            name: "node1".to_string(),
            file_path: None,
            data: serde_json::json!({}),
        })
        .unwrap();

    let n2 = backend
        .insert_node(NodeSpec {
            kind: "TestNode".to_string(),
            name: "node2".to_string(),
            file_path: None,
            data: serde_json::json!({}),
        })
        .unwrap();

    FORENSIC_COUNTERS.reset();
    let before = FORENSIC_COUNTERS.snapshot();

    // Single edge insert
    let edge = EdgeSpec {
        from: n1,
        to: n2,
        edge_type: "TestEdge".to_string(),
        data: serde_json::json!({}),
    };
    let _edge_id = backend.insert_edge(edge).unwrap();

    let after = FORENSIC_COUNTERS.snapshot();
    let delta = before.diff(&after);

    delta.print_report();

    assert_eq!(delta.logical_insert_edge_calls, 1);
}

// ============================================================================
// READ PATH SCENARIOS
// ============================================================================

#[test]
#[cfg(feature = "v3-forensics")]
#[ignore]
fn forensic_get_node_small_db() {
    println!("\n═══════════════════════════════════════════════════════════");
    println!("      SCENARIO: get_node in small DB (1K nodes)            ");
    println!("═══════════════════════════════════════════════════════════\n");

    let temp = TempDir::new().unwrap();
    let backend = V3Backend::create(temp.path().join("v3.db")).unwrap();

    // Pre-populate with 1K nodes
    let mut target_id = 0;
    for i in 0..1_000 {
        let node_id = backend
            .insert_node(NodeSpec {
                kind: "TestNode".to_string(),
                name: format!("node_{}", i),
                file_path: None,
                data: serde_json::json!({"id": i}),
            })
            .unwrap();
        if i == 500 {
            target_id = node_id;
        }
    }

    FORENSIC_COUNTERS.reset();
    let before = FORENSIC_COUNTERS.snapshot();

    // Single get_node operation
    let _node = backend.get_node(SnapshotId::current(), target_id).unwrap();

    let after = FORENSIC_COUNTERS.snapshot();
    let delta = before.diff(&after);

    delta.print_report();

    assert_eq!(delta.logical_get_node_calls, 1);

    // Check for read amplification
    if delta.page_read_count > 5 {
        println!(
            "⚠️  WARNING: High page read count for single get_node: {}",
            delta.page_read_count
        );
    }
}

#[test]
#[cfg(feature = "v3-forensics")]
#[ignore]
fn forensic_get_node_medium_db() {
    println!("\n═══════════════════════════════════════════════════════════");
    println!("      SCENARIO: get_node in medium DB (10K nodes)           ");
    println!("═══════════════════════════════════════════════════════════\n");

    let temp = TempDir::new().unwrap();
    let backend = V3Backend::create(temp.path().join("v3.db")).unwrap();

    // Pre-populate with 10K nodes
    let mut target_id = 0;
    for i in 0..10_000 {
        let node_id = backend
            .insert_node(NodeSpec {
                kind: "TestNode".to_string(),
                name: format!("node_{}", i),
                file_path: None,
                data: serde_json::json!({"id": i}),
            })
            .unwrap();
        if i == 5_000 {
            target_id = node_id;
        }
    }

    FORENSIC_COUNTERS.reset();
    let before = FORENSIC_COUNTERS.snapshot();

    // Single get_node operation
    let _node = backend.get_node(SnapshotId::current(), target_id).unwrap();

    let after = FORENSIC_COUNTERS.snapshot();
    let delta = before.diff(&after);

    delta.print_report();

    assert_eq!(delta.logical_get_node_calls, 1);

    // B+Tree height should be small even for 10K nodes
    if delta.page_read_count > 10 {
        println!(
            "⚠️  WARNING: Excessive page reads for B+Tree lookup: {}",
            delta.page_read_count
        );
        println!("  Expected: ~log2(10K) ≈ 14 pages max for node page + B+Tree pages");
    }
}

#[test]
#[cfg(feature = "v3-forensics")]
#[ignore]
fn forensic_neighbors_small_db() {
    println!("\n═══════════════════════════════════════════════════════════");
    println!("      SCENARIO: neighbors() in small DB (1K nodes)          ");
    println!("═══════════════════════════════════════════════════════════\n");

    let temp = TempDir::new().unwrap();
    let backend = V3Backend::create(temp.path().join("v3.db")).unwrap();

    // Create a star graph: node 0 connects to 100 other nodes
    let center_id = backend
        .insert_node(NodeSpec {
            kind: "Center".to_string(),
            name: "center".to_string(),
            file_path: None,
            data: serde_json::json!({}),
        })
        .unwrap();

    for i in 1..=100 {
        let node_id = backend
            .insert_node(NodeSpec {
                kind: "Leaf".to_string(),
                name: format!("leaf_{}", i),
                file_path: None,
                data: serde_json::json!({}),
            })
            .unwrap();

        backend
            .insert_edge(EdgeSpec {
                from: center_id,
                to: node_id,
                edge_type: "Connect".to_string(),
                data: serde_json::json!({}),
            })
            .unwrap();
    }

    FORENSIC_COUNTERS.reset();
    let before = FORENSIC_COUNTERS.snapshot();

    // Single neighbors() call
    use sqlitegraph::backend::{BackendDirection, NeighborQuery};
    let query = NeighborQuery {
        direction: BackendDirection::Outgoing,
        edge_type: None,
    };
    let neighbors = backend
        .neighbors(SnapshotId::current(), center_id, query)
        .unwrap();

    let after = FORENSIC_COUNTERS.snapshot();
    let delta = before.diff(&after);

    delta.print_report();

    assert_eq!(delta.logical_neighbors_calls, 1);
    assert_eq!(neighbors.len(), 100);
    println!("Retrieved {} neighbors\n", neighbors.len());

    // Check for read amplification
    if delta.page_read_count > 5 {
        println!(
            "⚠️  WARNING: High page read count for neighbors: {}",
            delta.page_read_count
        );
    }
}

#[test]
#[cfg(feature = "v3-forensics")]
#[ignore]
fn forensic_neighbors_medium_db() {
    println!("\n═══════════════════════════════════════════════════════════");
    println!("      SCENARIO: neighbors() in medium DB (10K nodes)         ");
    println!("═══════════════════════════════════════════════════════════\n");

    let temp = TempDir::new().unwrap();
    let backend = V3Backend::create(temp.path().join("v3.db")).unwrap();

    // Create a star graph: node 0 connects to 1000 other nodes
    let center_id = backend
        .insert_node(NodeSpec {
            kind: "Center".to_string(),
            name: "center".to_string(),
            file_path: None,
            data: serde_json::json!({}),
        })
        .unwrap();

    for i in 1..=1000 {
        let node_id = backend
            .insert_node(NodeSpec {
                kind: "Leaf".to_string(),
                name: format!("leaf_{}", i),
                file_path: None,
                data: serde_json::json!({}),
            })
            .unwrap();

        backend
            .insert_edge(EdgeSpec {
                from: center_id,
                to: node_id,
                edge_type: "Connect".to_string(),
                data: serde_json::json!({}),
            })
            .unwrap();
    }

    FORENSIC_COUNTERS.reset();
    let before = FORENSIC_COUNTERS.snapshot();

    // Single neighbors() call
    use sqlitegraph::backend::{BackendDirection, NeighborQuery};
    let query = NeighborQuery {
        direction: BackendDirection::Outgoing,
        edge_type: None,
    };
    let neighbors = backend
        .neighbors(SnapshotId::current(), center_id, query)
        .unwrap();

    let after = FORENSIC_COUNTERS.snapshot();
    let delta = before.diff(&after);

    delta.print_report();

    assert_eq!(delta.logical_neighbors_calls, 1);
    assert_eq!(neighbors.len(), 1000);
    println!("Retrieved {} neighbors\n", neighbors.len());

    // Check for read amplification
    if delta.page_read_count > 5 {
        println!(
            "⚠️  WARNING: High page read count for neighbors: {}",
            delta.page_read_count
        );
    }
}