memscope-rs 0.2.0

A memory tracking library for Rust applications.
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
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
//! Circular reference detection for smart pointers
//!
//! This module provides functionality to detect circular references in Rc/Arc
//! smart pointers that can lead to memory leaks.

use crate::capture::types::{AllocationInfo, SmartPointerInfo, SmartPointerType};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// Represents a detected circular reference
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CircularReference {
    /// The cycle path showing the circular reference chain
    pub cycle_path: Vec<CircularReferenceNode>,

    /// Suggested positions where Weak references should be used to break the cycle
    pub suggested_weak_positions: Vec<usize>,

    /// Estimated memory that would be leaked due to this cycle
    pub estimated_leaked_memory: usize,

    /// Severity level of this circular reference
    pub severity: CircularReferenceSeverity,

    /// Type of circular reference detected
    pub cycle_type: CircularReferenceType,
}

/// Node in a circular reference path
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CircularReferenceNode {
    /// Pointer address of this node
    pub ptr: usize,

    /// Data pointer this node points to
    pub data_ptr: usize,

    /// Variable name if available
    pub var_name: Option<String>,

    /// Type name of the smart pointer
    pub type_name: Option<String>,

    /// Smart pointer type
    pub pointer_type: SmartPointerType,

    /// Current reference count
    pub ref_count: usize,
}

/// Severity levels for circular references
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CircularReferenceSeverity {
    /// Low severity - small memory impact
    Low,
    /// Medium severity - moderate memory impact
    Medium,
    /// High severity - significant memory impact
    High,
    /// Critical severity - large memory impact or complex cycle
    Critical,
}

/// Types of circular references
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CircularReferenceType {
    /// Simple two-node cycle (A -> B -> A)
    Simple,
    /// Complex multi-node cycle
    Complex,
    /// Self-referencing cycle (A -> A)
    SelfReference,
    /// Nested cycles (cycles within cycles)
    Nested,
}

/// Analysis result for circular reference detection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CircularReferenceAnalysis {
    /// All detected circular references
    pub circular_references: Vec<CircularReference>,

    /// Total number of smart pointers analyzed
    pub total_smart_pointers: usize,

    /// Number of smart pointers involved in cycles
    pub pointers_in_cycles: usize,

    /// Total estimated leaked memory
    pub total_leaked_memory: usize,

    /// Analysis statistics
    pub statistics: CircularReferenceStatistics,
}

/// Statistics for circular reference analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CircularReferenceStatistics {
    /// Count by severity
    pub by_severity: HashMap<String, usize>,

    /// Count by type
    pub by_type: HashMap<String, usize>,

    /// Count by smart pointer type
    pub by_pointer_type: HashMap<String, usize>,

    /// Average cycle length
    pub average_cycle_length: f64,

    /// Largest cycle size
    pub largest_cycle_size: usize,
}

/// Graph representation for circular reference detection
#[derive(Debug)]
struct ReferenceGraph {
    /// Adjacency list: ptr -> list of data_ptrs it references
    adjacency: HashMap<usize, Vec<usize>>,

    /// Reverse mapping: data_ptr -> list of ptrs that reference it
    reverse_refs: HashMap<usize, Vec<usize>>,

    /// Smart pointer information by ptr
    smart_pointers: HashMap<usize, SmartPointerInfo>,

    /// Allocation information by ptr
    allocations: HashMap<usize, AllocationInfo>,
}

impl ReferenceGraph {
    /// Create a new reference graph from allocations
    fn new(allocations: &[AllocationInfo]) -> Self {
        let mut graph = ReferenceGraph {
            adjacency: HashMap::new(),
            reverse_refs: HashMap::new(),
            smart_pointers: HashMap::new(),
            allocations: HashMap::new(),
        };

        // Build the graph from smart pointer allocations
        for allocation in allocations {
            if let Some(ref smart_info) = allocation.smart_pointer_info {
                // Skip weak references for cycle detection (they don't create strong cycles)
                if smart_info.is_weak_reference {
                    continue;
                }

                graph
                    .smart_pointers
                    .insert(allocation.ptr, smart_info.clone());
                graph.allocations.insert(allocation.ptr, allocation.clone());

                // Add edge from this pointer to its data
                graph.adjacency.entry(allocation.ptr).or_default();

                // Add reverse reference from data to this pointer
                graph
                    .reverse_refs
                    .entry(smart_info.data_ptr)
                    .or_default()
                    .push(allocation.ptr);

                // Add edges to cloned pointers (they share the same data)
                for &clone_ptr in &smart_info.clones {
                    graph
                        .adjacency
                        .entry(allocation.ptr)
                        .or_default()
                        .push(clone_ptr);
                }

                // Add edge from cloned_from if it exists
                if let Some(source_ptr) = smart_info.cloned_from {
                    graph
                        .adjacency
                        .entry(source_ptr)
                        .or_default()
                        .push(allocation.ptr);
                }
            }
        }

        graph
    }

    /// Detect all circular references in the graph
    fn detect_cycles(&self) -> Vec<Vec<usize>> {
        let mut cycles = Vec::new();
        let mut visited = HashSet::new();
        let mut rec_stack = HashSet::new();
        let mut path = Vec::new();

        for &ptr in self.smart_pointers.keys() {
            if !visited.contains(&ptr) {
                self.dfs_detect_cycles(ptr, &mut visited, &mut rec_stack, &mut path, &mut cycles);
            }
        }

        cycles
    }

    /// Depth-first search to detect cycles
    fn dfs_detect_cycles(
        &self,
        ptr: usize,
        visited: &mut HashSet<usize>,
        rec_stack: &mut HashSet<usize>,
        path: &mut Vec<usize>,
        cycles: &mut Vec<Vec<usize>>,
    ) {
        visited.insert(ptr);
        rec_stack.insert(ptr);
        path.push(ptr);

        if let Some(neighbors) = self.adjacency.get(&ptr) {
            for &neighbor in neighbors {
                // Check for self-loop (node points to itself)
                if neighbor == ptr {
                    // Self-loop detected - record as a single-node cycle
                    cycles.push(vec![ptr]);
                    tracing::trace!("Self-loop detected at ptr=0x{:x}", ptr);
                    continue;
                }

                if !visited.contains(&neighbor) {
                    self.dfs_detect_cycles(neighbor, visited, rec_stack, path, cycles);
                } else if rec_stack.contains(&neighbor) {
                    // Found a cycle - extract the cycle path
                    if let Some(cycle_start) = path.iter().position(|&x| x == neighbor) {
                        let cycle = path[cycle_start..].to_vec();
                        cycles.push(cycle);
                    }
                }
            }
        }

        path.pop();
        rec_stack.remove(&ptr);
    }
}

/// Detect circular references in smart pointer allocations
pub fn detect_circular_references(allocations: &[AllocationInfo]) -> CircularReferenceAnalysis {
    let graph = ReferenceGraph::new(allocations);
    let raw_cycles = graph.detect_cycles();

    let mut circular_references = Vec::new();
    let mut total_leaked_memory = 0;
    let mut pointers_in_cycles = HashSet::new();

    // Process each detected cycle
    for cycle_path in raw_cycles {
        if cycle_path.len() < 2 {
            continue; // Skip trivial cycles
        }

        let circular_ref = analyze_cycle(&cycle_path, &graph);
        total_leaked_memory += circular_ref.estimated_leaked_memory;

        for node in &circular_ref.cycle_path {
            pointers_in_cycles.insert(node.ptr);
        }

        circular_references.push(circular_ref);
    }

    // Generate statistics
    let statistics = generate_statistics(&circular_references);

    CircularReferenceAnalysis {
        circular_references,
        total_smart_pointers: graph.smart_pointers.len(),
        pointers_in_cycles: pointers_in_cycles.len(),
        total_leaked_memory,
        statistics,
    }
}

/// Analyze a single cycle to create a CircularReference
fn analyze_cycle(cycle_path: &[usize], graph: &ReferenceGraph) -> CircularReference {
    let mut nodes = Vec::new();
    let mut total_memory = 0;

    // Build cycle nodes
    for &ptr in cycle_path {
        if let (Some(smart_info), Some(allocation)) =
            (graph.smart_pointers.get(&ptr), graph.allocations.get(&ptr))
        {
            let node = CircularReferenceNode {
                ptr,
                data_ptr: smart_info.data_ptr,
                var_name: allocation.var_name.clone(),
                type_name: allocation.type_name.clone(),
                pointer_type: smart_info.pointer_type.clone(),
                ref_count: smart_info
                    .latest_ref_counts()
                    .map(|snapshot| snapshot.strong_count)
                    .unwrap_or(1),
            };

            total_memory += allocation.size;
            nodes.push(node);
        }
    }

    // Determine cycle type
    let cycle_type = if cycle_path.len() == 1 {
        CircularReferenceType::SelfReference
    } else if cycle_path.len() == 2 {
        CircularReferenceType::Simple
    } else {
        CircularReferenceType::Complex
    };

    // Determine severity based on memory impact and cycle complexity
    let severity = if total_memory > 1024 * 1024 {
        // > 1MB
        CircularReferenceSeverity::Critical
    } else if total_memory > 64 * 1024 {
        // > 64KB
        CircularReferenceSeverity::High
    } else if total_memory > 4 * 1024 {
        // > 4KB
        CircularReferenceSeverity::Medium
    } else {
        CircularReferenceSeverity::Low
    };

    // Suggest weak reference positions (break the cycle at the longest-lived reference)
    let suggested_weak_positions = suggest_weak_positions(&nodes);

    CircularReference {
        cycle_path: nodes,
        suggested_weak_positions,
        estimated_leaked_memory: total_memory,
        severity,
        cycle_type,
    }
}

/// Suggest positions where weak references should be used to break cycles
fn suggest_weak_positions(nodes: &[CircularReferenceNode]) -> Vec<usize> {
    // Simple heuristic: suggest breaking at the node with the highest reference count
    // (likely to be the most shared and least critical to make weak)
    if let Some((index, _)) = nodes
        .iter()
        .enumerate()
        .max_by_key(|(_, node)| node.ref_count)
    {
        vec![index]
    } else {
        vec![0] // Fallback to first position
    }
}

/// Generate statistics for the analysis
fn generate_statistics(circular_references: &[CircularReference]) -> CircularReferenceStatistics {
    let mut by_severity = HashMap::new();
    let mut by_type = HashMap::new();
    let mut by_pointer_type = HashMap::new();
    let mut total_cycle_length = 0;
    let mut largest_cycle_size = 0;

    for circular_ref in circular_references {
        // Count by severity
        let severity_key = format!("{:?}", circular_ref.severity);
        *by_severity.entry(severity_key).or_insert(0) += 1;

        // Count by type
        let type_key = format!("{:?}", circular_ref.cycle_type);
        *by_type.entry(type_key).or_insert(0) += 1;

        // Count by pointer type
        for node in &circular_ref.cycle_path {
            let pointer_type_key = format!("{:?}", node.pointer_type);
            *by_pointer_type.entry(pointer_type_key).or_insert(0) += 1;
        }

        // Track cycle sizes
        let cycle_length = circular_ref.cycle_path.len();
        total_cycle_length += cycle_length;
        largest_cycle_size = largest_cycle_size.max(cycle_length);
    }

    let average_cycle_length = if circular_references.is_empty() {
        0.0
    } else {
        total_cycle_length as f64 / circular_references.len() as f64
    };

    CircularReferenceStatistics {
        by_severity,
        by_type,
        by_pointer_type,
        average_cycle_length,
        largest_cycle_size,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capture::types::{RefCountSnapshot, SmartPointerInfo, SmartPointerType};
    use crate::utils::current_thread_id_u64;

    use std::thread;

    #[test]
    fn test_circular_reference_node_creation() {
        let node = CircularReferenceNode {
            ptr: 0x1000,
            data_ptr: 0x2000,
            var_name: Some("test_node".to_string()),
            type_name: Some("Rc<RefCell<Node>>".to_string()),
            pointer_type: SmartPointerType::Rc,
            ref_count: 1,
        };

        assert_eq!(node.ptr, 0x1000);
        assert_eq!(node.data_ptr, 0x2000);
        assert_eq!(node.var_name, Some("test_node".to_string()));
        assert_eq!(node.type_name, Some("Rc<RefCell<Node>>".to_string()));
        assert_eq!(node.pointer_type, SmartPointerType::Rc);
        assert_eq!(node.ref_count, 1);
    }

    #[test]
    fn test_circular_reference_creation() {
        let cycle_path = vec![
            CircularReferenceNode {
                ptr: 0x1000,
                data_ptr: 0x2000,
                var_name: Some("node_a".to_string()),
                type_name: Some("Rc<RefCell<Node>>".to_string()),
                pointer_type: SmartPointerType::Rc,
                ref_count: 1,
            },
            CircularReferenceNode {
                ptr: 0x2000,
                data_ptr: 0x1000,
                var_name: Some("node_b".to_string()),
                type_name: Some("Rc<RefCell<Node>>".to_string()),
                pointer_type: SmartPointerType::Rc,
                ref_count: 1,
            },
        ];

        let circular_ref = CircularReference {
            cycle_path: cycle_path.clone(),
            suggested_weak_positions: vec![1],
            estimated_leaked_memory: 1024,
            severity: CircularReferenceSeverity::Medium,
            cycle_type: CircularReferenceType::Simple,
        };

        assert_eq!(circular_ref.cycle_path.len(), 2);
        assert_eq!(circular_ref.suggested_weak_positions, vec![1]);
        assert_eq!(circular_ref.estimated_leaked_memory, 1024);
        assert_eq!(circular_ref.severity, CircularReferenceSeverity::Medium);
        assert_eq!(circular_ref.cycle_type, CircularReferenceType::Simple);
    }

    #[test]
    fn test_circular_reference_severity_variants() {
        let severities = [
            CircularReferenceSeverity::Low,
            CircularReferenceSeverity::Medium,
            CircularReferenceSeverity::High,
            CircularReferenceSeverity::Critical,
        ];

        // Just ensure all variants can be created and compared
        assert_eq!(severities[0], CircularReferenceSeverity::Low);
        assert_eq!(severities[1], CircularReferenceSeverity::Medium);
        assert_eq!(severities[2], CircularReferenceSeverity::High);
        assert_eq!(severities[3], CircularReferenceSeverity::Critical);
    }

    #[test]
    fn test_circular_reference_type_variants() {
        let types = [
            CircularReferenceType::Simple,
            CircularReferenceType::Complex,
            CircularReferenceType::SelfReference,
            CircularReferenceType::Nested,
        ];

        // Just ensure all variants can be created and compared
        assert_eq!(types[0], CircularReferenceType::Simple);
        assert_eq!(types[1], CircularReferenceType::Complex);
        assert_eq!(types[2], CircularReferenceType::SelfReference);
        assert_eq!(types[3], CircularReferenceType::Nested);
    }

    #[test]
    fn test_circular_reference_statistics_generation() {
        // Test with empty cycles
        let empty_cycles = vec![];
        let stats = generate_statistics(&empty_cycles);

        assert_eq!(stats.average_cycle_length, 0.0);
        assert_eq!(stats.largest_cycle_size, 0);
        assert!(stats.by_severity.is_empty());
        assert!(stats.by_type.is_empty());
        assert!(stats.by_pointer_type.is_empty());

        // Test with some cycles
        let cycles = vec![
            CircularReference {
                cycle_path: vec![CircularReferenceNode {
                    ptr: 0x1000,
                    data_ptr: 0x2000,
                    var_name: Some("node_a".to_string()),
                    type_name: Some("Rc<Node>".to_string()),
                    pointer_type: SmartPointerType::Rc,
                    ref_count: 2,
                }],
                suggested_weak_positions: vec![0],
                estimated_leaked_memory: 1024,
                severity: CircularReferenceSeverity::Low,
                cycle_type: CircularReferenceType::SelfReference,
            },
            CircularReference {
                cycle_path: vec![
                    CircularReferenceNode {
                        ptr: 0x2000,
                        data_ptr: 0x3000,
                        var_name: Some("node_b".to_string()),
                        type_name: Some("Arc<Node>".to_string()),
                        pointer_type: SmartPointerType::Arc,
                        ref_count: 3,
                    },
                    CircularReferenceNode {
                        ptr: 0x3000,
                        data_ptr: 0x2000,
                        var_name: Some("node_c".to_string()),
                        type_name: Some("Arc<Node>".to_string()),
                        pointer_type: SmartPointerType::Arc,
                        ref_count: 1,
                    },
                ],
                suggested_weak_positions: vec![0],
                estimated_leaked_memory: 2048,
                severity: CircularReferenceSeverity::Medium,
                cycle_type: CircularReferenceType::Simple,
            },
        ];

        let stats = generate_statistics(&cycles);

        assert_eq!(stats.average_cycle_length, 1.5); // (1 + 2) / 2
        assert_eq!(stats.largest_cycle_size, 2);
        assert!(!stats.by_severity.is_empty());
        assert!(!stats.by_type.is_empty());
        assert!(!stats.by_pointer_type.is_empty());

        // Check specific counts
        assert_eq!(*stats.by_severity.get("Low").unwrap_or(&0), 1);
        assert_eq!(*stats.by_severity.get("Medium").unwrap_or(&0), 1);
        assert_eq!(*stats.by_type.get("SelfReference").unwrap_or(&0), 1);
        assert_eq!(*stats.by_type.get("Simple").unwrap_or(&0), 1);
        assert_eq!(*stats.by_pointer_type.get("Rc").unwrap_or(&0), 1);
        assert_eq!(*stats.by_pointer_type.get("Arc").unwrap_or(&0), 2);
    }

    #[test]
    fn test_suggest_weak_positions() {
        // Test with empty nodes
        let empty_nodes = vec![];
        let positions = suggest_weak_positions(&empty_nodes);
        assert_eq!(positions, vec![0]); // Should fallback to position 0

        // Test with single node
        let single_node = vec![CircularReferenceNode {
            ptr: 0x1000,
            data_ptr: 0x2000,
            var_name: Some("node".to_string()),
            type_name: Some("Rc<Node>".to_string()),
            pointer_type: SmartPointerType::Rc,
            ref_count: 1,
        }];
        let positions = suggest_weak_positions(&single_node);
        assert_eq!(positions, vec![0]);

        // Test with multiple nodes, different ref counts
        let multiple_nodes = vec![
            CircularReferenceNode {
                ptr: 0x1000,
                data_ptr: 0x2000,
                var_name: Some("node_a".to_string()),
                type_name: Some("Rc<Node>".to_string()),
                pointer_type: SmartPointerType::Rc,
                ref_count: 1,
            },
            CircularReferenceNode {
                ptr: 0x2000,
                data_ptr: 0x3000,
                var_name: Some("node_b".to_string()),
                type_name: Some("Rc<Node>".to_string()),
                pointer_type: SmartPointerType::Rc,
                ref_count: 3, // Highest ref count
            },
            CircularReferenceNode {
                ptr: 0x3000,
                data_ptr: 0x1000,
                var_name: Some("node_c".to_string()),
                type_name: Some("Rc<Node>".to_string()),
                pointer_type: SmartPointerType::Rc,
                ref_count: 2,
            },
        ];
        let positions = suggest_weak_positions(&multiple_nodes);
        assert_eq!(positions, vec![1]); // Should suggest position with highest ref count
    }

    #[test]
    fn test_analyze_cycle() {
        // Create a mock graph for testing
        let mut graph = ReferenceGraph {
            adjacency: HashMap::new(),
            reverse_refs: HashMap::new(),
            smart_pointers: HashMap::new(),
            allocations: HashMap::new(),
        };

        // Add mock data to the graph
        let smart_info_a = SmartPointerInfo {
            data_ptr: 0x2000,
            pointer_type: SmartPointerType::Rc,
            is_weak_reference: false,
            clones: vec![],
            cloned_from: None,
            ref_count_history: vec![RefCountSnapshot {
                strong_count: 1,
                weak_count: 0,
                timestamp: 0,
            }],
            weak_count: None,
            is_data_owner: true,
            is_implicitly_deallocated: false,
        };

        let smart_info_b = SmartPointerInfo {
            data_ptr: 0x1000,
            pointer_type: SmartPointerType::Rc,
            is_weak_reference: false,
            clones: vec![],
            cloned_from: None,
            ref_count_history: vec![RefCountSnapshot {
                strong_count: 1,
                weak_count: 0,
                timestamp: 0,
            }],
            weak_count: None,
            is_data_owner: true,
            is_implicitly_deallocated: false,
        };

        let allocation_a = AllocationInfo {
            ptr: 0x1000,
            size: 1024,
            var_name: Some("node_a".to_string()),
            type_name: Some("Rc<Node>".to_string()),
            smart_pointer_info: Some(smart_info_a.clone()),
            scope_name: None,
            timestamp_alloc: 0,
            timestamp_dealloc: None,
            thread_id: std::thread::current().id(),
            thread_id_u64: current_thread_id_u64(),
            borrow_count: 0,
            stack_trace: None,
            is_leaked: false,
            lifetime_ms: None,
            borrow_info: None,
            clone_info: None,
            ownership_history_available: false,
            memory_layout: None,
            generic_info: None,
            dynamic_type_info: None,
            runtime_state: None,
            stack_allocation: None,
            temporary_object: None,
            fragmentation_analysis: None,
            generic_instantiation: None,
            type_relationships: None,
            type_usage: None,
            function_call_tracking: None,
            lifecycle_tracking: None,
            access_tracking: None,
            drop_chain_analysis: None,
        };

        let allocation_b = AllocationInfo {
            ptr: 0x2000,
            size: 2048,
            var_name: Some("node_b".to_string()),
            type_name: Some("Rc<Node>".to_string()),
            smart_pointer_info: Some(smart_info_b.clone()),
            scope_name: None,
            timestamp_alloc: 0,
            timestamp_dealloc: None,
            thread_id: std::thread::current().id(),
            thread_id_u64: current_thread_id_u64(),
            borrow_count: 0,
            stack_trace: None,
            is_leaked: false,
            lifetime_ms: None,
            borrow_info: None,
            clone_info: None,
            ownership_history_available: false,
            memory_layout: None,
            generic_info: None,
            dynamic_type_info: None,
            runtime_state: None,
            stack_allocation: None,
            temporary_object: None,
            fragmentation_analysis: None,
            generic_instantiation: None,
            type_relationships: None,
            type_usage: None,
            function_call_tracking: None,
            lifecycle_tracking: None,
            access_tracking: None,
            drop_chain_analysis: None,
        };

        graph.smart_pointers.insert(0x1000, smart_info_a);
        graph.smart_pointers.insert(0x2000, smart_info_b);
        graph.allocations.insert(0x1000, allocation_a);
        graph.allocations.insert(0x2000, allocation_b);

        // Test analyzing a simple cycle
        let cycle_path = vec![0x1000, 0x2000];
        let circular_ref = analyze_cycle(&cycle_path, &graph);

        assert_eq!(circular_ref.cycle_path.len(), 2);
        assert_eq!(circular_ref.estimated_leaked_memory, 3072); // 1024 + 2048
        assert_eq!(circular_ref.cycle_type, CircularReferenceType::Simple);
        assert_eq!(circular_ref.severity, CircularReferenceSeverity::Low); // 3072 bytes < 4KB threshold
        assert!(!circular_ref.suggested_weak_positions.is_empty());
    }

    #[test]
    fn test_reference_graph_creation() {
        // Test with empty allocations
        let empty_allocations = vec![];
        let graph = ReferenceGraph::new(&empty_allocations);

        assert!(graph.adjacency.is_empty());
        assert!(graph.reverse_refs.is_empty());
        assert!(graph.smart_pointers.is_empty());
        assert!(graph.allocations.is_empty());

        // Test with allocations without smart pointer info
        let allocations_without_smart = vec![AllocationInfo {
            ptr: 0x1000,
            size: 1024,
            scope_name: None,
            timestamp_alloc: 0,
            timestamp_dealloc: None,
            thread_id: std::thread::current().id(),
            thread_id_u64: {
                use std::hash::{Hash, Hasher};
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                std::thread::current().id().hash(&mut hasher);
                hasher.finish()
            },
            borrow_count: 0,
            stack_trace: None,
            is_leaked: false,
            lifetime_ms: None,
            var_name: None,
            type_name: None,
            borrow_info: None,
            clone_info: None,
            ownership_history_available: false,
            smart_pointer_info: None,
            memory_layout: None,
            generic_info: None,
            dynamic_type_info: None,
            runtime_state: None,
            stack_allocation: None,
            temporary_object: None,
            fragmentation_analysis: None,
            generic_instantiation: None,
            type_relationships: None,
            type_usage: None,
            function_call_tracking: None,
            lifecycle_tracking: None,
            access_tracking: None,
            drop_chain_analysis: None,
        }];
        let graph = ReferenceGraph::new(&allocations_without_smart);

        assert!(graph.adjacency.is_empty());
        assert!(graph.reverse_refs.is_empty());
        assert!(graph.smart_pointers.is_empty());
        assert!(graph.allocations.is_empty());

        // Test with smart pointer allocations
        let smart_info = SmartPointerInfo {
            data_ptr: 0x2000,
            pointer_type: SmartPointerType::Rc,
            is_weak_reference: false,
            clones: vec![],
            cloned_from: None,
            ref_count_history: vec![RefCountSnapshot {
                strong_count: 1,
                weak_count: 0,
                timestamp: 0,
            }],
            weak_count: None,
            is_data_owner: true,
            is_implicitly_deallocated: false,
        };

        let allocations_with_smart = vec![AllocationInfo {
            ptr: 0x1000,
            size: 1024,
            var_name: None,
            type_name: None,
            scope_name: None,
            timestamp_alloc: 0,
            timestamp_dealloc: None,
            thread_id: thread::current().id(),
            thread_id_u64: {
                use std::hash::{Hash, Hasher};
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                thread::current().id().hash(&mut hasher);
                hasher.finish()
            },
            borrow_count: 0,
            stack_trace: None,
            is_leaked: false,
            lifetime_ms: None,
            borrow_info: None,
            clone_info: None,
            ownership_history_available: false,
            smart_pointer_info: Some(smart_info.clone()),
            memory_layout: None,
            generic_info: None,
            dynamic_type_info: None,
            runtime_state: None,
            stack_allocation: None,
            temporary_object: None,
            fragmentation_analysis: None,
            generic_instantiation: None,
            type_relationships: None,
            type_usage: None,
            function_call_tracking: None,
            lifecycle_tracking: None,
            access_tracking: None,
            drop_chain_analysis: None,
        }];

        let graph = ReferenceGraph::new(&allocations_with_smart);

        assert!(!graph.adjacency.is_empty());
        assert!(!graph.reverse_refs.is_empty());
        assert!(!graph.smart_pointers.is_empty());
        assert!(!graph.allocations.is_empty());

        assert!(graph.adjacency.contains_key(&0x1000));
        assert!(graph.reverse_refs.contains_key(&0x2000));
        assert!(graph.smart_pointers.contains_key(&0x1000));
        assert!(graph.allocations.contains_key(&0x1000));
    }

    #[test]
    fn test_reference_graph_with_weak_references() {
        // Test that weak references are skipped
        let weak_smart_info = SmartPointerInfo {
            data_ptr: 0x2000,
            pointer_type: SmartPointerType::Rc,
            is_weak_reference: true, // This is a weak reference
            clones: vec![],
            cloned_from: None,
            ref_count_history: vec![RefCountSnapshot {
                strong_count: 1,
                weak_count: 1,
                timestamp: 0,
            }],
            weak_count: Some(1),
            is_data_owner: false,
            is_implicitly_deallocated: false,
        };

        let allocations_with_weak = vec![AllocationInfo {
            ptr: 0x1000,
            size: 1024,
            var_name: None,
            type_name: None,
            scope_name: None,
            timestamp_alloc: 0,
            timestamp_dealloc: None,
            thread_id: thread::current().id(),
            thread_id_u64: {
                use std::hash::{Hash, Hasher};
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                thread::current().id().hash(&mut hasher);
                hasher.finish()
            },
            borrow_count: 0,
            stack_trace: None,
            is_leaked: false,
            lifetime_ms: None,
            borrow_info: None,
            clone_info: None,
            ownership_history_available: false,
            smart_pointer_info: Some(weak_smart_info),
            memory_layout: None,
            generic_info: None,
            dynamic_type_info: None,
            runtime_state: None,
            stack_allocation: None,
            temporary_object: None,
            fragmentation_analysis: None,
            generic_instantiation: None,
            type_relationships: None,
            type_usage: None,
            function_call_tracking: None,
            lifecycle_tracking: None,
            access_tracking: None,
            drop_chain_analysis: None,
        }];

        let graph = ReferenceGraph::new(&allocations_with_weak);

        // Weak references should be skipped, so graph should be empty
        assert!(graph.adjacency.is_empty());
        assert!(graph.reverse_refs.is_empty());
        assert!(graph.smart_pointers.is_empty());
        assert!(graph.allocations.is_empty());
    }

    #[test]
    fn test_detect_circular_references_empty() {
        let empty_allocations = vec![];
        let analysis = detect_circular_references(&empty_allocations);

        assert_eq!(analysis.circular_references.len(), 0);
        assert_eq!(analysis.total_smart_pointers, 0);
        assert_eq!(analysis.pointers_in_cycles, 0);
        assert_eq!(analysis.total_leaked_memory, 0);

        // Check statistics
        assert_eq!(analysis.statistics.average_cycle_length, 0.0);
        assert_eq!(analysis.statistics.largest_cycle_size, 0);
    }

    #[test]
    fn test_circular_reference_analysis_structure() {
        let analysis = CircularReferenceAnalysis {
            circular_references: vec![],
            total_smart_pointers: 10,
            pointers_in_cycles: 5,
            total_leaked_memory: 10240,
            statistics: CircularReferenceStatistics {
                by_severity: HashMap::new(),
                by_type: HashMap::new(),
                by_pointer_type: HashMap::new(),
                average_cycle_length: 0.0,
                largest_cycle_size: 0,
            },
        };

        assert_eq!(analysis.total_smart_pointers, 10);
        assert_eq!(analysis.pointers_in_cycles, 5);
        assert_eq!(analysis.total_leaked_memory, 10240);
    }

    #[test]
    fn test_circular_reference_severity_determination() {
        // Test low severity - memory size below all thresholds
        let memory_size = 1024; // 1KB
        let low_severity = if memory_size > 1024 * 1024 {
            // 1MB
            CircularReferenceSeverity::Critical
        } else if memory_size > 64 * 1024 {
            // 64KB
            CircularReferenceSeverity::High
        } else if memory_size > 4 * 1024 {
            // 4KB
            CircularReferenceSeverity::Medium
        } else {
            CircularReferenceSeverity::Low
        };
        assert_eq!(low_severity, CircularReferenceSeverity::Low);

        // Test medium severity - memory size between 4KB and 64KB
        let memory_size = 5000; // ~5KB
        let medium_severity = if memory_size > 1024 * 1024 {
            // 1MB
            CircularReferenceSeverity::Critical
        } else if memory_size > 64 * 1024 {
            // 64KB
            CircularReferenceSeverity::High
        } else if memory_size > 4 * 1024 {
            // 4KB
            CircularReferenceSeverity::Medium
        } else {
            CircularReferenceSeverity::Low
        };
        assert_eq!(medium_severity, CircularReferenceSeverity::Medium);

        // Test high severity - memory size between 64KB and 1MB
        let memory_size = 70000; // ~68KB
        let high_severity = if memory_size > 1024 * 1024 {
            // 1MB
            CircularReferenceSeverity::Critical
        } else if memory_size > 64 * 1024 {
            // 64KB
            CircularReferenceSeverity::High
        } else if memory_size > 4 * 1024 {
            // 4KB
            CircularReferenceSeverity::Medium
        } else {
            CircularReferenceSeverity::Low
        };
        assert_eq!(high_severity, CircularReferenceSeverity::High);

        // Test critical severity - memory size above 1MB
        let memory_size = 2000000; // ~2MB
        let critical_severity = if memory_size > 1024 * 1024 {
            // 1MB
            CircularReferenceSeverity::Critical
        } else if memory_size > 64 * 1024 {
            // 64KB
            CircularReferenceSeverity::High
        } else if memory_size > 4 * 1024 {
            // 4KB
            CircularReferenceSeverity::Medium
        } else {
            CircularReferenceSeverity::Low
        };
        assert_eq!(critical_severity, CircularReferenceSeverity::Critical);
    }

    #[test]
    fn test_circular_reference_type_determination() {
        // Test self reference - cycle length 1
        let cycle_length = 1;
        let self_ref_type = if cycle_length == 1 {
            CircularReferenceType::SelfReference
        } else if cycle_length == 2 {
            CircularReferenceType::Simple
        } else {
            CircularReferenceType::Complex
        };
        assert_eq!(self_ref_type, CircularReferenceType::SelfReference);

        // Test simple cycle - cycle length 2
        let cycle_length = 2;
        let simple_type = if cycle_length == 1 {
            CircularReferenceType::SelfReference
        } else if cycle_length == 2 {
            CircularReferenceType::Simple
        } else {
            CircularReferenceType::Complex
        };
        assert_eq!(simple_type, CircularReferenceType::Simple);

        // Test complex cycle - cycle length > 2
        let cycle_length = 5;
        let complex_type = if cycle_length == 1 {
            CircularReferenceType::SelfReference
        } else if cycle_length == 2 {
            CircularReferenceType::Simple
        } else {
            CircularReferenceType::Complex
        };
        assert_eq!(complex_type, CircularReferenceType::Complex);
    }
}