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
use std::collections::HashMap;
use std::path::{Component, PathBuf};

use super::{FrameCategory, FrameId, StackId};
use serde::Serialize;

use crate::sourcemap::SourceMapResolver;

/// Normalize path components (resolve .. and . without requiring file to exist)
fn normalize_path_components(path: &PathBuf) -> String {
    let mut components: Vec<Component> = Vec::new();

    for component in path.components() {
        match component {
            Component::ParentDir => {
                // Go up one level if possible
                if let Some(Component::Normal(_)) = components.last() {
                    components.pop();
                } else {
                    components.push(component);
                }
            }
            Component::CurDir => {
                // Skip current dir references
            }
            _ => {
                components.push(component);
            }
        }
    }

    components
        .iter()
        .collect::<PathBuf>()
        .to_string_lossy()
        .to_string()
}

/// A single sample from the profile
///
/// Represents a point in time where the profiler captured the call stack.
/// For CPU profiles, weight is the time delta since the last sample.
/// For heap profiles, weight is the allocation size in bytes.
#[derive(Debug, Clone, Serialize)]
pub struct Sample {
    /// Timestamp in microseconds (from profile start)
    pub timestamp_us: u64,

    /// The call stack at this sample
    pub stack_id: StackId,

    /// Weight of this sample:
    /// - CPU profile: time delta in microseconds
    /// - Heap profile: allocation size in bytes
    pub weight: u64,
}

impl Sample {
    /// Create a new sample
    pub fn new(timestamp_us: u64, stack_id: StackId, weight: u64) -> Self {
        Self {
            timestamp_us,
            stack_id,
            weight,
        }
    }
}

/// The normalized intermediate representation of a profile
///
/// This is the common format that all analyses and outputs work with,
/// regardless of whether the source was a CPU or heap profile.
#[derive(Debug, Clone)]
pub struct ProfileIR {
    /// All unique frames in the profile
    pub frames: Vec<super::Frame>,

    /// All unique stacks in the profile
    pub stacks: Vec<super::Stack>,

    /// All samples in chronological order
    pub samples: Vec<Sample>,

    /// Profile type indicator
    pub profile_type: ProfileType,

    /// Total duration in microseconds (for CPU profiles)
    pub duration_us: Option<u64>,

    /// Source file name
    pub source_file: Option<String>,

    /// Number of frames resolved via sourcemaps
    pub sourcemaps_resolved: usize,

    /// Number of profiles merged (1 = single profile, >1 = merged)
    pub profiles_merged: usize,
}

/// Type of profile
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProfileType {
    Cpu,
    Heap,
}

impl ProfileIR {
    /// Create a new CPU profile IR
    pub fn new_cpu(
        frames: Vec<super::Frame>,
        stacks: Vec<super::Stack>,
        samples: Vec<Sample>,
        duration_us: u64,
        source_file: Option<String>,
    ) -> Self {
        Self {
            frames,
            stacks,
            samples,
            profile_type: ProfileType::Cpu,
            duration_us: Some(duration_us),
            source_file,
            sourcemaps_resolved: 0,
            profiles_merged: 1,
        }
    }

    /// Create a new heap profile IR
    pub fn new_heap(
        frames: Vec<super::Frame>,
        stacks: Vec<super::Stack>,
        samples: Vec<Sample>,
        source_file: Option<String>,
    ) -> Self {
        Self {
            frames,
            stacks,
            samples,
            profile_type: ProfileType::Heap,
            duration_us: None,
            source_file,
            sourcemaps_resolved: 0,
            profiles_merged: 1,
        }
    }

    /// Get the total weight of all samples
    pub fn total_weight(&self) -> u64 {
        self.samples.iter().map(|s| s.weight).sum()
    }

    /// Get the number of samples
    pub fn sample_count(&self) -> usize {
        self.samples.len()
    }

    /// Get frame by ID
    pub fn get_frame(&self, id: super::FrameId) -> Option<&super::Frame> {
        self.frames.iter().find(|f| f.id == id)
    }

    /// Get stack by ID
    pub fn get_stack(&self, id: StackId) -> Option<&super::Stack> {
        self.stacks.iter().find(|s| s.id == id)
    }

    /// Resolve frame locations using sourcemaps.
    ///
    /// Returns the number of frames successfully resolved.
    pub fn resolve_sourcemaps(&mut self, sourcemap_dirs: Vec<PathBuf>) -> usize {
        if sourcemap_dirs.is_empty() {
            return 0;
        }

        let mut resolver = SourceMapResolver::new(sourcemap_dirs.clone());
        let mut resolved_count = 0;

        // Use first sourcemap dir as base for resolving relative paths
        // (sourcemap paths are relative to where the .map file is located)
        let base_dir = sourcemap_dirs.first().cloned();

        // Track resolved locations to detect problematic source maps
        let mut location_counts: std::collections::HashMap<String, usize> =
            std::collections::HashMap::new();

        for frame in &mut self.frames {
            // Skip frames without file/line info
            let (Some(file), Some(line), Some(col)) = (&frame.file, frame.line, frame.col) else {
                continue;
            };

            // Try to resolve via sourcemap
            if let Some(resolved) = resolver.resolve(file, line, col) {
                // Store original minified info
                frame.minified_name = Some(frame.name.clone());
                frame.minified_location = Some(frame.location());

                // Update with resolved info
                if let Some(name) = resolved.name {
                    if !name.is_empty() {
                        frame.name = name;
                    }
                }

                // Normalize the resolved file path to absolute
                let normalized_path = Self::normalize_sourcemap_path(&resolved.file, &base_dir);
                frame.file = Some(normalized_path.clone());
                frame.line = Some(resolved.line);
                frame.col = Some(resolved.col);

                // Track this location
                let loc_key = format!("{}:{}", normalized_path, resolved.line);
                *location_counts.entry(loc_key).or_insert(0) += 1;

                // Re-classify category based on new path (e.g., node_modules -> Deps)
                frame.category = Self::classify_category_from_path(&normalized_path);

                resolved_count += 1;
            }
        }

        // Warn if many frames resolve to the same location (indicates problematic source map)
        if resolved_count > 10 {
            for (loc, count) in &location_counts {
                let pct = (*count as f64 / resolved_count as f64) * 100.0;
                if pct > 50.0 && *count > 20 {
                    eprintln!(
                        "  ⚠️  Warning: {} frames ({:.0}%) resolved to same location: {}",
                        count, pct, loc
                    );
                    eprintln!(
                        "     This usually means the source map points to a bundled file, not original sources."
                    );
                    eprintln!(
                        "     Try pointing --sourcemap-dir to a directory with maps to original .ts files."
                    );
                    break;
                }
            }
        }

        self.sourcemaps_resolved = resolved_count;
        resolved_count
    }

    /// Normalize a sourcemap path to an absolute path.
    fn normalize_sourcemap_path(path: &str, base_dir: &Option<PathBuf>) -> String {
        // Strip common URL prefixes
        let path = path
            .strip_prefix("webpack://")
            .or_else(|| path.strip_prefix("webpack:///"))
            .or_else(|| path.strip_prefix("file://"))
            .unwrap_or(path);

        // Remove leading project name in webpack paths (e.g., "project/src/file.ts" -> "src/file.ts")
        let path = if path.contains('/') && !path.starts_with('.') && !path.starts_with('/') {
            // Check if first segment looks like a project name (no extension)
            let first_segment = path.split('/').next().unwrap_or("");
            if !first_segment.contains('.') {
                path.split_once('/').map(|(_, rest)| rest).unwrap_or(path)
            } else {
                path
            }
        } else {
            path
        };

        // If we have a base directory and path is relative, resolve it
        if let Some(base) = base_dir {
            let path_buf = PathBuf::from(path);
            if path_buf.is_relative() {
                let resolved = base.join(&path_buf);
                // Canonicalize to resolve ../ and ./ components
                if let Ok(canonical) = resolved.canonicalize() {
                    return canonical.to_string_lossy().to_string();
                }
                // If canonicalize fails (file doesn't exist), just normalize manually
                return normalize_path_components(&resolved);
            }
        }

        path.to_string()
    }

    /// Re-classify frame category based on resolved path.
    fn classify_category_from_path(path: &str) -> FrameCategory {
        // node_modules -> Dependencies
        if path.contains("node_modules") {
            return FrameCategory::Deps;
        }

        // Node.js internals
        if path.starts_with("node:") || path.contains("internal/") {
            return FrameCategory::NodeInternal;
        }

        // Default to App
        FrameCategory::App
    }

    /// Merge multiple profiles into one.
    ///
    /// Frames are deduplicated by (name, file, line, col).
    /// Stacks are deduplicated by their frame sequence.
    /// Samples from all profiles are combined.
    /// Duration is summed across all profiles.
    pub fn merge(profiles: Vec<Self>) -> Option<Self> {
        if profiles.is_empty() {
            return None;
        }

        if profiles.len() == 1 {
            return profiles.into_iter().next();
        }

        let profile_type = profiles[0].profile_type;

        // Map from (name, file, line, col) -> new FrameId
        let mut frame_key_to_id: HashMap<
            (String, Option<String>, Option<u32>, Option<u32>),
            FrameId,
        > = HashMap::new();
        let mut merged_frames: Vec<super::Frame> = Vec::new();

        // Map from frame sequence -> new StackId
        let mut stack_key_to_id: HashMap<Vec<FrameId>, StackId> = HashMap::new();
        let mut merged_stacks: Vec<super::Stack> = Vec::new();

        let mut merged_samples: Vec<Sample> = Vec::new();
        let mut total_duration: u64 = 0;
        let mut total_sourcemaps_resolved: usize = 0;
        let profiles_count = profiles.len();

        for profile in profiles {
            // Build mapping from old FrameId -> new FrameId for this profile
            let mut frame_id_map: HashMap<FrameId, FrameId> = HashMap::new();

            for frame in &profile.frames {
                let key = (
                    frame.name.clone(),
                    frame.file.clone(),
                    frame.line,
                    frame.col,
                );

                let new_id = *frame_key_to_id.entry(key).or_insert_with(|| {
                    let id = FrameId(merged_frames.len() as u32);
                    let mut new_frame = frame.clone();
                    new_frame.id = id;
                    merged_frames.push(new_frame);
                    id
                });

                frame_id_map.insert(frame.id, new_id);
            }

            // Build mapping from old StackId -> new StackId for this profile
            let mut stack_id_map: HashMap<StackId, StackId> = HashMap::new();

            for stack in &profile.stacks {
                // Remap frame IDs in this stack
                let remapped_frames: Vec<FrameId> = stack
                    .frames
                    .iter()
                    .filter_map(|fid| frame_id_map.get(fid).copied())
                    .collect();

                let new_id = *stack_key_to_id
                    .entry(remapped_frames.clone())
                    .or_insert_with(|| {
                        let id = StackId(merged_stacks.len() as u32);
                        merged_stacks.push(super::Stack::new(id, remapped_frames));
                        id
                    });

                stack_id_map.insert(stack.id, new_id);
            }

            // Remap samples
            for sample in &profile.samples {
                if let Some(&new_stack_id) = stack_id_map.get(&sample.stack_id) {
                    merged_samples.push(Sample {
                        timestamp_us: sample.timestamp_us,
                        stack_id: new_stack_id,
                        weight: sample.weight,
                    });
                }
            }

            if let Some(dur) = profile.duration_us {
                total_duration += dur;
            }
            total_sourcemaps_resolved += profile.sourcemaps_resolved;
        }

        Some(Self {
            frames: merged_frames,
            stacks: merged_stacks,
            samples: merged_samples,
            profile_type,
            duration_us: if total_duration > 0 {
                Some(total_duration)
            } else {
                None
            },
            source_file: Some("(merged)".to_string()),
            sourcemaps_resolved: total_sourcemaps_resolved,
            profiles_merged: profiles_count,
        })
    }
}