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
//! Lifecycle summary generation for enhanced memory analysis
//!
//! This module provides functionality to generate high-level lifecycle summaries
//! from detailed ownership history, creating the data needed for lifetime.json export.

use super::ownership_history::{BorrowInfo, CloneInfo, OwnershipHistoryRecorder, OwnershipSummary};
use crate::capture::types::AllocationInfo;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Generator for lifecycle summaries and lifetime.json export
pub struct LifecycleSummaryGenerator {
    /// Configuration for summary generation
    config: SummaryConfig,
}

/// Configuration for lifecycle summary generation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SummaryConfig {
    /// Include detailed borrow information
    pub include_borrow_details: bool,
    /// Include clone relationship information
    pub include_clone_details: bool,
    /// Minimum lifetime threshold for inclusion (in milliseconds)
    pub min_lifetime_threshold_ms: u64,
    /// Maximum number of lifecycle events to include per allocation
    pub max_events_per_allocation: usize,
}

impl Default for SummaryConfig {
    fn default() -> Self {
        Self {
            include_borrow_details: true,
            include_clone_details: true,
            min_lifetime_threshold_ms: 0,
            max_events_per_allocation: 50,
        }
    }
}

/// Complete lifecycle data for export to lifetime.json
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LifecycleExportData {
    /// Lifecycle events for each allocation
    pub lifecycle_events: Vec<LifecycleEventSummary>,
    /// Variable groups for organization
    pub variable_groups: Vec<VariableGroup>,
    /// Count of user variables (those with meaningful names)
    pub user_variables_count: usize,
    /// Whether visualization data is ready
    pub visualization_ready: bool,
    /// Export metadata
    pub metadata: ExportMetadata,
}

/// Summary of lifecycle events for a single allocation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LifecycleEventSummary {
    /// Allocation pointer
    pub allocation_ptr: usize,
    /// Variable name (if available)
    pub var_name: Option<String>,
    /// Type name
    pub type_name: Option<String>,
    /// Size of the allocation
    pub size: usize,
    /// Total lifetime in milliseconds
    pub lifetime_ms: Option<u64>,
    /// Lifecycle events
    pub events: Vec<LifecycleEvent>,
    /// High-level summary
    pub summary: AllocationLifecycleSummary,
}

/// Individual lifecycle event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LifecycleEvent {
    /// Event ID
    pub id: u64,
    /// Event type
    pub event_type: String,
    /// Timestamp when the event occurred
    pub timestamp: u64,
    /// Size involved in the event (if applicable)
    pub size: Option<usize>,
    /// Additional event details
    pub details: Option<String>,
}

/// High-level summary of an allocation's lifecycle
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AllocationLifecycleSummary {
    /// Total lifetime in milliseconds
    pub lifetime_ms: Option<u64>,
    /// Borrowing information
    pub borrow_info: BorrowInfo,
    /// Cloning information
    pub clone_info: CloneInfo,
    /// Whether detailed ownership history is available
    pub ownership_history_available: bool,
    /// Lifecycle pattern classification
    pub lifecycle_pattern: LifecyclePattern,
    /// Memory efficiency score (0.0 to 1.0)
    pub efficiency_score: f64,
}

/// Classification of lifecycle patterns
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LifecyclePattern {
    /// Short-lived allocation (< 1ms)
    Ephemeral,
    /// Short-term allocation (1ms - 100ms)
    ShortTerm,
    /// Medium-term allocation (100ms - 10s)
    MediumTerm,
    /// Long-term allocation (> 10s)
    LongTerm,
    /// Leaked allocation (never deallocated)
    Leaked,
    /// Unknown pattern
    Unknown,
}

/// Group of related variables
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VariableGroup {
    /// Group name
    pub name: String,
    /// Variables in this group
    pub variables: Vec<String>,
    /// Total memory used by this group
    pub total_memory: usize,
    /// Average lifetime of variables in this group
    pub average_lifetime_ms: f64,
}

/// Export metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportMetadata {
    /// Export timestamp
    pub export_timestamp: u64,
    /// Total allocations analyzed
    pub total_allocations: usize,
    /// Total events processed
    pub total_events: usize,
    /// Analysis duration in milliseconds
    pub analysis_duration_ms: u64,
}

impl LifecycleSummaryGenerator {
    /// Create a new lifecycle summary generator
    pub fn new() -> Self {
        Self::with_config(SummaryConfig::default())
    }

    /// Create a new lifecycle summary generator with custom configuration
    pub fn with_config(config: SummaryConfig) -> Self {
        Self { config }
    }

    /// Generate complete lifecycle export data
    pub fn generate_lifecycle_export(
        &self,
        ownership_history: &OwnershipHistoryRecorder,
        allocations: &[AllocationInfo],
    ) -> LifecycleExportData {
        let start_time = std::time::Instant::now();

        // Generate lifecycle event summaries
        let lifecycle_events = self.generate_lifecycle_events(ownership_history, allocations);

        // Generate variable groups
        let variable_groups = self.generate_variable_groups(&lifecycle_events);

        // Count user variables (those with meaningful names)
        let user_variables_count = lifecycle_events
            .iter()
            .filter(|event| {
                event
                    .var_name
                    .as_ref()
                    .map(|name| self.is_user_variable(name))
                    .unwrap_or(false)
            })
            .count();

        let analysis_duration = start_time.elapsed().as_millis() as u64;

        LifecycleExportData {
            lifecycle_events,
            variable_groups,
            user_variables_count,
            visualization_ready: true,
            metadata: ExportMetadata {
                export_timestamp: self.get_current_timestamp(),
                total_allocations: allocations.len(),
                total_events: ownership_history.get_statistics().total_events,
                analysis_duration_ms: analysis_duration,
            },
        }
    }

    /// Generate lifecycle event summaries for all allocations
    fn generate_lifecycle_events(
        &self,
        ownership_history: &OwnershipHistoryRecorder,
        allocations: &[AllocationInfo],
    ) -> Vec<LifecycleEventSummary> {
        let mut summaries = Vec::new();

        for allocation in allocations {
            // Skip allocations below the minimum lifetime threshold
            if let Some(lifetime_ms) = allocation.lifetime_ms {
                if lifetime_ms < self.config.min_lifetime_threshold_ms {
                    continue;
                }
            }

            let summary = self.generate_single_lifecycle_summary(ownership_history, allocation);
            summaries.push(summary);
        }

        summaries
    }

    /// Generate lifecycle summary for a single allocation
    fn generate_single_lifecycle_summary(
        &self,
        ownership_history: &OwnershipHistoryRecorder,
        allocation: &AllocationInfo,
    ) -> LifecycleEventSummary {
        let ptr = allocation.ptr;

        // Get ownership summary if available
        let ownership_summary = ownership_history.get_summary(ptr);

        // Generate lifecycle events
        let events = if let Some(ownership_events) = ownership_history.get_events(ptr) {
            ownership_events
                .iter()
                .take(self.config.max_events_per_allocation)
                .map(|event| LifecycleEvent {
                    id: event.event_id,
                    event_type: self.format_event_type(&event.event_type),
                    timestamp: event.timestamp,
                    size: Some(allocation.size),
                    details: event.details.context.clone(),
                })
                .collect()
        } else {
            // Create basic events from allocation info
            let mut basic_events = vec![LifecycleEvent {
                id: 1,
                event_type: "Allocation".to_string(),
                timestamp: allocation.timestamp_alloc,
                size: Some(allocation.size),
                details: Some("Memory allocated".to_string()),
            }];

            if let Some(dealloc_time) = allocation.timestamp_dealloc {
                basic_events.push(LifecycleEvent {
                    id: 2,
                    event_type: "Deallocation".to_string(),
                    timestamp: dealloc_time,
                    size: Some(allocation.size),
                    details: Some("Memory deallocated".to_string()),
                });
            }

            basic_events
        };

        // Create allocation lifecycle summary
        let summary = if let Some(ownership_summary) = ownership_summary {
            AllocationLifecycleSummary {
                lifetime_ms: allocation.lifetime_ms,
                borrow_info: ownership_summary.borrow_info.clone(),
                clone_info: ownership_summary.clone_info.clone(),
                ownership_history_available: true,
                lifecycle_pattern: self.classify_lifecycle_pattern(allocation.lifetime_ms),
                efficiency_score: self.calculate_efficiency_score(allocation, ownership_summary),
            }
        } else {
            AllocationLifecycleSummary {
                lifetime_ms: allocation.lifetime_ms,
                borrow_info: BorrowInfo {
                    immutable_borrows: 0,
                    mutable_borrows: 0,
                    max_concurrent_borrows: 0,
                    last_borrow_timestamp: None,
                    active_borrows: Vec::new(),
                },
                clone_info: CloneInfo {
                    clone_count: 0,
                    is_clone: false,
                    original_ptr: None,
                    cloned_ptrs: Vec::new(),
                },
                ownership_history_available: false,
                lifecycle_pattern: self.classify_lifecycle_pattern(allocation.lifetime_ms),
                efficiency_score: 0.5, // Default score
            }
        };

        LifecycleEventSummary {
            allocation_ptr: ptr,
            var_name: allocation.var_name.clone(),
            type_name: allocation.type_name.clone(),
            size: allocation.size,
            lifetime_ms: allocation.lifetime_ms,
            events,
            summary,
        }
    }

    /// Format ownership event type for display
    fn format_event_type(
        &self,
        event_type: &super::ownership_history::OwnershipEventType,
    ) -> String {
        match event_type {
            super::ownership_history::OwnershipEventType::Allocated => "Allocation".to_string(),
            super::ownership_history::OwnershipEventType::Cloned { .. } => "Clone".to_string(),
            super::ownership_history::OwnershipEventType::Dropped => "Deallocation".to_string(),
            super::ownership_history::OwnershipEventType::OwnershipTransferred { .. } => {
                "OwnershipTransfer".to_string()
            }
            super::ownership_history::OwnershipEventType::Borrowed { .. } => "Borrow".to_string(),
            super::ownership_history::OwnershipEventType::MutablyBorrowed { .. } => {
                "MutableBorrow".to_string()
            }
            super::ownership_history::OwnershipEventType::BorrowReleased { .. } => {
                "BorrowRelease".to_string()
            }
            super::ownership_history::OwnershipEventType::RefCountChanged { .. } => {
                "RefCountChange".to_string()
            }
        }
    }

    /// Classify the lifecycle pattern based on lifetime
    fn classify_lifecycle_pattern(&self, lifetime_ms: Option<u64>) -> LifecyclePattern {
        match lifetime_ms {
            None => LifecyclePattern::Leaked,
            Some(0) => LifecyclePattern::Ephemeral,
            Some(ms) if ms < 1 => LifecyclePattern::Ephemeral,
            Some(ms) if ms < 100 => LifecyclePattern::ShortTerm,
            Some(ms) if ms < 10_000 => LifecyclePattern::MediumTerm,
            Some(_) => LifecyclePattern::LongTerm,
        }
    }

    /// Calculate efficiency score for an allocation
    fn calculate_efficiency_score(
        &self,
        allocation: &AllocationInfo,
        ownership_summary: &OwnershipSummary,
    ) -> f64 {
        let mut score: f64 = 0.5; // Base score

        // Bonus for having a meaningful variable name
        if allocation
            .var_name
            .as_ref()
            .map(|name| self.is_user_variable(name))
            .unwrap_or(false)
        {
            score += 0.1;
        }

        // Bonus for appropriate lifetime (not too short, not leaked)
        match self.classify_lifecycle_pattern(allocation.lifetime_ms) {
            LifecyclePattern::ShortTerm | LifecyclePattern::MediumTerm => score += 0.2,
            LifecyclePattern::Ephemeral => score -= 0.1,
            LifecyclePattern::Leaked => score -= 0.3,
            _ => {}
        }

        // Penalty for excessive borrowing
        if ownership_summary.borrow_info.max_concurrent_borrows > 5 {
            score -= 0.1;
        }

        // Bonus for being part of a clone chain (indicates reuse)
        if ownership_summary.clone_info.clone_count > 0 || ownership_summary.clone_info.is_clone {
            score += 0.1;
        }

        // Clamp score between 0.0 and 1.0
        score.clamp(0.0, 1.0)
    }

    /// Check if a variable name indicates a user-defined variable
    fn is_user_variable(&self, name: &str) -> bool {
        // Filter out system-generated names
        !name.starts_with("primitive_")
            && !name.starts_with("struct_")
            && !name.starts_with("collection_")
            && !name.starts_with("buffer_")
            && !name.starts_with("system_")
            && !name.starts_with("fast_tracked")
            && name != "unknown"
    }

    /// Generate variable groups for organization
    fn generate_variable_groups(
        &self,
        lifecycle_events: &[LifecycleEventSummary],
    ) -> Vec<VariableGroup> {
        let mut groups: HashMap<String, Vec<&LifecycleEventSummary>> = HashMap::new();

        // Group by type name
        for event in lifecycle_events {
            if let Some(ref type_name) = event.type_name {
                let group_name = self.extract_base_type_name(type_name);
                groups.entry(group_name).or_default().push(event);
            }
        }

        // Convert to VariableGroup structs
        groups
            .into_iter()
            .map(|(name, events)| {
                let variables: Vec<String> =
                    events.iter().filter_map(|e| e.var_name.clone()).collect();

                let total_memory: usize = events.iter().map(|e| e.size).sum();

                let average_lifetime_ms = if !events.is_empty() {
                    let total_lifetime: u64 = events.iter().filter_map(|e| e.lifetime_ms).sum();
                    let count = events.iter().filter(|e| e.lifetime_ms.is_some()).count();
                    if count > 0 {
                        total_lifetime as f64 / count as f64
                    } else {
                        0.0
                    }
                } else {
                    0.0
                };

                VariableGroup {
                    name,
                    variables,
                    total_memory,
                    average_lifetime_ms,
                }
            })
            .collect()
    }

    /// Extract base type name for grouping
    fn extract_base_type_name(&self, type_name: &str) -> String {
        // Extract the base type from complex type names
        if let Some(pos) = type_name.find('<') {
            type_name[..pos].to_string()
        } else if let Some(pos) = type_name.rfind("::") {
            type_name[pos + 2..].to_string()
        } else {
            type_name.to_string()
        }
    }

    /// Get current timestamp in nanoseconds
    fn get_current_timestamp(&self) -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos() as u64
    }

    /// Export lifecycle data to JSON string
    pub fn export_to_json(&self, export_data: &LifecycleExportData) -> serde_json::Result<String> {
        serde_json::to_string_pretty(export_data)
    }
}

impl Default for LifecycleSummaryGenerator {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_lifecycle_summary_generator_creation() {
        let generator = LifecycleSummaryGenerator::new();
        assert!(generator.config.include_borrow_details);
        assert!(generator.config.include_clone_details);
    }

    #[test]
    fn test_lifecycle_pattern_classification() {
        let generator = LifecycleSummaryGenerator::default();

        assert!(matches!(
            generator.classify_lifecycle_pattern(None),
            LifecyclePattern::Leaked
        ));
        assert!(matches!(
            generator.classify_lifecycle_pattern(Some(0)),
            LifecyclePattern::Ephemeral
        ));
        assert!(matches!(
            generator.classify_lifecycle_pattern(Some(50)),
            LifecyclePattern::ShortTerm
        ));
        assert!(matches!(
            generator.classify_lifecycle_pattern(Some(5000)),
            LifecyclePattern::MediumTerm
        ));
        assert!(matches!(
            generator.classify_lifecycle_pattern(Some(15000)),
            LifecyclePattern::LongTerm
        ));
    }

    #[test]
    fn test_json_export_basic() {
        let generator = LifecycleSummaryGenerator::default();
        let export_data = LifecycleExportData {
            lifecycle_events: vec![],
            variable_groups: vec![],
            user_variables_count: 0,
            visualization_ready: true,
            metadata: ExportMetadata {
                export_timestamp: 0,
                total_allocations: 0,
                total_events: 0,
                analysis_duration_ms: 0,
            },
        };

        let json = generator.export_to_json(&export_data).unwrap();
        assert!(json.contains("lifecycle_events"));
        assert!(json.contains("variable_groups"));
        assert!(json.contains("metadata"));
    }

    #[test]
    fn test_json_export_with_events() {
        let generator = LifecycleSummaryGenerator::default();

        let event_summary = LifecycleEventSummary {
            allocation_ptr: 0x1000,
            var_name: Some("test_var".to_string()),
            type_name: Some("String".to_string()),
            size: 1024,
            lifetime_ms: Some(1000),
            events: vec![],
            summary: AllocationLifecycleSummary {
                lifetime_ms: Some(1000),
                borrow_info: BorrowInfo {
                    immutable_borrows: 0,
                    mutable_borrows: 0,
                    max_concurrent_borrows: 0,
                    last_borrow_timestamp: None,
                    active_borrows: vec![],
                },
                clone_info: CloneInfo {
                    clone_count: 0,
                    is_clone: false,
                    original_ptr: None,
                    cloned_ptrs: vec![],
                },
                ownership_history_available: false,
                lifecycle_pattern: LifecyclePattern::ShortTerm,
                efficiency_score: 0.8,
            },
        };

        let export_data = LifecycleExportData {
            lifecycle_events: vec![event_summary],
            variable_groups: vec![],
            user_variables_count: 1,
            visualization_ready: true,
            metadata: ExportMetadata {
                export_timestamp: 1000,
                total_allocations: 1,
                total_events: 1,
                analysis_duration_ms: 100,
            },
        };

        let json = generator.export_to_json(&export_data).unwrap();
        assert!(json.contains("test_var"));
        assert!(json.contains("String"));
        assert!(json.contains("ShortTerm"));
    }

    #[test]
    fn test_summary_config_default() {
        let config = SummaryConfig::default();
        assert!(config.include_borrow_details);
        assert!(config.include_clone_details);
        assert_eq!(config.min_lifetime_threshold_ms, 0);
        assert_eq!(config.max_events_per_allocation, 50);
    }

    #[test]
    fn test_lifecycle_export_metadata() {
        let metadata = ExportMetadata {
            export_timestamp: 1234567890,
            total_allocations: 100,
            total_events: 500,
            analysis_duration_ms: 1000,
        };

        assert_eq!(metadata.export_timestamp, 1234567890);
        assert_eq!(metadata.total_allocations, 100);
        assert_eq!(metadata.total_events, 500);
        assert_eq!(metadata.analysis_duration_ms, 1000);
    }

    #[test]
    fn test_lifecycle_event_serialization() {
        let event = LifecycleEvent {
            id: 1,
            event_type: "Allocation".to_string(),
            timestamp: 1000,
            size: Some(1024),
            details: Some("Memory allocated".to_string()),
        };

        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("Allocation"));
        assert!(json.contains("1024"));
    }
}