profile-inspect 0.1.3

Analyze V8 CPU and heap profiles from Node.js/Chrome DevTools
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
//! Integration tests for analysis modules

mod fixtures;

use insta::assert_snapshot;
use profile_inspect::analysis::{CallerCalleeAnalyzer, CpuAnalyzer, HeapAnalyzer, ProfileDiffer};
use profile_inspect::ir::{FrameCategory, FrameId};
use regex::Regex;

// ============================================================================
// CPU Analyzer Tests
// ============================================================================

#[test]
fn test_cpu_analyzer_basic() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CpuAnalyzer::new();
    let analysis = analyzer.analyze(&profile);

    // Verify totals
    assert_eq!(analysis.total_time, 10000);
    assert_eq!(analysis.total_samples, 13);

    // Verify we have functions
    assert!(!analysis.functions.is_empty());

    // Verify category breakdown sums to total
    let breakdown = &analysis.category_breakdown;
    let breakdown_total = breakdown.app
        + breakdown.deps
        + breakdown.node_internal
        + breakdown.v8_internal
        + breakdown.native;
    assert_eq!(breakdown_total, 10000);
}

#[test]
fn test_cpu_analyzer_default_hides_internals() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CpuAnalyzer::new(); // Default: hide internals
    let analysis = analyzer.analyze(&profile);

    // Should not include internal frames in functions list
    for func in &analysis.functions {
        assert!(
            !func.category.is_internal(),
            "Function {} should not be internal",
            func.name
        );
    }
}

#[test]
fn test_cpu_analyzer_include_internals() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CpuAnalyzer::new().include_internals(true);
    let analysis = analyzer.analyze(&profile);

    // Should include some internal frames
    let has_internal = analysis.functions.iter().any(|f| f.category.is_internal());
    assert!(
        has_internal,
        "Should include internal frames when include_internals is true"
    );
}

#[test]
fn test_cpu_analyzer_min_percent_filter() {
    let profile = fixtures::create_simple_cpu_profile();

    // With high min_percent, should filter out small functions
    let analyzer = CpuAnalyzer::new().min_percent(50.0);
    let analysis = analyzer.analyze(&profile);

    // Only functions with >= 50% self time should remain
    for func in &analysis.functions {
        let pct = func.self_percent(analysis.total_time);
        assert!(
            pct >= 50.0,
            "Function {} has {}% but min is 50%",
            func.name,
            pct
        );
    }
}

#[test]
fn test_cpu_analyzer_top_n() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CpuAnalyzer::new().include_internals(true).top_n(2);
    let analysis = analyzer.analyze(&profile);

    assert!(
        analysis.functions.len() <= 2,
        "Should have at most 2 functions"
    );
}

#[test]
fn test_cpu_analyzer_category_filter() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CpuAnalyzer::new().filter_categories(vec![FrameCategory::App]);
    let analysis = analyzer.analyze(&profile);

    // All functions should be App category
    for func in &analysis.functions {
        assert_eq!(
            func.category,
            FrameCategory::App,
            "Function {} should be App category",
            func.name
        );
    }
}

#[test]
fn test_cpu_analyzer_focus_pattern() {
    let profile = fixtures::create_simple_cpu_profile();
    let pattern = Regex::new("compute").unwrap();
    let analyzer = CpuAnalyzer::new().focus(pattern);
    let analysis = analyzer.analyze(&profile);

    // Should only have functions matching "compute"
    assert!(!analysis.functions.is_empty());
    for func in &analysis.functions {
        assert!(
            func.name.contains("compute") || func.location.contains("compute"),
            "Function {} should match 'compute'",
            func.name
        );
    }
}

#[test]
fn test_cpu_analyzer_exclude_pattern() {
    let profile = fixtures::create_simple_cpu_profile();
    let pattern = Regex::new("main").unwrap();
    let analyzer = CpuAnalyzer::new().exclude(pattern);
    let analysis = analyzer.analyze(&profile);

    // No functions should match "main"
    for func in &analysis.functions {
        assert!(
            !func.name.contains("main"),
            "Function {} should not match 'main'",
            func.name
        );
    }
}

#[test]
fn test_cpu_analyzer_gc_tracking() {
    let profile = fixtures::create_gc_heavy_profile();
    let analyzer = CpuAnalyzer::new().include_internals(true);
    let analysis = analyzer.analyze(&profile);

    // Should have significant GC time
    assert!(analysis.gc_time > 0, "Should detect GC time");

    let gc_pct = (analysis.gc_time as f64 / analysis.total_time as f64) * 100.0;
    assert!(gc_pct > 10.0, "GC should be >10%, got {:.1}%", gc_pct);

    // Should have GC analysis
    assert!(analysis.gc_analysis.is_some(), "Should have GC analysis");

    let gc = analysis.gc_analysis.as_ref().unwrap();
    assert!(gc.sample_count > 0, "Should have GC samples");
    assert!(
        !gc.allocation_hotspots.is_empty(),
        "Should identify allocation hotspots"
    );
}

#[test]
fn test_cpu_analyzer_recursive_detection() {
    let profile = fixtures::create_recursive_profile();
    let analyzer = CpuAnalyzer::new();
    let analysis = analyzer.analyze(&profile);

    // Should detect recursive functions
    assert!(
        !analysis.recursive_functions.is_empty(),
        "Should detect recursive functions"
    );

    // Check that factorial and fibonacci are detected
    let recursive_names: Vec<&str> = analysis
        .recursive_functions
        .iter()
        .map(|f| f.name.as_str())
        .collect();
    assert!(
        recursive_names.contains(&"factorial") || recursive_names.contains(&"fibonacci"),
        "Should detect factorial or fibonacci as recursive"
    );

    // Check max recursion depth
    for func in &analysis.recursive_functions {
        if func.name == "fibonacci" {
            assert!(func.max_depth >= 3, "Fibonacci should have depth >= 3");
        }
    }
}

#[test]
fn test_cpu_analyzer_phase_analysis() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CpuAnalyzer::new();
    let analysis = analyzer.analyze(&profile);

    assert!(
        analysis.phase_analysis.is_some(),
        "Should have phase analysis"
    );

    let phases = analysis.phase_analysis.as_ref().unwrap();
    assert!(
        phases.startup.sample_count > 0,
        "Startup phase should have samples"
    );
    assert!(
        phases.steady_state.sample_count > 0,
        "Steady state should have samples"
    );
    assert_eq!(
        phases.startup.sample_count + phases.steady_state.sample_count,
        analysis.total_samples,
        "Phases should account for all samples"
    );
}

#[test]
fn test_cpu_analyzer_hot_paths() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CpuAnalyzer::new();
    let analysis = analyzer.analyze(&profile);

    assert!(!analysis.hot_paths.is_empty(), "Should have hot paths");

    // Hot paths should be sorted by CPU time descending
    for window in analysis.hot_paths.windows(2) {
        assert!(
            window[0].time >= window[1].time,
            "Hot paths should be sorted by CPU time"
        );
    }
}

#[test]
fn test_cpu_analyzer_package_stats() {
    let profile = fixtures::create_multi_package_profile();
    let analyzer = CpuAnalyzer::new();
    let analysis = analyzer.analyze(&profile);

    assert!(
        !analysis.package_stats.is_empty(),
        "Should have package stats"
    );

    // Should identify lodash as a package
    let packages: Vec<&str> = analysis
        .package_stats
        .iter()
        .map(|p| p.package.as_str())
        .collect();
    assert!(
        packages.iter().any(|p| p.contains("lodash")),
        "Should identify lodash package"
    );
}

// ============================================================================
// CPU Analysis Snapshot Tests
// ============================================================================

#[test]
fn test_cpu_analysis_snapshot() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CpuAnalyzer::new();
    let analysis = analyzer.analyze(&profile);

    // Create a summary for snapshot testing
    let summary = format!(
        "Total time: {}us\n\
         Total samples: {}\n\
         Functions count: {}\n\
         Category breakdown:\n\
           App: {}us ({:.1}%)\n\
           Deps: {}us ({:.1}%)\n\
           NodeInternal: {}us ({:.1}%)\n\
           V8Internal: {}us ({:.1}%)\n\
           Native: {}us ({:.1}%)\n\
         GC time: {}us ({:.1}%)\n\
         Hot paths: {}\n\
         Recursive functions: {}",
        analysis.total_time,
        analysis.total_samples,
        analysis.functions.len(),
        analysis.category_breakdown.app,
        analysis.category_breakdown.percent(FrameCategory::App),
        analysis.category_breakdown.deps,
        analysis.category_breakdown.percent(FrameCategory::Deps),
        analysis.category_breakdown.node_internal,
        analysis
            .category_breakdown
            .percent(FrameCategory::NodeInternal),
        analysis.category_breakdown.v8_internal,
        analysis
            .category_breakdown
            .percent(FrameCategory::V8Internal),
        analysis.category_breakdown.native,
        analysis.category_breakdown.percent(FrameCategory::Native),
        analysis.gc_time,
        if analysis.total_time > 0 {
            (analysis.gc_time as f64 / analysis.total_time as f64) * 100.0
        } else {
            0.0
        },
        analysis.hot_paths.len(),
        analysis.recursive_functions.len(),
    );

    assert_snapshot!(summary);
}

// ============================================================================
// Heap Analyzer Tests
// ============================================================================

#[test]
fn test_heap_analyzer_basic() {
    let profile = fixtures::create_simple_heap_profile();
    let analyzer = HeapAnalyzer::new();
    let analysis = analyzer.analyze(&profile);

    // Verify totals (1024 + 2048 + 4096 + 8192 + 1024 + 2048 = 18432 bytes)
    assert_eq!(analysis.total_size, 18432);
    assert_eq!(analysis.total_allocations, 6);

    // Should have allocation stats
    assert!(!analysis.functions.is_empty());
}

#[test]
fn test_heap_analyzer_category_breakdown() {
    let profile = fixtures::create_simple_heap_profile();
    let analyzer = HeapAnalyzer::new().include_internals(true);
    let analysis = analyzer.analyze(&profile);

    let breakdown = &analysis.category_breakdown;

    // Should have allocations in multiple categories
    assert!(
        breakdown.app > 0 || breakdown.deps > 0,
        "Should have app or deps allocations"
    );
}

#[test]
fn test_heap_analyzer_default_hides_internals() {
    let profile = fixtures::create_simple_heap_profile();
    let analyzer = HeapAnalyzer::new();
    let analysis = analyzer.analyze(&profile);

    for func in &analysis.functions {
        assert!(
            !func.category.is_internal(),
            "Function {} should not be internal",
            func.name
        );
    }
}

#[test]
fn test_heap_analysis_snapshot() {
    let profile = fixtures::create_simple_heap_profile();
    let analyzer = HeapAnalyzer::new().include_internals(true);
    let analysis = analyzer.analyze(&profile);

    let summary = format!(
        "Total size: {} bytes\n\
         Total allocations: {}\n\
         Functions count: {}\n\
         Category breakdown:\n\
           App: {} bytes\n\
           Deps: {} bytes\n\
           NodeInternal: {} bytes\n\
           V8Internal: {} bytes\n\
           Native: {} bytes",
        analysis.total_size,
        analysis.total_allocations,
        analysis.functions.len(),
        analysis.category_breakdown.app,
        analysis.category_breakdown.deps,
        analysis.category_breakdown.node_internal,
        analysis.category_breakdown.v8_internal,
        analysis.category_breakdown.native,
    );

    assert_snapshot!(summary);
}

// ============================================================================
// Caller/Callee Analyzer Tests
// ============================================================================

#[test]
fn test_caller_callee_basic() {
    let profile = fixtures::create_simple_cpu_profile();
    let analyzer = CallerCalleeAnalyzer::new();

    // Analyze "compute" function (FrameId(1))
    let analysis = analyzer.analyze(&profile, FrameId(1));

    assert!(analysis.is_some(), "Should find analysis for compute");
    let analysis = analysis.unwrap();

    assert_eq!(analysis.target_name, "compute");

    // "compute" is called by "main"
    assert!(!analysis.callers.is_empty(), "Should have callers");
    assert!(
        analysis.callers.iter().any(|c| c.name == "main"),
        "main should be a caller"
    );
}

#[test]
fn test_caller_callee_find_by_name() {
    let profile = fixtures::create_simple_cpu_profile();

    let frame = CallerCalleeAnalyzer::find_frame_by_name(&profile, "compute");
    assert!(frame.is_some(), "Should find compute frame");
    assert_eq!(frame.unwrap().name, "compute");

    let not_found = CallerCalleeAnalyzer::find_frame_by_name(&profile, "nonexistent");
    assert!(not_found.is_none(), "Should not find nonexistent frame");
}

// ============================================================================
// Profile Differ Tests
// ============================================================================

#[test]
fn test_profile_differ_basic() {
    let before = fixtures::create_diff_profile_before();
    let after = fixtures::create_diff_profile_after();

    let differ = ProfileDiffer::new();
    let diff = differ.diff(&before, &after);

    // Check totals
    assert_eq!(diff.before_total, 5000);
    assert_eq!(diff.after_total, 4000);

    // Should have improvements (slowFunction got faster)
    assert!(!diff.improvements.is_empty(), "Should have improvements");
    let has_slow_improvement = diff.improvements.iter().any(|d| d.name == "slowFunction");
    assert!(
        has_slow_improvement,
        "slowFunction should be an improvement"
    );

    // Should have regressions (fastFunction got slower)
    assert!(!diff.regressions.is_empty(), "Should have regressions");
    let has_fast_regression = diff.regressions.iter().any(|d| d.name == "fastFunction");
    assert!(has_fast_regression, "fastFunction should be a regression");

    // Should detect new functions
    let has_new = diff.new_functions.iter().any(|f| f.name == "newFunction");
    assert!(has_new, "Should detect newFunction");

    // Should detect removed functions
    let has_removed = diff
        .removed_functions
        .iter()
        .any(|f| f.name == "removedFunction");
    assert!(has_removed, "Should detect removedFunction");
}

#[test]
fn test_profile_differ_min_delta() {
    let before = fixtures::create_diff_profile_before();
    let after = fixtures::create_diff_profile_after();

    // With high min_delta, should filter out small changes
    let differ = ProfileDiffer::new().min_delta_percent(100.0);
    let diff = differ.diff(&before, &after);

    // Only changes >= 100% should be reported
    for regression in &diff.regressions {
        assert!(
            regression.delta_percent.abs() >= 100.0,
            "Regression {} has {}% but min is 100%",
            regression.name,
            regression.delta_percent
        );
    }
}

#[test]
fn test_profile_differ_snapshot() {
    let before = fixtures::create_diff_profile_before();
    let after = fixtures::create_diff_profile_after();

    let differ = ProfileDiffer::new().min_delta_percent(1.0);
    let diff = differ.diff(&before, &after);

    let summary = format!(
        "Before total: {}us\n\
         After total: {}us\n\
         Overall delta: {:.1}%\n\
         Regressions: {}\n\
         Improvements: {}\n\
         New functions: {}\n\
         Removed functions: {}",
        diff.before_total,
        diff.after_total,
        diff.overall_delta_percent,
        diff.regressions
            .iter()
            .map(|r| format!("{} ({:+.1}%)", r.name, r.delta_percent))
            .collect::<Vec<_>>()
            .join(", "),
        diff.improvements
            .iter()
            .map(|i| format!("{} ({:+.1}%)", i.name, i.delta_percent))
            .collect::<Vec<_>>()
            .join(", "),
        diff.new_functions
            .iter()
            .map(|f| f.name.as_str())
            .collect::<Vec<_>>()
            .join(", "),
        diff.removed_functions
            .iter()
            .map(|f| f.name.as_str())
            .collect::<Vec<_>>()
            .join(", "),
    );

    assert_snapshot!(summary);
}