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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
//! MVCC Snapshot Lifecycle Edge Case Tests
//!
//! **Purpose:** Validate snapshot lifecycle behavior under edge conditions
//! **Scope:** Empty graphs, large graphs, rapid lifecycle, memory pressure
//! **Focus:** Snapshot lifecycle edge cases, stress testing, memory validation
//!
//! These tests verify that MVCC-lite snapshots handle edge cases correctly
//! including empty graphs, large graphs, rapid creation/destruction, and
/// special scenarios like transaction rollbacks and deleted nodes.
use sqlitegraph::{GraphEdgeCreate, GraphEntityCreate, SqliteGraph, SqliteGraphError};
use std::time::{Duration, Instant};

//
// TEST HELPERS
//

/// Helper: Get node count from graph
fn node_count(graph: &SqliteGraph) -> Result<i64, SqliteGraphError> {
    let ids = graph.list_entity_ids()?;
    Ok(ids.len() as i64)
}

/// Helper: Get edge count from graph
fn edge_count(graph: &SqliteGraph) -> Result<i64, SqliteGraphError> {
    let entity_ids = graph.list_entity_ids()?;
    let mut total_edges = 0;
    for &id in &entity_ids {
        let outgoing = graph.query().outgoing(id)?;
        total_edges += outgoing.len();
    }
    Ok(total_edges as i64)
}

/// Helper: Warm the cache by reading all adjacency data
fn warm_cache(graph: &SqliteGraph) -> Result<(), SqliteGraphError> {
    let entity_ids = graph.list_entity_ids()?;
    for &id in &entity_ids {
        let _ = graph.query().outgoing(id);
        let _ = graph.query().incoming(id);
    }
    Ok(())
}

/// Helper: Insert entity using proper API
fn insert_entity(graph: &SqliteGraph, create: GraphEntityCreate) -> Result<i64, SqliteGraphError> {
    let entity = sqlitegraph::GraphEntity {
        id: 0, // Will be assigned by database
        kind: create.kind,
        name: create.name,
        file_path: create.file_path,
        data: create.data,
    };
    graph.insert_entity(&entity)
}

/// Helper: Insert edge using proper API
fn insert_edge(graph: &SqliteGraph, create: GraphEdgeCreate) -> Result<i64, SqliteGraphError> {
    let edge = sqlitegraph::GraphEdge {
        id: 0, // Will be assigned by database
        from_id: create.from_id,
        to_id: create.to_id,
        edge_type: create.edge_type,
        data: create.data,
    };
    graph.insert_edge(&edge)
}

/// Helper: Create test graph with sample data
fn create_test_graph() -> Result<SqliteGraph, SqliteGraphError> {
    let graph = SqliteGraph::open_in_memory()?;

    // Create test entities
    let entity1 = GraphEntityCreate {
        kind: "function".to_string(),
        name: "main".to_string(),
        file_path: Some("src/main.rs".to_string()),
        data: serde_json::json!({"line": 10}),
    };

    let entity2 = GraphEntityCreate {
        kind: "function".to_string(),
        name: "helper".to_string(),
        file_path: Some("src/helper.rs".to_string()),
        data: serde_json::json!({"line": 5}),
    };

    let entity3 = GraphEntityCreate {
        kind: "variable".to_string(),
        name: "config".to_string(),
        file_path: Some("src/config.rs".to_string()),
        data: serde_json::json!({"type": "String"}),
    };

    let id1 = insert_entity(&graph, entity1)?;
    let id2 = insert_entity(&graph, entity2)?;
    let id3 = insert_entity(&graph, entity3)?;

    // Create test edges
    let edge1 = GraphEdgeCreate {
        from_id: id1,
        to_id: id2,
        edge_type: "calls".to_string(),
        data: serde_json::json!({"line": 15}),
    };

    let edge2 = GraphEdgeCreate {
        from_id: id1,
        to_id: id3,
        edge_type: "reads".to_string(),
        data: serde_json::json!({"line": 12}),
    };

    insert_edge(&graph, edge1)?;
    insert_edge(&graph, edge2)?;

    Ok(graph)
}

//
// GROUP 1: EMPTY GRAPH SNAPSHOTS
//

#[test]
fn test_empty_graph_snapshot() -> Result<(), SqliteGraphError> {
    // Scenario: Create snapshot of empty graph
    // Expected: Snapshot has 0 nodes and 0 edges

    let graph = SqliteGraph::open_in_memory()?;

    // Warm cache (no-op for empty graph)
    warm_cache(&graph)?;

    // Create snapshot
    let snapshot = graph.acquire_snapshot()?;

    // Verify empty state
    assert_eq!(snapshot.node_count(), 0);
    assert_eq!(snapshot.edge_count(), 0);

    // Verify no nodes exist
    assert!(!snapshot.contains_node(1));
    assert!(!snapshot.contains_node(999));

    // Verify neighbor queries return None
    assert_eq!(snapshot.get_outgoing(1), None);
    assert_eq!(snapshot.get_incoming(1), None);

    Ok(())
}

#[test]
fn test_empty_graph_snapshot_after_writes() -> Result<(), SqliteGraphError> {
    // Scenario: Empty snapshot, then writes, verify snapshot unchanged
    // Expected: Empty snapshot remains empty after writes

    let graph = SqliteGraph::open_in_memory()?;

    // Acquire empty snapshot
    warm_cache(&graph)?;
    let snapshot_empty = graph.acquire_snapshot()?;
    assert_eq!(snapshot_empty.node_count(), 0);

    // Add data
    for i in 0..10 {
        insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "test".to_string(),
                name: format!("test_{}", i),
                file_path: Some(format!("test_{}.rs", i)),
                data: serde_json::json!({}),
            },
        )?;
    }

    // Verify empty snapshot still empty
    assert_eq!(snapshot_empty.node_count(), 0);
    assert_eq!(snapshot_empty.edge_count(), 0);

    // Verify new snapshot sees data
    warm_cache(&graph)?;
    let snapshot_populated = graph.acquire_snapshot()?;
    assert!(snapshot_populated.node_count() > 0);

    Ok(())
}

#[test]
fn test_multiple_empty_snapshots() -> Result<(), SqliteGraphError> {
    // Scenario: Create multiple snapshots of empty graph
    // Expected: All snapshots have 0 nodes

    let graph = SqliteGraph::open_in_memory()?;

    warm_cache(&graph)?;

    // Create multiple snapshots
    let snapshot1 = graph.acquire_snapshot()?;
    let snapshot2 = graph.acquire_snapshot()?;
    let snapshot3 = graph.acquire_snapshot()?;

    // All should be empty
    assert_eq!(snapshot1.node_count(), 0);
    assert_eq!(snapshot2.node_count(), 0);
    assert_eq!(snapshot3.node_count(), 0);

    Ok(())
}

//
// GROUP 2: LARGE GRAPH SNAPSHOTS
//

#[test]
fn test_large_graph_snapshot_memory() -> Result<(), SqliteGraphError> {
    // Scenario: Create graph with 100K+ nodes, acquire multiple snapshots
    // Expected: All snapshots succeed, no unbounded memory growth

    let graph = SqliteGraph::open_in_memory()?;

    // Create large graph (10K nodes to keep test fast)
    let num_nodes = 10_000;

    println!("Creating {} nodes...", num_nodes);
    for i in 0..num_nodes {
        insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "large".to_string(),
                name: format!("large_node_{}", i),
                file_path: Some(format!("large_{}.rs", i)),
                data: serde_json::json!({"index": i}),
            },
        )?;
    }

    // Warm cache
    println!("Warming cache...");
    warm_cache(&graph)?;

    let total_nodes = node_count(&graph)?;
    println!("Total nodes: {}", total_nodes);

    // Acquire multiple snapshots
    println!("Acquiring snapshots...");
    let snapshot1 = graph.acquire_snapshot()?;
    let snapshot2 = graph.acquire_snapshot()?;
    let snapshot3 = graph.acquire_snapshot()?;

    // Verify all snapshots have same data
    assert_eq!(snapshot1.node_count() as i64, total_nodes);
    assert_eq!(snapshot2.node_count() as i64, total_nodes);
    assert_eq!(snapshot3.node_count() as i64, total_nodes);

    println!("All snapshots consistent with {} nodes", total_nodes);

    Ok(())
}

#[test]
fn test_large_graph_snapshot_performance() -> Result<(), SqliteGraphError> {
    // Scenario: Measure snapshot acquisition latency for large graph
    // Expected: Acquisition completes in reasonable time

    let graph = SqliteGraph::open_in_memory()?;

    // Create moderately large graph
    let num_nodes = 5_000;

    for i in 0..num_nodes {
        insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "perf".to_string(),
                name: format!("perf_node_{}", i),
                file_path: Some(format!("perf_{}.rs", i)),
                data: serde_json::json!({}),
            },
        )?;
    }

    warm_cache(&graph)?;

    // Measure snapshot acquisition
    let start = Instant::now();
    let snapshot = graph.acquire_snapshot()?;
    let duration = start.elapsed();

    println!(
        "Snapshot acquisition for {} nodes: {:?}",
        num_nodes, duration
    );

    // Verify snapshot is valid
    assert!(snapshot.node_count() > 0);

    // Should complete in reasonable time (< 5 seconds)
    assert!(duration < Duration::from_secs(5));

    Ok(())
}

//
// GROUP 3: RAPID SNAPSHOT LIFECYCLE
//

#[test]
fn test_rapid_snapshot_lifecycle() -> Result<(), SqliteGraphError> {
    // Scenario: Create and drop 10K snapshots in rapid succession
    // Expected: All operations succeed, no memory leaks

    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    let iterations = 10_000;

    println!("Creating {} snapshots...", iterations);
    let start = Instant::now();

    for i in 0..iterations {
        let snapshot = graph.acquire_snapshot()?;

        // Verify snapshot valid
        assert!(snapshot.node_count() > 0, "Snapshot {} invalid", i);

        // Snapshot dropped here
    }

    let duration = start.elapsed();
    println!(
        "Created and dropped {} snapshots in {:?}",
        iterations, duration
    );

    // Final snapshot should still work
    let final_snapshot = graph.acquire_snapshot()?;
    assert!(final_snapshot.node_count() > 0);

    Ok(())
}

#[test]
fn test_rapid_snapshot_creation() -> Result<(), SqliteGraphError> {
    // Scenario: Create 1K snapshots as fast as possible
    // Expected: All succeed, performance reasonable

    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    let mut snapshots = Vec::new();
    let count = 1_000;

    let start = Instant::now();

    for _ in 0..count {
        snapshots.push(graph.acquire_snapshot()?);
    }

    let duration = start.elapsed();
    println!("Created {} snapshots in {:?}", count, duration);

    // Verify all snapshots valid
    for (i, snapshot) in snapshots.iter().enumerate() {
        assert!(snapshot.node_count() > 0, "Snapshot {} invalid", i);
    }

    // Should be fast (< 1 second for 1K snapshots)
    assert!(duration < Duration::from_secs(1));

    Ok(())
}

#[test]
fn test_snapshot_clone_stress() -> Result<(), SqliteGraphError> {
    // Scenario: Clone snapshot many times
    // Expected: All clones work, cheap operation

    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    let snapshot = Arc::new(graph.acquire_snapshot()?);

    let start = Instant::now();

    // Clone 10K times
    for _ in 0..10_000 {
        let _clone = Arc::clone(&snapshot);
    }

    let duration = start.elapsed();
    println!("10K Arc clones in {:?}", duration);

    // Arc::clone should be very fast (< 100ms)
    assert!(duration < Duration::from_millis(100));

    Ok(())
}

//
// GROUP 4: SNAPSHOT DURING TRANSACTION ROLLBACK
//

#[test]
fn test_snapshot_during_transaction_commit() -> Result<(), SqliteGraphError> {
    // Scenario: Acquire snapshot, then transaction commit
    // Expected: Snapshot unaffected by committed transaction

    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    // Acquire initial snapshot
    let snapshot1 = graph.acquire_snapshot()?;
    let count1 = snapshot1.node_count();

    // Perform writes (SQLite auto-commits each statement)
    for i in 0..5 {
        insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "commit_test".to_string(),
                name: format!("commit_func_{}", i),
                file_path: Some(format!("commit_{}.rs", i)),
                data: serde_json::json!({}),
            },
        )?;
    }

    // Verify snapshot1 unchanged
    assert_eq!(snapshot1.node_count(), count1);

    // New snapshot sees committed data
    warm_cache(&graph)?;
    let snapshot2 = graph.acquire_snapshot()?;
    assert!(snapshot2.node_count() > count1);

    Ok(())
}

#[test]
fn test_snapshot_isolation_with_deletes() -> Result<(), SqliteGraphError> {
    // Scenario: Create snapshot, then delete nodes from graph
    // Expected: Snapshot still sees deleted nodes

    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    // Acquire snapshot
    let snapshot = graph.acquire_snapshot()?;
    let original_count = snapshot.node_count();

    // Verify snapshot sees all nodes
    assert!(original_count > 0);

    // Delete a node from main graph
    let entity_ids = graph.list_entity_ids()?;
    if !entity_ids.is_empty() {
        graph.delete_entity(entity_ids[0])?;
    }

    // Verify main graph changed
    let new_count = node_count(&graph)?;
    assert!(new_count < original_count as i64);

    // Verify snapshot unchanged (still sees deleted node)
    assert_eq!(snapshot.node_count(), original_count);

    Ok(())
}

#[test]
fn test_snapshot_with_deleted_node_visibility() -> Result<(), SqliteGraphError> {
    // Scenario: Verify snapshot maintains visibility of deleted nodes
    // Expected: Snapshot preserves adjacency of deleted nodes

    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    let entity_ids = graph.list_entity_ids()?;
    if entity_ids.len() < 2 {
        return Ok(()); // Skip if not enough entities
    }

    // Get neighbors before deletion
    let test_node = entity_ids[0];
    let neighbors_before = graph.query().outgoing(test_node)?;

    // Acquire snapshot
    let snapshot = graph.acquire_snapshot()?;

    // Verify snapshot sees neighbors
    let snapshot_neighbors = snapshot.get_outgoing(test_node);
    assert_eq!(snapshot_neighbors, Some(&neighbors_before));

    // Delete node from main graph
    graph.delete_entity(test_node)?;

    // Verify snapshot still sees deleted node and its neighbors
    assert!(snapshot.contains_node(test_node));
    assert_eq!(snapshot.get_outgoing(test_node), Some(&neighbors_before));

    Ok(())
}

//
// GROUP 5: SPECIAL SCENARIOS
//

#[test]
fn test_snapshot_with_single_node() -> Result<(), SqliteGraphError> {
    // Scenario: Graph with single node, no edges
    // Expected: Snapshot handles single node correctly

    let graph = SqliteGraph::open_in_memory()?;

    // Create single node
    let entity_id = insert_entity(
        &graph,
        GraphEntityCreate {
            kind: "single".to_string(),
            name: "single_node".to_string(),
            file_path: Some("single.rs".to_string()),
            data: serde_json::json!({}),
        },
    )?;

    warm_cache(&graph)?;

    // Acquire snapshot
    let snapshot = graph.acquire_snapshot()?;

    // Verify single node
    assert_eq!(snapshot.node_count(), 1);
    assert_eq!(snapshot.edge_count(), 0);

    // Verify neighbor access
    assert!(snapshot.contains_node(entity_id));
    assert_eq!(snapshot.get_outgoing(entity_id), Some(&vec![]));
    assert_eq!(snapshot.get_incoming(entity_id), Some(&vec![]));

    Ok(())
}

#[test]
fn test_snapshot_with_disconnected_components() -> Result<(), SqliteGraphError> {
    // Scenario: Graph with multiple disconnected components
    // Expected: Snapshot sees all components

    let graph = SqliteGraph::open_in_memory()?;

    // Create component 1
    let id1 = insert_entity(
        &graph,
        GraphEntityCreate {
            kind: "comp1".to_string(),
            name: "comp1_node1".to_string(),
            file_path: Some("comp1.rs".to_string()),
            data: serde_json::json!({}),
        },
    )?;
    let id2 = insert_entity(
        &graph,
        GraphEntityCreate {
            kind: "comp1".to_string(),
            name: "comp1_node2".to_string(),
            file_path: Some("comp1.rs".to_string()),
            data: serde_json::json!({}),
        },
    )?;

    // Create component 2 (disconnected)
    let id3 = insert_entity(
        &graph,
        GraphEntityCreate {
            kind: "comp2".to_string(),
            name: "comp2_node1".to_string(),
            file_path: Some("comp2.rs".to_string()),
            data: serde_json::json!({}),
        },
    )?;
    let id4 = insert_entity(
        &graph,
        GraphEntityCreate {
            kind: "comp2".to_string(),
            name: "comp2_node2".to_string(),
            file_path: Some("comp2.rs".to_string()),
            data: serde_json::json!({}),
        },
    )?;

    // Connect component 1
    insert_edge(
        &graph,
        GraphEdgeCreate {
            from_id: id1,
            to_id: id2,
            edge_type: "connects".to_string(),
            data: serde_json::json!({}),
        },
    )?;

    // Connect component 2
    insert_edge(
        &graph,
        GraphEdgeCreate {
            from_id: id3,
            to_id: id4,
            edge_type: "connects".to_string(),
            data: serde_json::json!({}),
        },
    )?;

    warm_cache(&graph)?;

    // Acquire snapshot
    let snapshot = graph.acquire_snapshot()?;

    // Verify all nodes present
    assert_eq!(snapshot.node_count(), 4);
    assert_eq!(snapshot.edge_count(), 2);

    // Verify component 1 connectivity
    let neighbors1 = snapshot.get_outgoing(id1);
    assert_eq!(neighbors1, Some(&vec![id2]));

    // Verify component 2 connectivity
    let neighbors3 = snapshot.get_outgoing(id3);
    assert_eq!(neighbors3, Some(&vec![id4]));

    Ok(())
}

#[test]
fn test_snapshot_consistency_under_modifications() -> Result<(), SqliteGraphError> {
    // Scenario: Snapshot remains consistent while graph is modified
    // Expected: Snapshot state immutable despite modifications

    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    let entity_ids = graph.list_entity_ids()?;

    // Acquire snapshot
    let snapshot = graph.acquire_snapshot()?;
    let original_count = snapshot.node_count();
    let original_edges = snapshot.edge_count();

    // Perform various modifications
    for i in 0..10 {
        insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "mod".to_string(),
                name: format!("mod_func_{}", i),
                file_path: Some(format!("mod_{}.rs", i)),
                data: serde_json::json!({}),
            },
        )?;

        if !entity_ids.is_empty() {
            let new_id = insert_entity(
                &graph,
                GraphEntityCreate {
                    kind: "edge_mod".to_string(),
                    name: format!("edge_mod_{}", i),
                    file_path: Some(format!("edge_mod_{}.rs", i)),
                    data: serde_json::json!({}),
                },
            )?;

            insert_edge(
                &graph,
                GraphEdgeCreate {
                    from_id: entity_ids[0],
                    to_id: new_id,
                    edge_type: "mod_edge".to_string(),
                    data: serde_json::json!({}),
                },
            )?;
        }
    }

    // Verify snapshot unchanged
    assert_eq!(snapshot.node_count(), original_count);
    assert_eq!(snapshot.edge_count(), original_edges);

    Ok(())
}

#[test]
fn test_multiple_snapshots_different_states() -> Result<(), SqliteGraphError> {
    // Scenario: Acquire snapshots at different graph states
    // Expected: Each snapshot reflects state at acquisition time

    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    // Snapshot 1: Initial state
    let snapshot1 = graph.acquire_snapshot()?;
    let count1 = snapshot1.node_count();

    // Add data
    for i in 0..5 {
        insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "phase1".to_string(),
                name: format!("phase1_{}", i),
                file_path: Some(format!("phase1_{}.rs", i)),
                data: serde_json::json!({}),
            },
        )?;
    }

    warm_cache(&graph)?;

    // Snapshot 2: After phase 1
    let snapshot2 = graph.acquire_snapshot()?;
    let count2 = snapshot2.node_count();

    // Add more data
    for i in 0..5 {
        insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "phase2".to_string(),
                name: format!("phase2_{}", i),
                file_path: Some(format!("phase2_{}.rs", i)),
                data: serde_json::json!({}),
            },
        )?;
    }

    warm_cache(&graph)?;

    // Snapshot 3: After phase 2
    let snapshot3 = graph.acquire_snapshot()?;
    let count3 = snapshot3.node_count();

    // Verify monotonic growth and isolation
    assert!(count1 < count2);
    assert!(count2 < count3);

    assert_eq!(snapshot1.node_count(), count1);
    assert_eq!(snapshot2.node_count(), count2);
    assert_eq!(snapshot3.node_count(), count3);

    Ok(())
}

//
// GROUP 6: SNAPSHOT LIFECYCLE EDGE CASES
//

#[test]
fn test_snapshot_outlives_graph() -> Result<(), SqliteGraphError> {
    // Scenario: Snapshot outlives graph (should work with Arc)
    // Expected: Snapshot remains valid even after graph is dropped
    let snapshot = {
        let graph = create_test_graph()?;
        warm_cache(&graph)?;

        // Acquire snapshot and move it out
        let snap = graph.acquire_snapshot()?;
        snap
    };

    // Graph is dropped here, but snapshot should still work
    // (Snapshot holds Arc<SnapshotState>, which is independent)

    let count = snapshot.node_count();
    assert!(count > 0, "Snapshot should remain valid");

    // Verify snapshot data is still accessible
    let _ = snapshot.edge_count();

    Ok(())
}

#[test]
fn test_snapshot_clone_independence() -> Result<(), SqliteGraphError> {
    // Scenario: Clone snapshot and verify independence
    // Expected: Both clones see same state, independent modifications
    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    let snapshot1 = Arc::new(graph.acquire_snapshot()?);
    let snapshot2 = Arc::clone(&snapshot1);

    // Both should see same data
    assert_eq!(snapshot1.node_count(), snapshot2.node_count());
    assert_eq!(snapshot1.edge_count(), snapshot2.edge_count());

    // Modify graph
    let _ = insert_entity(
        &graph,
        GraphEntityCreate {
            kind: "clone_test".to_string(),
            name: "clone_node".to_string(),
            file_path: Some("clone.rs".to_string()),
            data: serde_json::json!({}),
        },
    );

    warm_cache(&graph)?;

    // Both snapshots should still see original state
    let original_count = snapshot1.node_count();
    assert_eq!(snapshot2.node_count(), original_count);

    // New snapshot should see more nodes
    let new_snapshot = graph.acquire_snapshot()?;
    assert!(new_snapshot.node_count() > original_count);

    Ok(())
}

#[test]
fn test_nested_snapshots() -> Result<(), SqliteGraphError> {
    // Scenario: Create snapshot, then another snapshot (not of snapshot, but sequential)
    // Expected: Both snapshots are independent
    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    // First snapshot
    let snapshot1 = graph.acquire_snapshot()?;
    let count1 = snapshot1.node_count();

    // Second snapshot (not nested, but sequential)
    let snapshot2 = graph.acquire_snapshot()?;
    let count2 = snapshot2.node_count();

    // Should be equal (no modifications between)
    assert_eq!(count1, count2);
    assert_eq!(snapshot1.node_count(), snapshot2.node_count());

    // Modify graph
    let _ = insert_entity(
        &graph,
        GraphEntityCreate {
            kind: "nested".to_string(),
            name: "nested_node".to_string(),
            file_path: Some("nested.rs".to_string()),
            data: serde_json::json!({}),
        },
    );

    warm_cache(&graph)?;

    // Third snapshot
    let snapshot3 = graph.acquire_snapshot()?;

    // First two unchanged, third sees modification
    assert_eq!(snapshot1.node_count(), count1);
    assert_eq!(snapshot2.node_count(), count2);
    assert!(snapshot3.node_count() > count2);

    Ok(())
}

#[test]
fn test_snapshot_consistency_with_writes() -> Result<(), SqliteGraphError> {
    // Scenario: Verify snapshot remains consistent despite writes
    // Expected: Snapshot never changes after acquisition
    let graph = create_test_graph()?;
    warm_cache(&graph)?;

    let snapshot = graph.acquire_snapshot()?;
    let original_count = snapshot.node_count();
    let original_edges = snapshot.edge_count();

    // Perform many writes
    for i in 0..20 {
        let _ = insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "write_test".to_string(),
                name: format!("write_node_{}", i),
                file_path: Some(format!("write_{}.rs", i)),
                data: serde_json::json!({}),
            },
        );
    }

    warm_cache(&graph)?;

    // Verify snapshot unchanged
    assert_eq!(snapshot.node_count(), original_count);
    assert_eq!(snapshot.edge_count(), original_edges);

    // Verify graph changed
    let final_count = node_count(&graph)?;
    assert!(final_count > original_count as i64);

    Ok(())
}

//
// GROUP 7: TRANSACTION EDGE CASES
//

#[test]
fn test_empty_transaction() -> Result<(), SqliteGraphError> {
    // Scenario: Transaction with no operations (SQLite auto-commits each statement)
    // Expected: Empty state is valid, no errors
    let graph = SqliteGraph::open_in_memory()?;

    // Auto-commit each statement in SQLite
    let ids = graph.list_entity_ids()?;
    assert!(ids.is_empty(), "Graph should be empty");

    // "Empty transaction" - no operations performed
    // Verify state is consistent
    let count_after = node_count(&graph)?;
    assert_eq!(count_after, 0, "Count should still be 0");

    Ok(())
}

#[test]
fn test_transaction_with_failed_operations() -> Result<(), SqliteGraphError> {
    // Scenario: Transaction mix of successful and failed operations
    // Expected: Successful operations commit, failed ones error
    let graph = SqliteGraph::open_in_memory()?;

    // Successful operation
    let id1 = insert_entity(
        &graph,
        GraphEntityCreate {
            kind: "test".to_string(),
            name: "success".to_string(),
            file_path: Some("success.rs".to_string()),
            data: serde_json::json!({}),
        },
    )?;

    // Try to create edge to non-existent node (will fail)
    let result = insert_edge(
        &graph,
        GraphEdgeCreate {
            from_id: id1,
            to_id: 99999, // Non-existent
            edge_type: "fails".to_string(),
            data: serde_json::json!({}),
        },
    );

    // Edge creation should fail
    assert!(result.is_err(), "Edge to non-existent node should fail");

    // But entity should still exist (SQLite auto-commits the insert)
    let ids = graph.list_entity_ids()?;
    assert_eq!(ids.len(), 1, "Entity should exist");

    Ok(())
}

#[test]
fn test_partial_modification_state() -> Result<(), SqliteGraphError> {
    // Scenario: Partial graph modification with errors
    // Expected: Successful modifications persist, errors don't corrupt state
    let graph = create_test_graph()?;

    let initial_count = node_count(&graph)?;

    // Add some entities successfully
    for i in 0..5 {
        let _ = insert_entity(
            &graph,
            GraphEntityCreate {
                kind: "partial".to_string(),
                name: format!("partial_{}", i),
                file_path: Some(format!("partial_{}.rs", i)),
                data: serde_json::json!({}),
            },
        );
    }

    // Try to create edges to non-existent nodes
    let entity_ids = graph.list_entity_ids()?;
    if !entity_ids.is_empty() {
        let _ = insert_edge(
            &graph,
            GraphEdgeCreate {
                from_id: entity_ids[0],
                to_id: 99998,
                edge_type: "bad_edge".to_string(),
                data: serde_json::json!({}),
            },
        );
    }

    // Verify state is consistent
    let final_count = node_count(&graph)?;
    assert!(
        final_count > initial_count,
        "Successful inserts should persist"
    );

    // Verify graph is still functional
    let _ = graph.acquire_snapshot()?;

    Ok(())
}

use std::sync::Arc;