diff --git a/crates/ide-profiler/src/lib.rs b/crates/ide-profiler/src/lib.rs index 4a6513255f..06578515bc 100644 --- a/crates/ide-profiler/src/lib.rs +++ b/crates/ide-profiler/src/lib.rs @@ -10,11 +10,14 @@ //! | Python | `py-spy record --format raw` | collapsed stacks | //! | JVM applications | async-profiler agent (`JAVA_TOOL_OPTIONS`) | collapsed stacks | //! | native / `cargo run` (Linux) | `perf record -g`, then `perf script` | perf script text | +//! +//! Saved snapshots open too: V8 `.cpuprofile` files and cProfile / profile `pstats` files. mod formats; mod jvm; mod live; mod plan; +mod pstats; mod tree; pub use live::gc_before_stop; @@ -83,6 +86,27 @@ pub struct MethodStat { pub frame: u32, pub self_weight: f64, pub total: f64, + /// Calls, when the profiler counts them (cProfile); sampling profilers don't. + pub calls: Option, + /// Calls that were not recursive (`pstats`' primitive calls). + pub primitive_calls: Option, +} + +/// What one function spent when called from another, as a call-graph profiler (cProfile) +/// records it. Sampling profilers leave [`Profile::calls`] empty; their callers and callees +/// come from the call tree. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CallEdge { + /// Index into [`Profile::frames`]. + pub caller: u32, + pub callee: u32, + /// Weight spent in the callee itself on these calls. + pub self_weight: f64, + /// Weight of these calls, including what the callee called. + pub total: f64, + pub calls: f64, + pub primitive_calls: f64, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] @@ -99,6 +123,9 @@ pub struct Profile { pub nodes: Vec, /// Sorted by self weight, heaviest first. pub methods: Vec, + /// Exact caller → callee totals of a call-graph profile; its call tree is then rebuilt + /// from them, so below the first level it is an estimate. Empty for sampled profiles. + pub calls: Vec, } /// Where a prepared run's profile will be, and how to read it. @@ -109,8 +136,10 @@ pub enum ProfileSpec { /// ran no code of `root` (the package manager of an npm script) are left /// out when another one did. CpuProfiles { dir: IpcPath, root: IpcPath }, - /// One `.cpuprofile` the user opened (saved by `node --cpu-prof`, Chrome DevTools, CI). - CpuProfileFile { path: IpcPath }, + /// A snapshot file the user opened: a V8 `.cpuprofile` (`node --cpu-prof`, Chrome + /// DevTools, CI) or a `pstats` file (cProfile, profile, yappi), told apart by content. + /// Relative source files of a `pstats` file resolve against `root`, then its directory. + SnapshotFile { path: IpcPath, root: Option }, /// Collapsed-stack files with extension `ext` in `dir`; relative frame files resolve /// against `base`. `jvm_root`: map JVM class frames to sources below it. For the /// allocation modes the last frame of a JVM stack is the allocated type. @@ -174,12 +203,22 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult { } Ok(b.finish("node --cpu-prof", "ms", ProfileMode::Cpu)) } - ProfileSpec::CpuProfileFile { path } => { + ProfileSpec::SnapshotFile { path, root } => { let path: &Path = path.as_ref(); let name = path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()); - let text = - std::fs::read_to_string(path).map_err(|e| IdeError::invalid(format!("Cannot read {name}: {e}")))?; + let bytes = std::fs::read(path).map_err(|e| IdeError::invalid(format!("Cannot read {name}: {e}")))?; + let ext = path.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default(); + if pstats::looks_like_pstats(&bytes) || ext == "pstats" || ext == "prof" { + let bases: Vec<&Path> = root.iter().map(|r| r.as_ref()).chain(path.parent()).collect(); + let profile = pstats::read(&bytes, &bases, "cProfile") + .map_err(|e| IdeError::invalid(format!("{name} is not a cProfile snapshot ({e}).")))?; + if profile.methods.is_empty() { + return Err(IdeError::invalid(format!("{name} has no calls."))); + } + return Ok(profile); + } + let text = String::from_utf8_lossy(&bytes); formats::add_cpuprofile(&mut b, &text) .map_err(|e| IdeError::invalid(format!("{name} is not a V8 CPU profile ({e}).")))?; if b.is_empty() { @@ -289,7 +328,7 @@ mod tests { ); let path = dir.path().join("CPU.cpuprofile"); std::fs::write(&path, json).unwrap(); - let p = collect(&ProfileSpec::CpuProfileFile { path: path.into() }).unwrap(); + let p = collect(&ProfileSpec::SnapshotFile { path: path.into(), root: None }).unwrap(); assert_eq!((p.unit.as_str(), p.mode), ("ms", ProfileMode::Cpu)); let frame = |name: &str| p.frames.iter().find(|f| f.name == name).unwrap(); assert_eq!(frame("here").file.as_deref(), Some(src.as_path())); @@ -307,14 +346,33 @@ mod tests { ] { let path = dir.path().join(file); std::fs::write(&path, text).unwrap(); - let err = collect(&ProfileSpec::CpuProfileFile { path: path.into() }).unwrap_err(); + let err = collect(&ProfileSpec::SnapshotFile { path: path.into(), root: None }).unwrap_err(); assert_eq!(err.message.split_once(' ').unwrap().0, file); assert!(err.message.contains(says), "{}", err.message); } - let missing = collect(&ProfileSpec::CpuProfileFile { path: dir.path().join("gone.cpuprofile").into() }); + let missing = + collect(&ProfileSpec::SnapshotFile { path: dir.path().join("gone.cpuprofile").into(), root: None }); assert!(missing.unwrap_err().message.starts_with("Cannot read gone.cpuprofile")); } + #[test] + fn an_opened_pstats_file_is_told_apart_by_content() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("run.out"); + std::fs::write(&path, include_bytes!("../testdata/fib.prof")).unwrap(); + std::fs::write(dir.path().join("work.py"), "").unwrap(); + let p = collect(&ProfileSpec::SnapshotFile { path: path.into(), root: None }).unwrap(); + assert_eq!((p.profiler.as_str(), p.unit.as_str()), ("cProfile", "ms")); + assert!(!p.calls.is_empty()); + let fib = p.frames.iter().find(|f| f.name == "fib").unwrap(); + assert_eq!(fib.file.as_deref(), Some(dir.path().join("work.py").as_path()), "relative to the snapshot"); + + let bad = dir.path().join("bad.prof"); + std::fs::write(&bad, "not marshal").unwrap(); + let err = collect(&ProfileSpec::SnapshotFile { path: bad.into(), root: None }).unwrap_err(); + assert!(err.message.starts_with("bad.prof is not a cProfile snapshot"), "{}", err.message); + } + #[test] fn cpu_profile_stays_in_samples() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-profiler/src/pstats.rs b/crates/ide-profiler/src/pstats.rs new file mode 100644 index 0000000000..ce53af2582 --- /dev/null +++ b/crates/ide-profiler/src/pstats.rs @@ -0,0 +1,680 @@ +//! cProfile / profile snapshots (`pstats` files): a marshal'd dict +//! `{(file, line, name): (cc, nc, tt, ct, {caller: (nc, cc, tt, ct)})}` in seconds, +//! read without a Python interpreter. `profile` (the pure-Python module) stores a bare +//! call count per caller instead of the tuple. + +use crate::tree::{FrameKey, TreeBuilder}; +use crate::{CallEdge, MethodStat, Profile, ProfileMode}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +/// Whether `bytes` start like a marshal'd pstats dict rather than JSON (`{"nodes"…`). +pub(crate) fn looks_like_pstats(bytes: &[u8]) -> bool { + // A dict (`{`, with or without the ref flag) whose first key is a tuple, or empty (`0`). + matches!(bytes, [first, second, ..] if first & 0x7f == b'{' && matches!(second & 0x7f, b'(' | b')' | b'0')) +} + +#[derive(Clone, Debug)] +enum Value { + None, + Int(f64), + Float(f64), + // Shared: a reference (`r`) to a key or file name is a cheap clone. + Str(Rc), + Seq(Rc<[Value]>), + Dict(Vec<(Value, Value)>), +} + +impl Value { + fn num(&self) -> Option { + match self { + Value::Int(v) | Value::Float(v) => Some(*v), + _ => None, + } + } +} + +/// The subset of marshal (format 2–5) that pstats files use. +struct Reader<'a> { + data: &'a [u8], + pos: usize, + refs: Vec, +} + +const MAX_DEPTH: u32 = 32; + +impl Reader<'_> { + fn take(&mut self, n: usize) -> Result<&[u8], String> { + let end = self.pos.checked_add(n).filter(|e| *e <= self.data.len()).ok_or("truncated")?; + let s = &self.data[self.pos..end]; + self.pos = end; + Ok(s) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn i32(&mut self) -> Result { + Ok(i32::from_le_bytes(self.take(4)?.try_into().unwrap())) + } + + fn len(&mut self, short: bool) -> Result { + if short { + return Ok(self.u8()? as usize); + } + usize::try_from(self.i32()?).map_err(|_| "negative length".to_owned()) + } + + fn str(&mut self, n: usize) -> Result { + Ok(Value::Str(String::from_utf8_lossy(self.take(n)?).into())) + } + + fn read(&mut self, depth: u32) -> Result { + if depth > MAX_DEPTH { + return Err("nested too deeply".into()); + } + let code = self.u8()?; + // FLAG_REF: the object is remembered for later `r` references. Containers take + // their slot before their items, as CPython numbers them. + let slot = (code & 0x80 != 0).then(|| { + self.refs.push(Value::None); + self.refs.len() - 1 + }); + let value = match code & 0x7f { + b'N' | b'F' | b'T' => Value::None, + b'i' => Value::Int(self.i32()? as f64), + b'l' => { + let n = self.i32()?; + let mut v = 0.0; + for i in 0..n.unsigned_abs() { + let digit = u16::from_le_bytes(self.take(2)?.try_into().unwrap()); + v += f64::from(digit) * 2f64.powi(15 * i as i32); + } + Value::Int(if n < 0 { -v } else { v }) + } + b'g' => Value::Float(f64::from_le_bytes(self.take(8)?.try_into().unwrap())), + b'f' => { + let n = self.len(true)?; + let text = String::from_utf8_lossy(self.take(n)?).into_owned(); + Value::Float(text.trim().parse().map_err(|_| "bad float")?) + } + b'u' | b't' | b'a' | b'A' | b's' => { + let n = self.len(false)?; + self.str(n)? + } + b'z' | b'Z' => { + let n = self.len(true)?; + self.str(n)? + } + c @ (b'(' | b')' | b'[' | b'<' | b'>') => { + let n = self.len(c == b')')?; + let mut items = Vec::with_capacity(n.min(1024)); + for _ in 0..n { + items.push(self.read(depth + 1)?); + } + Value::Seq(items.into()) + } + b'{' => { + let mut items = Vec::new(); + loop { + if self.data.get(self.pos) == Some(&b'0') { + self.pos += 1; + break; + } + let k = self.read(depth + 1)?; + let v = self.read(depth + 1)?; + items.push((k, v)); + } + // pstats never refers back to a dict, so its slot stays empty instead of + // holding a copy of the whole table. + return Ok(Value::Dict(items)); + } + b'r' => { + let i = usize::try_from(self.i32()?).map_err(|_| "bad reference")?; + self.refs.get(i).cloned().ok_or("bad reference")? + } + other => return Err(format!("unexpected marshal type {:?}", other as char)), + }; + if let Some(s) = slot { + self.refs[s] = value.clone(); + } + Ok(value) + } +} + +/// `(file, line, name)` as cProfile records it. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct Func { + file: Rc, + line: u32, + name: Rc, +} + +#[derive(Default)] +struct Stat { + cc: f64, + nc: f64, + tt: f64, + ct: f64, +} + +struct Edge { + caller: usize, + callee: usize, + nc: f64, + cc: f64, + tt: f64, + ct: f64, +} + +fn func(key: &Value) -> Result { + match key { + Value::Seq(t) if t.len() == 3 => match (&t[0], t[1].num(), &t[2]) { + (Value::Str(file), Some(line), Value::Str(name)) => { + Ok(Func { file: file.clone(), line: line.max(0.0) as u32, name: name.clone() }) + } + _ => Err("a function key is not (file, line, name)".into()), + }, + _ => Err("a function key is not (file, line, name)".into()), + } +} + +/// Functions, their stats (same index) and caller edges. +type Graph = (Vec, Vec, Vec); + +/// Every function and caller edge of a pstats file. +fn parse(bytes: &[u8]) -> Result { + let mut r = Reader { data: bytes, pos: 0, refs: Vec::new() }; + let Value::Dict(table) = r.read(0)? else { return Err("not a dict".into()) }; + let mut funcs: Vec = Vec::new(); + let mut ids: HashMap = HashMap::new(); + let mut id = |f: Func, funcs: &mut Vec| { + *ids.entry(f.clone()).or_insert_with(|| { + funcs.push(f); + funcs.len() - 1 + }) + }; + let mut stats: Vec = Vec::new(); + let mut edges = Vec::new(); + for (key, value) in &table { + let callee = id(func(key)?, &mut funcs); + let Value::Seq(v) = value else { return Err("a function's stats are not a tuple".into()) }; + let n = |i: usize| v.get(i).and_then(Value::num).ok_or("a function's stats are not numbers"); + stats.resize_with(funcs.len(), Stat::default); + stats[callee] = Stat { cc: n(0)?, nc: n(1)?, tt: n(2)?, ct: n(3)? }; + let Some(Value::Dict(callers)) = v.get(4) else { return Err("a function has no callers table".into()) }; + for (caller, e) in callers { + let caller = id(func(caller)?, &mut funcs); + let edge = match e { + Value::Seq(t) => { + let n = |i: usize| t.get(i).and_then(Value::num).ok_or("a caller's stats are not numbers"); + Edge { caller, callee, nc: n(0)?, cc: n(1)?, tt: n(2)?, ct: n(3)? } + } + // `profile` keeps only the call count. + other => { + let nc = other.num().ok_or("a caller's stats are not numbers")?; + Edge { caller, callee, nc, cc: nc, tt: 0.0, ct: 0.0 } + } + }; + edges.push(edge); + } + } + stats.resize_with(funcs.len(), Stat::default); + Ok((funcs, stats, edges)) +} + +/// Where a recorded file is here: absolute, or relative to `bases` (the profile was +/// written with the run's working directory, which isn't recorded). `None` for +/// built-ins (`~`), `` / `` and files that aren't on this machine. +fn source(file: &str, bases: &[&Path]) -> Option { + let p = Path::new(file); + if file == "~" || file.starts_with('<') { + return None; + } + if p.is_absolute() { + return p.is_file().then(|| p.to_path_buf()); + } + bases.iter().map(|b| b.join(p)).find(|p| p.is_file()) +} + +/// Where the rebuilt call tree starts, with the time spent there outside any recorded +/// caller. One start per strongly connected component of the call graph: a function that +/// calls back into itself through others (`exec` running an imported module, which runs +/// `exec`) has callers, yet they all run inside it. The component's heaviest function +/// stands for it, with its total minus what callers outside the component spent in it. +fn roots(stats: &[Stat], edges: &[Edge], callees: &[Vec<(usize, f64)>], min: f64) -> Vec<(usize, f64)> { + let comp = components(callees); + let count = comp.iter().max().map_or(0, |m| m + 1); + let mut incoming = vec![0.0; count]; + for e in edges { + if comp[e.caller] != comp[e.callee] { + incoming[comp[e.callee]] += e.ct; + } + } + let mut top: Vec> = vec![None; count]; + for (f, c) in comp.iter().enumerate() { + if top[*c].is_none_or(|t| stats[f].ct > stats[t].ct) { + top[*c] = Some(f); + } + } + let mut out: Vec<(usize, f64)> = top + .iter() + .enumerate() + .filter_map(|(c, t)| { + let t = (*t)?; + let w = stats[t].ct - incoming[c]; + (w > min).then_some((t, w)) + }) + .collect(); + if out.is_empty() + && let Some(f) = (0..stats.len()).max_by(|a, b| stats[*a].ct.total_cmp(&stats[*b].ct)) + { + out.push((f, stats[f].ct)); + } + out +} + +/// The strongly connected component of every function (Tarjan's algorithm, iterative). +fn components(callees: &[Vec<(usize, f64)>]) -> Vec { + const UNSEEN: usize = usize::MAX; + let n = callees.len(); + let (mut index, mut low, mut comp, mut on_stack) = (vec![UNSEEN; n], vec![0; n], vec![UNSEEN; n], vec![false; n]); + let (mut stack, mut next, mut count) = (Vec::new(), 0, 0); + for start in 0..n { + if index[start] != UNSEEN { + continue; + } + let mut work = vec![(start, 0usize)]; + (index[start], low[start], on_stack[start]) = (next, next, true); + stack.push(start); + next += 1; + while let Some(&(v, i)) = work.last() { + if let Some(&(w, _)) = callees[v].get(i) { + work.last_mut().unwrap().1 += 1; + if index[w] == UNSEEN { + (index[w], low[w], on_stack[w]) = (next, next, true); + stack.push(w); + next += 1; + work.push((w, 0)); + } else if on_stack[w] { + low[v] = low[v].min(index[w]); + } + continue; + } + work.pop(); + if let Some(&(p, _)) = work.last() { + low[p] = low[p].min(low[v]); + } + if low[v] == index[v] { + while let Some(w) = stack.pop() { + on_stack[w] = false; + comp[w] = count; + if w == v { + break; + } + } + count += 1; + } + } + } + comp +} + +/// Smallest share of the total a rebuilt call-tree node keeps, and the most nodes the +/// tree may have: a call graph with many paths would otherwise unfold exponentially. +const MIN_SHARE: f64 = 0.0005; +const MAX_NODES: usize = 200_000; +const MAX_DEPTH_TREE: u32 = 256; + +/// Reads a pstats file. Times become milliseconds. The method list and call edges are +/// exact; the call tree is rebuilt from the edges by sharing each function's time among +/// its callees in proportion, so it is an estimate below the first level. +pub(crate) fn read(bytes: &[u8], bases: &[&Path], profiler: &str) -> Result { + let (funcs, stats, edges) = parse(bytes)?; + let mut b = TreeBuilder::new(); + // Functions share files: look each one up once. + let mut sources: HashMap, Option> = HashMap::new(); + let frames: Vec = funcs + .iter() + .map(|f| { + let file = sources.entry(f.file.clone()).or_insert_with(|| source(&f.file, bases)).clone(); + let name = if &*f.file == "~" || file.is_some() { + f.name.to_string() + } else { + // Keep functions of files that aren't here apart, and say where they were. + format!("{} ({}:{})", f.name, f.file, f.line) + }; + let line = file.as_ref().map(|_| f.line.saturating_sub(1)); + b.frame(FrameKey { name, file, line, kind: Default::default() }) + }) + .collect(); + + let mut callees: Vec> = vec![Vec::new(); funcs.len()]; + for e in &edges { + callees[e.caller].push((e.callee, e.ct)); + } + let min = stats.iter().map(|s| s.tt).sum::() * MIN_SHARE; + // `profile` records no time per caller: without it only own times can be drawn. + let timed = edges.iter().any(|e| e.ct > 0.0); + let roots = if timed { roots(&stats, &edges, &callees, min) } else { Vec::new() }; + if !timed { + for (f, s) in stats.iter().enumerate() { + let node = b.child(0, frames[f]); + b.add_self(node, s.tt * 1000.0); + } + } + + enum Step { + Enter { parent: u32, func: usize, weight: f64, depth: u32 }, + Exit(usize), + } + let mut on_path = vec![false; funcs.len()]; + let mut stack: Vec = + roots.iter().map(|&(f, weight)| Step::Enter { parent: 0, func: f, weight, depth: 0 }).collect(); + while let Some(step) = stack.pop() { + let (parent, func, weight, depth) = match step { + Step::Exit(f) => { + on_path[f] = false; + continue; + } + Step::Enter { parent, func, weight, depth } => (parent, func, weight, depth), + }; + let node = b.child(parent, frames[func]); + if b.len() >= MAX_NODES || depth >= MAX_DEPTH_TREE { + b.add_self(node, weight * 1000.0); + continue; + } + on_path[func] = true; + stack.push(Step::Exit(func)); + let ct = stats[func].ct; + let scale = if ct > 0.0 { weight / ct } else { 0.0 }; + // A recursive call's time is already in the outer call's. + let kids: Vec<(usize, f64)> = + callees[func].iter().filter(|(c, _)| !on_path[*c]).map(|&(c, ect)| (c, ect * scale)).collect(); + let sum: f64 = kids.iter().map(|k| k.1).sum(); + // Mutual recursion can make the callees add up to more than the caller. + let fit = if sum > weight && sum > 0.0 { weight / sum } else { 1.0 }; + let mut kept = 0.0; + for (c, w) in kids { + let w = w * fit; + if w >= min && w > 0.0 { + kept += w; + stack.push(Step::Enter { parent: node, func: c, weight: w, depth: depth + 1 }); + } + } + b.add_self(node, (weight - kept).max(0.0) * 1000.0); + } + + let mut profile = b.finish(profiler, "ms", ProfileMode::Cpu); + profile.methods = (0..funcs.len()) + .filter(|f| stats[*f].nc > 0.0 || stats[*f].ct > 0.0) + .map(|f| MethodStat { + frame: frames[f], + self_weight: stats[f].tt * 1000.0, + total: stats[f].ct * 1000.0, + calls: Some(stats[f].nc), + primitive_calls: Some(stats[f].cc), + }) + .collect(); + profile.methods.sort_by(|a, b| b.self_weight.total_cmp(&a.self_weight).then(b.total.total_cmp(&a.total))); + profile.calls = edges + .iter() + .map(|e| CallEdge { + caller: frames[e.caller], + callee: frames[e.callee], + self_weight: e.tt * 1000.0, + total: e.ct * 1000.0, + calls: e.nc, + primitive_calls: e.cc, + }) + .collect(); + Ok(profile) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A tiny marshal writer for the shapes pstats uses (format 4: refs, short tuples and strings). + #[derive(Default)] + struct W(Vec); + impl W { + fn s(&mut self, v: &str) -> &mut Self { + self.0.push(b'z'); + self.0.push(v.len() as u8); + self.0.extend(v.as_bytes()); + self + } + fn i(&mut self, v: i32) -> &mut Self { + self.0.push(b'i'); + self.0.extend(v.to_le_bytes()); + self + } + fn g(&mut self, v: f64) -> &mut Self { + self.0.push(b'g'); + self.0.extend(v.to_le_bytes()); + self + } + fn tuple(&mut self, n: u8) -> &mut Self { + self.0.extend([b')', n]); + self + } + fn key(&mut self, (file, line, name): (&str, i32, &str)) -> &mut Self { + self.tuple(3).s(file).i(line).s(name) + } + } + + type Key<'a> = (&'a str, i32, &'a str); + /// `(caller, nc, cc, tt, ct)`. + type CallerRow<'a> = (Key<'a>, i32, i32, f64, f64); + /// `(func, cc, nc, tt, ct, callers)`. + type Row<'a> = (Key<'a>, i32, i32, f64, f64, &'a [CallerRow<'a>]); + + /// `rows` as a pstats file. + fn pstats(rows: &[Row]) -> Vec { + let mut w = W::default(); + w.0.push(b'{'); + for (f, cc, nc, tt, ct, callers) in rows { + w.key(*f).tuple(5).i(*cc).i(*nc).g(*tt).g(*ct); + w.0.push(b'{'); + for (c, nc, cc, tt, ct) in *callers { + w.key(*c).tuple(4).i(*nc).i(*cc).g(*tt).g(*ct); + } + w.0.push(b'0'); + } + w.0.push(b'0'); + w.0 + } + + fn name(p: &Profile, frame: u32) -> &str { + &p.frames[frame as usize].name + } + + fn method<'a>(p: &'a Profile, n: &str) -> &'a MethodStat { + p.methods.iter().find(|m| name(p, m.frame).starts_with(n)).unwrap() + } + + const EXEC: Key = ("~", 0, ""); + + #[test] + fn reads_a_file_written_by_cprofile() { + // `python -m cProfile -o out.prof work.py` (3.14), trimmed: refs, interned strings. + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("work.py"), "").unwrap(); + let bytes = pstats(&[ + (EXEC, 1, 1, 0.000_01, 0.004, &[]), + (("work.py", 1, ""), 1, 1, 0.000_002, 0.0039, &[(EXEC, 1, 1, 0.000_002, 0.0039)]), + (("work.py", 6, "main"), 1, 1, 0.000_002, 0.0038, &[(("work.py", 1, ""), 1, 1, 0.000_002, 0.0038)]), + ( + ("work.py", 1, "fib"), + 1, + 8361, + 0.002, + 0.002, + &[(("work.py", 1, "fib"), 8360, 2, 0.0019, 0.002), (("work.py", 6, "main"), 1, 1, 0.000_001, 0.002)], + ), + ( + ("/ci/runner/lib.py", 3, "helper"), + 2, + 2, + 0.0018, + 0.0018, + &[(("work.py", 6, "main"), 2, 2, 0.0018, 0.0018)], + ), + ]); + assert!(looks_like_pstats(&bytes)); + let p = read(&bytes, &[dir.path()], "cProfile").unwrap(); + assert_eq!((p.unit.as_str(), p.profiler.as_str()), ("ms", "cProfile")); + assert!((p.total - 4.0).abs() < 1e-9, "{}", p.total); + + // Recursion: 8361 calls, 1 primitive; own and total time as recorded. + let fib = method(&p, "fib"); + assert_eq!((fib.calls, fib.primitive_calls), (Some(8361.0), Some(1.0))); + assert!((fib.self_weight - 2.0).abs() < 1e-9 && (fib.total - 2.0).abs() < 1e-9); + let frame = &p.frames[fib.frame as usize]; + assert_eq!(frame.file.as_deref(), Some(dir.path().join("work.py").as_path())); + assert_eq!(frame.line, Some(0)); + + // A file that isn't here keeps its recorded location in the name, without a link. + let helper = &p.frames[method(&p, "helper").frame as usize]; + assert_eq!((helper.name.as_str(), helper.file.as_ref()), ("helper (/ci/runner/lib.py:3)", None)); + assert_eq!(name(&p, method(&p, ""); + + // Exact edges, including the recursive one. + let edge = |caller: &str, callee: &str| { + p.calls.iter().find(|e| name(&p, e.caller).starts_with(caller) && name(&p, e.callee).starts_with(callee)) + }; + assert_eq!(edge("fib", "fib").map(|e| (e.calls, e.primitive_calls)), Some((8360.0, 2.0))); + assert_eq!(edge("main", "helper").map(|e| e.calls), Some(2.0)); + + // The tree: exec → → main → {fib, helper}; fib's self-call is not unfolded. + let path = |names: &[&str]| { + let mut node = 0usize; + for n in names { + node = *p.nodes[node] + .children + .iter() + .find(|c| name(&p, p.nodes[**c as usize].frame).starts_with(n)) + .unwrap_or_else(|| panic!("no {n}")) as usize; + } + &p.nodes[node] + }; + let fib_node = path(&["", "main", "fib"]); + assert!(fib_node.children.is_empty()); + assert!((fib_node.total - 2.0).abs() < 1e-9); + assert!((path(&["", "main"]).total - 3.8).abs() < 1e-9); + } + + #[test] + fn reads_cpythons_own_output() { + // `python3.14 -m cProfile -o fib.prof work.py`: interned strings, refs, short tuples. + let p = read(include_bytes!("../testdata/fib.prof"), &[], "cProfile").unwrap(); + let fib = method(&p, "fib"); + assert_eq!((fib.calls, fib.primitive_calls), (Some(8361.0), Some(1.0))); + assert_eq!(name(&p, fib.frame), "fib (work.py:1)"); + assert!(p.methods.iter().any(|m| name(&p, m.frame) == "")); + let module = method(&p, ""); + assert!(p.total >= module.total && module.total > 0.0); + } + + #[test] + fn a_shared_callee_splits_its_time_by_caller() { + // a and b both call leaf; leaf spends 4 ms for a and 1 ms for b. + let bytes = pstats(&[ + (("m.py", 1, "a"), 1, 1, 0.0, 0.004, &[]), + (("m.py", 2, "b"), 1, 1, 0.0, 0.001, &[]), + ( + ("m.py", 3, "leaf"), + 5, + 5, + 0.005, + 0.005, + &[(("m.py", 1, "a"), 4, 4, 0.004, 0.004), (("m.py", 2, "b"), 1, 1, 0.001, 0.001)], + ), + ]); + let p = read(&bytes, &[], "cProfile").unwrap(); + let under = |n: &str| { + let root = + p.nodes[0].children.iter().find(|c| name(&p, p.nodes[**c as usize].frame).starts_with(n)).unwrap(); + p.nodes[p.nodes[*root as usize].children[0] as usize].total + }; + assert!((under("a ") - 4.0).abs() < 1e-9 && (under("b ") - 1.0).abs() < 1e-9); + } + + #[test] + fn a_function_that_calls_back_into_itself_through_others_is_still_the_root() { + // exec runs the script, whose import runs exec again: exec has a caller, inside itself. + let import: Key = ("", 1, "_call_with_frames_removed"); + let bytes = pstats(&[ + (EXEC, 2, 3, 0.0, 0.010, &[(import, 1, 1, 0.0, 0.003)]), + (("main.py", 1, ""), 1, 1, 0.006, 0.010, &[(EXEC, 1, 1, 0.006, 0.010)]), + (import, 1, 1, 0.0, 0.004, &[(("main.py", 1, ""), 1, 1, 0.0, 0.004)]), + (("~", 0, ""), 1, 1, 0.000_001, 0.000_001, &[]), + ]); + let p = read(&bytes, &[], "cProfile").unwrap(); + let roots: Vec<&str> = p.nodes[0].children.iter().map(|c| name(&p, p.nodes[*c as usize].frame)).collect(); + assert_eq!(roots, [""], "disable is below the share kept"); + assert!((p.total - 10.0).abs() < 1e-9, "{}", p.total); + let exec = &p.nodes[p.nodes[0].children[0] as usize]; + assert_eq!(name(&p, p.nodes[exec.children[0] as usize].frame), " (main.py:1)"); + } + + #[test] + fn without_times_per_caller_the_tree_is_flat() { + let mut w = W::default(); + w.0.push(b'{'); + w.key(("m.py", 1, "f")).tuple(5).i(1).i(1).g(0.002).g(0.003); + w.0.push(b'{'); + w.key(("m.py", 9, "g")).i(1); + w.0.push(b'0'); + w.key(("m.py", 9, "g")).tuple(5).i(1).i(1).g(0.001).g(0.003); + w.0.extend(b"{00"); + let p = read(&w.0, &[], "profile").unwrap(); + assert_eq!(p.nodes[0].children.len(), 2); + assert!((p.total - 3.0).abs() < 1e-9, "{}", p.total); + } + + #[test] + fn a_dense_call_graph_stays_bounded() { + // f0 → f1 → … with every fi also calling every fj (j > i): exponentially many paths. + let n = 60; + let keys: Vec = (0..n).map(|i| format!("f{i}")).collect(); + let mut rows = Vec::new(); + let callers: Vec> = + (0..n).map(|j| (0..j).map(|i| (("m.py", i as i32, keys[i].as_str()), 1, 1, 0.0, 1.0)).collect()).collect(); + for j in 0..n { + rows.push((("m.py", j as i32, keys[j].as_str()), 1, 1, 0.001, 1.0, callers[j].as_slice())); + } + let p = read(&pstats(&rows), &[], "cProfile").unwrap(); + assert!(p.nodes.len() <= MAX_NODES + 1, "{}", p.nodes.len()); + assert_eq!(p.methods.len(), n); + } + + #[test] + fn profile_module_caller_counts_and_long_ints() { + let mut w = W::default(); + w.0.push(b'{'); + w.key(("m.py", 1, "f")).tuple(5).i(1); + // 2**31 calls as a marshal long: digits 0, 0, 2 (15 bits each). + w.0.extend([b'l', 3, 0, 0, 0, 0, 0, 0, 0, 2, 0]); + w.g(0.5).g(0.5); + w.0.push(b'{'); + w.key(("m.py", 9, "g")).i(7); + w.0.extend(b"00"); + let p = read(&w.0, &[], "profile").unwrap(); + let f = method(&p, "f"); + assert_eq!(f.calls, Some(2f64.powi(31))); + assert_eq!(p.calls.iter().map(|e| e.calls).collect::>(), [7.0]); + } + + #[test] + fn garbage_is_an_error_not_a_panic() { + for bytes in [&b"{)"[..], b"{)\x03z\xff", b"{\xff", b"{)\x03z\x01~i\x00\x00\x00\x00r\xff\xff\xff\x7f"] { + assert!(read(bytes, &[], "cProfile").is_err(), "{bytes:?}"); + } + assert!(!looks_like_pstats(br#"{"nodes":[]}"#)); + assert!(looks_like_pstats(b"\xfb)\x03")); + } +} diff --git a/crates/ide-profiler/src/tree.rs b/crates/ide-profiler/src/tree.rs index aa98220488..23472f1285 100644 --- a/crates/ide-profiler/src/tree.rs +++ b/crates/ide-profiler/src/tree.rs @@ -79,6 +79,11 @@ impl TreeBuilder { self.add_self(node, weight); } + /// Nodes so far, the root included. + pub fn len(&self) -> usize { + self.nodes.len() + } + pub fn is_empty(&self) -> bool { self.nodes.len() <= 1 && self.nodes[0].self_weight == 0.0 } @@ -121,7 +126,16 @@ impl TreeBuilder { .map(|k| ProfileFrame { name: k.name, file: k.file.map(Into::into), line: k.line, kind: k.kind }) .collect(); let methods = methods(&nodes, frames.len()); - Profile { profiler: profiler.to_owned(), unit: unit.to_owned(), mode, total: totals[0], frames, nodes, methods } + Profile { + profiler: profiler.to_owned(), + unit: unit.to_owned(), + mode, + total: totals[0], + frames, + nodes, + methods, + calls: Vec::new(), + } } } @@ -150,7 +164,13 @@ fn methods(nodes: &[ProfileNode], frame_count: usize) -> Vec { let root_frame = nodes.first().map(|n| n.frame as usize); let mut out: Vec = (0..frame_count) .filter(|f| Some(*f) != root_frame && total_w[*f] > 0.0) - .map(|f| MethodStat { frame: f as u32, self_weight: self_w[f], total: total_w[f] }) + .map(|f| MethodStat { + frame: f as u32, + self_weight: self_w[f], + total: total_w[f], + calls: None, + primitive_calls: None, + }) .collect(); out.sort_by(|a, b| b.self_weight.total_cmp(&a.self_weight).then(b.total.total_cmp(&a.total))); out diff --git a/crates/ide-profiler/testdata/fib.prof b/crates/ide-profiler/testdata/fib.prof new file mode 100644 index 0000000000..254b5d4e22 Binary files /dev/null and b/crates/ide-profiler/testdata/fib.prof differ diff --git a/src/bindings.ts b/src/bindings.ts index e09adeedb4..c5e88d6a80 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -4212,6 +4212,23 @@ export type CMakeSettings_Serialize = { profiles?: CMakeProfile[] | null, }; +/** + * What one function spent when called from another, as a call-graph profiler (cProfile) + * records it. Sampling profilers leave [`Profile::calls`] empty; their callers and callees + * come from the call tree. + */ +export type CallEdge = { + /** Index into [`Profile::frames`]. */ + caller: number, + callee: number, + /** Weight spent in the callee itself on these calls. */ + selfWeight: number | null, + /** Weight of these calls, including what the callee called. */ + total: number | null, + calls: number | null, + primitiveCalls: number | null, +}; + export type CallHierarchy = { /** The symbol the hierarchy is for: the first item the server prepared at the position. */ root?: HierarchyItem | null, @@ -10569,6 +10586,10 @@ export type MethodStat = { frame: number, selfWeight: number | null, total: number | null, + /** Calls, when the profiler counts them (cProfile); sampling profilers don't. */ + calls: number | null, + /** Calls that were not recursive (`pstats`' primitive calls). */ + primitiveCalls: number | null, }; /** Dependency entry of a module (Project Structure › Modules › Dependencies). */ @@ -11765,6 +11786,11 @@ export type Profile = { nodes: ProfileNode[], /** Sorted by self weight, heaviest first. */ methods: MethodStat[], + /** + * Exact caller → callee totals of a call-graph profile; its call tree is then rebuilt + * from them, so below the first level it is an estimate. Empty for sampled profiles. + */ + calls: CallEdge[], }; export type ProfileFrame = { @@ -11816,8 +11842,12 @@ export type ProfileSpec = * out when another one did. */ { kind: "cpuProfiles"; dir: IpcPath; root: IpcPath } | -/** One `.cpuprofile` the user opened (saved by `node --cpu-prof`, Chrome DevTools, CI). */ -{ kind: "cpuProfileFile"; path: IpcPath } | +/** + * A snapshot file the user opened: a V8 `.cpuprofile` (`node --cpu-prof`, Chrome + * DevTools, CI) or a `pstats` file (cProfile, profile, yappi), told apart by content. + * Relative source files of a `pstats` file resolve against `root`, then its directory. + */ +{ kind: "snapshotFile"; path: IpcPath; root: IpcPath | null } | /** * Collapsed-stack files with extension `ext` in `dir`; relative frame files resolve * against `base`. `jvm_root`: map JVM class frames to sources below it. For the diff --git a/src/features/profiler/Profiler.module.css b/src/features/profiler/Profiler.module.css index 2694f85671..742463fc15 100644 --- a/src/features/profiler/Profiler.module.css +++ b/src/features/profiler/Profiler.module.css @@ -168,6 +168,30 @@ } /* method list */ +.methodPane { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; +} +.callSites { + flex: 0 0 40%; + min-height: 0; + display: flex; + border-top: 1px solid var(--border); +} +.callSites > .tableScroll + .tableScroll { + border-left: 1px solid var(--border); +} +.selectedRow, +.table tbody tr.selectedRow:hover { + background: var(--bg-active); +} +.count { + width: 90px; + font-variant-numeric: tabular-nums; + color: var(--fg-secondary); +} .tableScroll { flex: 1; min-height: 0; diff --git a/src/features/profiler/ProfilerView.test.tsx b/src/features/profiler/ProfilerView.test.tsx index 964a4d57d4..b72d431f60 100644 --- a/src/features/profiler/ProfilerView.test.tsx +++ b/src/features/profiler/ProfilerView.test.tsx @@ -24,7 +24,8 @@ function profile(mode: ProfileMode, total: number): Profile { { frame: 1, total, selfWeight: 0, children: [2] }, { frame: 2, total, selfWeight: total, children: [] }, ], - methods: [{ frame: 2, selfWeight: total, total }], + methods: [{ frame: 2, selfWeight: total, total, calls: null, primitiveCalls: null }], + calls: [], }; } @@ -132,4 +133,40 @@ describe("ProfilerView", () => { const labels = screen.getAllByRole("tab").map((t) => t.textContent); expect(labels).toEqual(["App · Live Objects", "App · Allocations", "App"]); }); + + it("lists call counts and the callers and callees of the selected method", () => { + const cpu = profile("cpu", 100); + addSnapshot("work.pstats", { + ...cpu, + profiler: "cProfile", + methods: [ + { frame: 1, selfWeight: 0, total: 100, calls: 1, primitiveCalls: 1 }, + { frame: 2, selfWeight: 100, total: 100, calls: 8361, primitiveCalls: 1 }, + ], + calls: [{ caller: 1, callee: 2, selfWeight: 100, total: 100, calls: 1, primitiveCalls: 1 }], + }); + useProfiler.setState({ tab: "methods" }); + render(); + const list = screen.getByRole("table", { name: "Method list" }); + expect(within(list).getByRole("columnheader", { name: "Calls" })).toBeInTheDocument(); + expect(within(list).getByText("8,361/1")).toBeInTheDocument(); + expect(screen.queryByRole("table", { name: "Callers" })).toBeNull(); + + fireEvent.click(within(list).getByText("Main.work")); + const callers = screen.getByRole("table", { name: "Callers" }); + expect(within(callers).getByText("Main.run")).toBeInTheDocument(); + expect(within(screen.getByRole("table", { name: "Callees" })).getByText("None")).toBeInTheDocument(); + + // A caller selects that method in the list. + fireEvent.click(within(callers).getByText("Main.run")); + expect(within(list).getByText("Main.run").closest("tr")).toHaveAttribute("aria-selected", "true"); + expect(within(screen.getByRole("table", { name: "Callees" })).getByText("Main.work")).toBeInTheDocument(); + }); + + it("shows no call counts for a sampled profile", () => { + addSnapshot("App", profile("cpu", 100)); + useProfiler.setState({ tab: "methods" }); + render(); + expect(screen.queryByRole("columnheader", { name: "Calls" })).toBeNull(); + }); }); diff --git a/src/features/profiler/ProfilerView.tsx b/src/features/profiler/ProfilerView.tsx index 678f83c017..08d1756053 100644 --- a/src/features/profiler/ProfilerView.tsx +++ b/src/features/profiler/ProfilerView.tsx @@ -9,7 +9,18 @@ import type { Profile } from "@/platform/ipc"; import { Button, EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui"; import { editorService } from "@/workbench/contributions"; import { executeAction } from "@/platform/actions"; -import { colorSlot, flameLayout, flameStep, formatWeight, frameLocation, matchingFrames, share } from "./model"; +import { + callSites, + colorSlot, + flameLayout, + flameStep, + formatCalls, + formatWeight, + frameLocation, + matchingFrames, + share, + type CallSite, +} from "./model"; import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store"; import styles from "./Profiler.module.css"; import { useTx } from "@/platform/i18n"; @@ -233,21 +244,33 @@ function CallTree({ profile }: { profile: Profile }) { ); } -type MethodSort = "self" | "total" | "name"; +type MethodSort = "self" | "total" | "name" | "calls"; const MAX_METHODS = 2000; function MethodList({ profile, query }: { profile: Profile; query: string }) { const tx = useTx(); const [sort, setSort] = useState("self"); + const [selected, setSelected] = useState(null); const total = profile.total ?? 0; + const counted = profile.methods.some((m) => m.calls !== null); const rows = useMemo(() => { const matches = matchingFrames(profile, query); const list = profile.methods.filter((m) => !matches || matches.has(m.frame)); const name = (f: number) => profile.frames[f]!.name; if (sort === "name") list.sort((a, b) => name(a.frame).localeCompare(name(b.frame))); else if (sort === "total") list.sort((a, b) => (b.total ?? 0) - (a.total ?? 0)); + else if (sort === "calls") list.sort((a, b) => (b.calls ?? 0) - (a.calls ?? 0)); return list.slice(0, MAX_METHODS); }, [profile, query, sort]); + const sites = useMemo(() => (selected === null ? null : callSites(profile, selected)), [profile, selected]); + // Picking a caller or callee selects it in the list, even when the search hides it. + const select = (frame: number) => { + setSelected(frame); + if (!rows.some((m) => m.frame === frame)) useProfiler.setState({ query: "" }); + }; + useEffect(() => { + if (selected !== null) document.getElementById(`method-${selected}`)?.scrollIntoView?.({ block: "nearest" }); + }, [selected]); const header = (key: MethodSort, label: string) => ( ); + return ( +
+
+ + + + {header("name", "Method")} + {header("self", "Self")} + {header("total", "Total")} + {counted && header("calls", "Calls")} + + + + {rows.map((m) => { + const location = frameLocation(profile, m.frame); + return ( + setSelected(m.frame)} + onDoubleClick={() => openFrame(profile, m.frame)} + > + + + + {counted && ( + + )} + + ); + })} + +
+ {profile.frames[m.frame]!.name} + + {location && {location}} + + {formatWeight(m.selfWeight ?? 0, profile.unit)}{" "} + {share(m.selfWeight ?? 0, total)} + + {formatWeight(m.total ?? 0, profile.unit)}{" "} + {share(m.total ?? 0, total)} + {m.calls !== null ? formatCalls(m.calls, m.primitiveCalls) : ""}
+
+ {sites && selected !== null && ( +
+ + +
+ )} +
+ ); +} + +/** The callers or callees of the selected method: click selects one, double-click opens its source. */ +function CallSiteList({ + title, + profile, + sites, + onSelect, +}: { + title: string; + profile: Profile; + sites: CallSite[]; + onSelect: (frame: number) => void; +}) { + const tx = useTx(); + const total = profile.total ?? 0; return (
- +
- {header("name", "Method")} - {header("self", "Self")} - {header("total", "Total")} + + + {sites.some((x) => x.calls !== null) && ( + + )} - {rows.map((m) => { - const location = frameLocation(profile, m.frame); + {sites.map((x) => { + const location = frameLocation(profile, x.frame); return ( - openFrame(profile, m.frame)}> + onSelect(x.frame)} onDoubleClick={() => openFrame(profile, x.frame)}> - + {x.calls !== null && } ); })} + {!sites.length && ( + + + + )}
+ {tx(title)} + + {tx("Total")} + + {tx("Calls")} +
- {profile.frames[m.frame]!.name} - + {profile.frames[x.frame]!.name} {location && {location}} - {formatWeight(m.selfWeight ?? 0, profile.unit)}{" "} - {share(m.selfWeight ?? 0, total)} - - {formatWeight(m.total ?? 0, profile.unit)}{" "} - {share(m.total ?? 0, total)} + {formatWeight(x.total, profile.unit)} {share(x.total, total)} {formatCalls(x.calls, x.primitiveCalls)}
+ None +
@@ -349,7 +452,7 @@ export function ProfilerView() {
{tab === "flame" && } {tab === "tree" && } - {tab === "methods" && } + {tab === "methods" && }
); diff --git a/src/features/profiler/cpuProfiles.test.ts b/src/features/profiler/cpuProfiles.test.ts index 888d1531cc..bc6c65a935 100644 --- a/src/features/profiler/cpuProfiles.test.ts +++ b/src/features/profiler/cpuProfiles.test.ts @@ -10,7 +10,8 @@ vi.mock("@/workbench/contributions", () => ({ toolWindowService: () => ({ show: () => undefined }), })); vi.mock("@/platform/choosePath", () => ({ choosePaths: () => Promise.resolve(picked) })); -const profile = { profiler: "v8", unit: "samples", mode: "cpu", total: 3, frames: [] } as unknown as Profile; +let profile = { profiler: "v8", unit: "samples", mode: "cpu", total: 3, frames: [], calls: [] } as unknown as Profile; +vi.mock("@/platform/project", () => ({ useProject: { getState: () => ({ project: { root: "/work/app" } }) } })); vi.mock("@/platform/ipc", async (orig) => { const real = await orig(); return { @@ -29,10 +30,11 @@ vi.mock("@/platform/ipc", async (orig) => { }; }); -const { isCpuProfilePath, openCpuProfileFiles, showCpuProfiles } = await import("./cpuProfiles"); +const { isSnapshotPath, openSnapshotFiles, showCpuProfiles } = await import("./cpuProfiles"); const { resetProfiler, useProfiler } = await import("./store"); beforeEach(() => { + profile = { ...profile, calls: [] }; collected.length = 0; fails = false; picked = []; @@ -67,32 +69,32 @@ describe("Open Snapshot", () => { const names = () => useProfiler.getState().snapshots.map((s) => s.name); it("opens each .cpuprofile file as its own snapshot", async () => { - await openCpuProfileFiles(["/work/app/CPU.1.cpuprofile", "C:\\ci\\run.cpuprofile"]); + await openSnapshotFiles(["/work/app/CPU.1.cpuprofile", "C:\\ci\\run.cpuprofile"]); expect(collected).toEqual([ - { kind: "cpuProfileFile", path: "/work/app/CPU.1.cpuprofile" }, - { kind: "cpuProfileFile", path: "C:\\ci\\run.cpuprofile" }, + { kind: "snapshotFile", path: "/work/app/CPU.1.cpuprofile", root: "/work/app" }, + { kind: "snapshotFile", path: "C:\\ci\\run.cpuprofile", root: "/work/app" }, ]); expect(names()).toEqual(["run.cpuprofile", "CPU.1.cpuprofile"]); }); it("asks for the files when the action has none, and opens nothing when cancelled", async () => { - await openCpuProfileFiles(undefined); + await openSnapshotFiles(undefined); expect(collected).toEqual([]); picked = ["/tmp/a.cpuprofile"]; - await openCpuProfileFiles(undefined); + await openSnapshotFiles(undefined); expect(names()).toEqual(["a.cpuprofile"]); }); it("skips a file that is not a CPU profile and still opens the others", async () => { - fails = (spec) => spec.kind === "cpuProfileFile" && spec.path.endsWith("bad.cpuprofile"); - await expect(openCpuProfileFiles(["/tmp/bad.cpuprofile", "/tmp/good.cpuprofile"])).resolves.toBeUndefined(); + fails = (spec) => spec.kind === "snapshotFile" && spec.path.endsWith("bad.cpuprofile"); + await expect(openSnapshotFiles(["/tmp/bad.cpuprofile", "/tmp/good.cpuprofile"])).resolves.toBeUndefined(); expect(names()).toEqual(["good.cpuprofile"]); }); it("replaces the snapshot of a file opened again", async () => { - await openCpuProfileFiles(["/tmp/a.cpuprofile", "/tmp/b.cpuprofile"]); + await openSnapshotFiles(["/tmp/a.cpuprofile", "/tmp/b.cpuprofile"]); const first = useProfiler.getState().snapshots.find((s) => s.name === "a.cpuprofile")!.id; - await openCpuProfileFiles("/tmp/a.cpuprofile"); + await openSnapshotFiles("/tmp/a.cpuprofile"); const state = useProfiler.getState(); expect(names()).toEqual(["a.cpuprofile", "b.cpuprofile"]); expect(state.activeId).toBe(first); @@ -100,7 +102,7 @@ describe("Open Snapshot", () => { it("says which snapshots it closed to stay within the limit, recordings included", async () => { await showCpuProfiles({ name: "localhost:5173", dir: "/tmp/p", root: "/work/shop" }); - await openCpuProfileFiles([1, 2, 3, 4, 5].map((n) => `/tmp/${n}.cpuprofile`)); + await openSnapshotFiles([1, 2, 3, 4, 5].map((n) => `/tmp/${n}.cpuprofile`)); expect(names()).toEqual(["5.cpuprofile", "4.cpuprofile", "3.cpuprofile", "2.cpuprofile", "1.cpuprofile"]); expect(notified).toEqual([ { @@ -112,9 +114,21 @@ describe("Open Snapshot", () => { ]); }); - it("recognises .cpuprofile files by extension", () => { - expect(isCpuProfilePath("/a/CPU.20261126.cpuprofile")).toBe(true); - expect(isCpuProfilePath("/a/X.CPUPROFILE")).toBe(true); - expect(isCpuProfilePath("/a/cpuprofile.json")).toBe(false); + it("recognises snapshot files by extension", () => { + expect(isSnapshotPath("/a/CPU.20261126.cpuprofile")).toBe(true); + expect(isSnapshotPath("/a/X.CPUPROFILE")).toBe(true); + expect(isSnapshotPath("/a/cpuprofile.json")).toBe(false); + expect(["/a/out.pstats", "/a/run.PROF", "/a/prof"].map(isSnapshotPath)).toEqual([true, true, false]); + }); + + it("says that a cProfile snapshot's call tree is estimated", async () => { + await openSnapshotFiles("/tmp/a.cpuprofile"); + profile = { ...profile, calls: [{ caller: 1, callee: 2, selfWeight: 1, total: 2, calls: 3, primitiveCalls: 3 }] }; + await openSnapshotFiles("/tmp/out.pstats"); + const notices = useProfiler.getState().snapshots.map((s) => [s.name, s.notice !== null]); + expect(notices).toEqual([ + ["out.pstats", true], + ["a.cpuprofile", false], + ]); }); }); diff --git a/src/features/profiler/cpuProfiles.ts b/src/features/profiler/cpuProfiles.ts index 233af1567e..e757927024 100644 --- a/src/features/profiler/cpuProfiles.ts +++ b/src/features/profiler/cpuProfiles.ts @@ -1,6 +1,7 @@ import { choosePaths } from "@/platform/choosePath"; import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; import { notifications, toolWindowService } from "@/workbench/contributions"; import { addSnapshot } from "./store"; @@ -51,7 +52,11 @@ function showProfiler() { } } -export const isCpuProfilePath = (path: string) => path.toLowerCase().endsWith(".cpuprofile"); +const SNAPSHOT_EXTENSIONS = ["cpuprofile", "pstats", "prof"]; + +/** A file the Profiler opens: a V8 `.cpuprofile` or a cProfile `.pstats` / `.prof`. */ +export const isSnapshotPath = (path: string) => + SNAPSHOT_EXTENSIONS.includes(path.split(".").pop()?.toLowerCase() ?? ""); /** The paths to open: the action's arg (a path or paths), else the ones picked in a file dialog. */ async function snapshotPaths(arg: unknown): Promise { @@ -60,24 +65,29 @@ async function snapshotPaths(arg: unknown): Promise { return choosePaths({ directory: false, title: tx("Open Snapshot"), - filters: [{ name: tx("V8 CPU profile"), extensions: ["cpuprofile"] }], + filters: [{ name: tx("Profiler snapshots"), extensions: SNAPSHOT_EXTENSIONS }], }); } -/** Opens `.cpuprofile` files (`node --cpu-prof`, Chrome DevTools), each as its own snapshot. */ -export async function openCpuProfileFiles(arg: unknown): Promise { +/** Opens snapshot files (`node --cpu-prof`, Chrome DevTools, cProfile), each as its own snapshot. */ +export async function openSnapshotFiles(arg: unknown): Promise { + const root = useProject.getState().project?.root ?? null; let opened = false; for (const path of await snapshotPaths(arg)) { try { // oxlint-disable-next-line no-await-in-loop -- one snapshot per file, in the order picked - const profile = await call(commands.profilerCollect({ kind: "cpuProfileFile", path })); - addSnapshot(path.split(/[/\\]/).pop() ?? path, profile, null, path); + const profile = await call(commands.profilerCollect({ kind: "snapshotFile", path, root })); + // A call-graph profile (cProfile) has exact edges but only an estimated call tree. + const notice = profile.calls.length + ? "cProfile records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact." + : null; + addSnapshot(path.split(/[/\\]/).pop() ?? path, profile, notice, path); opened = true; } catch (e) { notifications().notify({ group: "run", level: "error", - title: "Cannot open the CPU profile", + title: "Cannot open the profiler snapshot", body: e instanceof Error ? e.message : String(e), }); } diff --git a/src/features/profiler/index.ts b/src/features/profiler/index.ts index c53bae0fc7..2a5b583849 100644 --- a/src/features/profiler/index.ts +++ b/src/features/profiler/index.ts @@ -11,17 +11,18 @@ import { registerToolWindow, type EditorBanner, } from "@/workbench/contributions"; -import { isCpuProfilePath, openCpuProfileFiles, showCpuProfiles } from "./cpuProfiles"; +import { isSnapshotPath, openSnapshotFiles, showCpuProfiles } from "./cpuProfiles"; import { profilerExecutor } from "./executor"; import { ProfilerHeaderActions, ProfilerTabs, ProfilerView } from "./ProfilerView"; import { resetProfiler } from "./store"; +// cProfile snapshots are binary: they open in the hex viewer, which shows no banners. function useCpuProfileBanner(path: string): EditorBanner | null { - if (!isCpuProfilePath(path)) return null; + if (!path.toLowerCase().endsWith(".cpuprofile")) return null; return { text: "This file is a V8 CPU profile", icon: "profile", - actions: [{ label: "Open in Profiler", run: () => void openCpuProfileFiles(path) }], + actions: [{ label: "Open in Profiler", run: () => void openSnapshotFiles(path) }], }; } @@ -47,7 +48,7 @@ export function activate(): () => void { menus: ["projectView", "editor", "editorTab"], order: 45, items: (_menu, { paths, dirs }) => - paths.length && paths.every((p, i) => !dirs?.[i] && isCpuProfilePath(p)) + paths.length && paths.every((p, i) => !dirs?.[i] && isSnapshotPath(p)) ? [{ kind: "action", action: "profiler.openInProfiler", arg: paths }] : [], }), @@ -75,22 +76,23 @@ export function activate(): () => void { { id: "profiler.openSnapshot", title: "Open Snapshot…", - description: "Open V8 .cpuprofile files saved by node --cpu-prof or Chrome DevTools in the Profiler", + description: + "Open V8 .cpuprofile files (node --cpu-prof, Chrome DevTools) or cProfile .pstats / .prof files in the Profiler", category: "Profiler", icon: "profile", when: "projectOpen", - keywords: ["cpuprofile", "profiler", "snapshot", "flame graph"], - run: () => openCpuProfileFiles(undefined), + keywords: ["cpuprofile", "pstats", "cprofile", "profiler", "snapshot", "flame graph"], + run: () => openSnapshotFiles(undefined), }, { id: "profiler.openInProfiler", title: "Open in Profiler", - description: "Open the selected .cpuprofile files as Profiler snapshots", + description: "Open the selected .cpuprofile, .pstats or .prof files as Profiler snapshots", category: "Profiler", icon: "profile", hidden: true, when: "projectOpen", - run: ({ arg }) => (arg === undefined ? undefined : openCpuProfileFiles(arg)), + run: ({ arg }) => (arg === undefined ? undefined : openSnapshotFiles(arg)), }, { id: "run.profileAllocations", diff --git a/src/features/profiler/model.ts b/src/features/profiler/model.ts index 6868ba3d1c..ed279815ae 100644 --- a/src/features/profiler/model.ts +++ b/src/features/profiler/model.ts @@ -175,3 +175,67 @@ export function colorSlot(name: string): number { for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) | 0; return (Math.abs(h) % 4) + 1; } + +/** A caller or callee of a function, with what the calls between the two took. */ +export interface CallSite { + frame: number; + total: number; + /** Known for call-graph profiles (cProfile) only. */ + calls: number | null; + primitiveCalls: number | null; +} + +/** + * Callers and callees of `frame`, heaviest first: the exact edges of a call-graph profile, + * else summed from the call tree, counting a recursive function at its outermost call only. + */ +export function callSites(profile: Profile, frame: number): { callers: CallSite[]; callees: CallSite[] } { + const byTotal = (a: CallSite, b: CallSite) => b.total - a.total; + if (profile.calls.length) { + const site = (other: number, e: (typeof profile.calls)[number]): CallSite => ({ + frame: other, + total: e.total ?? 0, + calls: e.calls ?? 0, + primitiveCalls: e.primitiveCalls ?? 0, + }); + return { + callers: profile.calls + .filter((e) => e.callee === frame) + .map((e) => site(e.caller, e)) + .sort(byTotal), + callees: profile.calls + .filter((e) => e.caller === frame) + .map((e) => site(e.callee, e)) + .sort(byTotal), + }; + } + const nodes = profile.nodes; + const callers = new Map(); + const callees = new Map(); + const add = (m: Map, f: number, w: number) => m.set(f, (m.get(f) ?? 0) + w); + // How many calls of `frame` are above the node being visited. + let above = 0; + const stack: Array<{ node: number; parent: number; exit: boolean }> = [{ node: 0, parent: -1, exit: false }]; + while (stack.length) { + const { node, parent, exit } = stack.pop()!; + const n = nodes[node]!; + if (exit) { + if (n.frame === frame) above--; + continue; + } + if (n.frame === frame && above === 0 && parent > 0) add(callers, nodes[parent]!.frame, n.total ?? 0); + if (parent >= 0 && nodes[parent]!.frame === frame && above === 1) add(callees, n.frame, n.total ?? 0); + if (n.frame === frame) above++; + stack.push({ node, parent, exit: true }); + for (const c of n.children) stack.push({ node: c, parent: node, exit: false }); + } + const sites = (m: Map) => + [...m].map(([f, total]): CallSite => ({ frame: f, total, calls: null, primitiveCalls: null })).sort(byTotal); + return { callers: sites(callers), callees: sites(callees) }; +} + +/** `12` or, when some calls were recursive, `12/1` (total/primitive), as `pstats` prints it. */ +export function formatCalls(calls: number, primitive: number | null): string { + const n = (v: number) => Math.round(v).toLocaleString("en-US"); + return primitive !== null && primitive !== calls ? `${n(calls)}/${n(primitive)}` : n(calls); +} diff --git a/src/features/profiler/profiler.test.ts b/src/features/profiler/profiler.test.ts index 63f099f613..27e834a710 100644 --- a/src/features/profiler/profiler.test.ts +++ b/src/features/profiler/profiler.test.ts @@ -9,6 +9,8 @@ import { frameLocation, matchingFrames, profilerSupports, + callSites, + formatCalls, share, } from "./model"; @@ -31,6 +33,7 @@ const profile: Profile = { { frame: 3, total: 2, selfWeight: 2, children: [] }, ], methods: [], + calls: [], }; function cfg(command: string, args: string[], kind = "shell"): RunConfig { @@ -128,3 +131,64 @@ describe("flameStep", () => { expect(flameStep(rects, 2, "shallower")).toBe(0); }); }); + +describe("callers and callees", () => { + const names = (sites: Array<{ frame: number; total: number }>) => + sites.map((x) => [recursive.frames[x.frame]!.name, x.total]); + // all(10) → main(10) → f(8) → f(5) → g(5); main → g(2) + const recursive: Profile = { + ...profile, + frames: [ + ...profile.frames.slice(0, 2), + { name: "f", file: null, line: null, kind: "code" }, + { name: "g", file: null, line: null, kind: "code" }, + ], + nodes: [ + { frame: 0, total: 10, selfWeight: 0, children: [1] }, + { frame: 1, total: 10, selfWeight: 0, children: [2, 5] }, + { frame: 2, total: 8, selfWeight: 3, children: [3] }, + { frame: 2, total: 5, selfWeight: 0, children: [4] }, + { frame: 3, total: 5, selfWeight: 5, children: [] }, + { frame: 3, total: 2, selfWeight: 2, children: [] }, + ], + }; + + it("come from the call tree, a recursive function counted at its outermost call", () => { + const f = callSites(recursive, 2); + expect(names(f.callers)).toEqual([["main", 8]]); + expect(names(f.callees)).toEqual([["f", 5]]); + expect(f.callers[0]!.calls).toBeNull(); + const g = callSites(recursive, 3); + expect(names(g.callers)).toEqual([ + ["f", 5], + ["main", 2], + ]); + expect(callSites(recursive, 1).callers).toEqual([]); + }); + + it("are the recorded edges of a call-graph profile", () => { + const graph: Profile = { + ...recursive, + calls: [ + { caller: 1, callee: 2, selfWeight: 1, total: 4, calls: 1, primitiveCalls: 1 }, + { caller: 2, callee: 2, selfWeight: 3, total: 4, calls: 99, primitiveCalls: 0 }, + { caller: 2, callee: 3, selfWeight: 6, total: 6, calls: 7, primitiveCalls: 7 }, + ], + }; + const f = callSites(graph, 2); + expect(f.callers.map((x) => [x.frame, x.calls])).toEqual([ + [1, 1], + [2, 99], + ]); + expect(f.callees.map((x) => [x.frame, x.total, x.calls])).toEqual([ + [3, 6, 7], + [2, 4, 99], + ]); + }); + + it("show recursive call counts as total/primitive", () => { + expect(formatCalls(8361, 1)).toBe("8,361/1"); + expect(formatCalls(3, 3)).toBe("3"); + expect(formatCalls(3, null)).toBe("3"); + }); +}); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index f55b6109fc..50c5b55b87 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2715,12 +2715,17 @@ "No CPU profile to show": "No CPU profile to show", "Open Snapshot…": "Open Snapshot…", "Open Snapshot": "Open Snapshot", - "Open V8 .cpuprofile files saved by node --cpu-prof or Chrome DevTools in the Profiler": "Open V8 .cpuprofile files saved by node --cpu-prof or Chrome DevTools in the Profiler", "Open in Profiler": "Open in Profiler", - "Open the selected .cpuprofile files as Profiler snapshots": "Open the selected .cpuprofile files as Profiler snapshots", "This file is a V8 CPU profile": "This file is a V8 CPU profile", - "V8 CPU profile": "V8 CPU profile", - "Cannot open the CPU profile": "Cannot open the CPU profile", + "Open V8 .cpuprofile files (node --cpu-prof, Chrome DevTools) or cProfile .pstats / .prof files in the Profiler": "Open V8 .cpuprofile files (node --cpu-prof, Chrome DevTools) or cProfile .pstats / .prof files in the Profiler", + "Open the selected .cpuprofile, .pstats or .prof files as Profiler snapshots": "Open the selected .cpuprofile, .pstats or .prof files as Profiler snapshots", + "Profiler snapshots": "Profiler snapshots", + "Cannot open the profiler snapshot": "Cannot open the profiler snapshot", + "cProfile records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact.": "cProfile records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact.", + "Method list": "Method list", + "Calls": "Calls", + "Callers": "Callers", + "Callees": "Callees", "Closed older profiler snapshots": "Closed older profiler snapshots", "The Profiler keeps the last {max} snapshots open; closed {names}.": "The Profiler keeps the last {max} snapshots open; closed {names}.", "Profiler": "Profiler", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 8c5cba1c44..9219776b78 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9245,12 +9245,14 @@ "No CPU profile to show": "没有可显示的 CPU 性能分析", "Open Snapshot…": "打开快照…", "Open Snapshot": "打开快照", - "Open V8 .cpuprofile files saved by node --cpu-prof or Chrome DevTools in the Profiler": "在性能分析器中打开由 node --cpu-prof 或 Chrome DevTools 保存的 V8 .cpuprofile 文件", "Open in Profiler": "在性能分析器中打开", - "Open the selected .cpuprofile files as Profiler snapshots": "将选中的 .cpuprofile 文件作为性能分析快照打开", "This file is a V8 CPU profile": "此文件是 V8 CPU 性能分析文件", - "V8 CPU profile": "V8 CPU 性能分析文件", - "Cannot open the CPU profile": "无法打开 CPU 性能分析文件", + "Open V8 .cpuprofile files (node --cpu-prof, Chrome DevTools) or cProfile .pstats / .prof files in the Profiler": "在性能分析器中打开 V8 .cpuprofile 文件(node --cpu-prof、Chrome DevTools)或 cProfile .pstats / .prof 文件", + "Open the selected .cpuprofile, .pstats or .prof files as Profiler snapshots": "将选中的 .cpuprofile、.pstats 或 .prof 文件作为性能分析快照打开", + "Cannot open the profiler snapshot": "无法打开性能分析快照", + "cProfile records callers and callees, not whole stacks: the flame graph and call tree are estimated from them. The method list is exact.": "cProfile 只记录调用方和被调用方,不记录完整调用栈:火焰图和调用树是据此估算的,方法列表是精确的。", + "Method list": "方法列表", + "Calls": "调用次数", "Closed older profiler snapshots": "已关闭较早的性能分析快照", "The Profiler keeps the last {max} snapshots open; closed {names}.": "性能分析器只保留最近 {max} 个快照;已关闭 {names}。", "Opens the V8 .cpuprofile files of a directory as a snapshot (arg: { name, dir, root, profiler? }).": "将目录中的 V8 .cpuprofile 文件作为快照打开(参数:{ name, dir, root, profiler? })。",