From d1c07306e90a4f04ab20a1275ceeedbf42dfff44 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 5 Dec 2026 11:10:00 +0900 Subject: [PATCH] feat(profiler): profile Python runs with yappi (threads, asyncio) (#7466) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Profile on a Python run configuration uses yappi when the run's interpreter can import it: Automatic picks yappi, else py-spy where it can sample without root, else cProfile, and Settings › Python › Profiler gains a yappi choice (missing yappi offers `python -m pip install yappi`, or only the homepage under uv/poetry). yappi runs through python_profile.py with the wall clock and builtins, so a coroutine's time includes its awaits and every thread is profiled; the launcher writes the merged profile.pstats plus one pstats per thread and threads.json (busiest 64), converted to cProfile's call-count order and built-in names. Non-daemon threads and pools are waited for before saving, except after Stop. The Profiler view gets a thread selector (All threads merged, then each thread) when a run has two or more threads. The Rust CI job installs yappi 1.7.6 in a venv on GitHub-hosted runners for the real-interpreter tests. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- .github/workflows/ci.yml | 17 + crates/ide-core/src/settings.rs | 5 +- crates/ide-profiler/src/lib.rs | 38 +- crates/ide-profiler/src/plan.rs | 109 ++++- crates/ide-profiler/src/python_profile.py | 87 +++- crates/ide-profiler/src/tree.rs | 1 + crates/ide-profiler/tests/python_yappi.rs | 419 ++++++++++++++++++ docs/en/guide/profiler.mdx | 3 +- docs/en/languages/python.mdx | 4 +- docs/zh/guide/profiler.mdx | 3 +- docs/zh/languages/python.mdx | 4 +- src/bindings.ts | 22 +- src/features/profiler/ProfilerView.test.tsx | 45 ++ src/features/profiler/ProfilerView.tsx | 58 ++- src/features/profiler/executor.ts | 8 +- src/features/profiler/model.ts | 6 +- src/features/profiler/profiler.test.ts | 1 + src/features/profiler/store.ts | 20 +- src/features/profiler/threads.test.tsx | 110 +++++ .../settings/languages/PythonProfilerPage.tsx | 3 +- src/features/settings/pages/languages.tsx | 2 +- src/platform/i18n.test.ts | 1 + src/platform/languageSettings.ts | 2 +- src/platform/locales/text/en.json | 6 +- src/platform/locales/text/zh.json | 6 +- 25 files changed, 924 insertions(+), 56 deletions(-) create mode 100644 crates/ide-profiler/tests/python_yappi.rs create mode 100644 src/features/profiler/threads.test.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0688350912..24f34f76dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -217,6 +217,23 @@ jobs: with: path: ${{ runner.temp }}/jbuild-maven-repository key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }} + # python_yappi.rs profiles real runs. Self-hosted runners have no setup-python; without + # YAPPI_PYTHON those tests return early. + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + if: runner.environment == 'github-hosted' + id: yappi-python + with: { python-version: "3.12", update-environment: false } + - name: Install yappi for the Python profiler tests + if: steps.yappi-python.outputs.python-path != '' + shell: bash + env: + PYTHON: ${{ steps.yappi-python.outputs.python-path }} + run: | + "$PYTHON" -m venv "$RUNNER_TEMP/yappi-venv" + venv_py="$RUNNER_TEMP/yappi-venv/bin/python" + [ -x "$venv_py" ] || venv_py="$RUNNER_TEMP/yappi-venv/Scripts/python.exe" + "$venv_py" -m pip install yappi==1.7.6 + echo "YAPPI_PYTHON=$venv_py" >> "$GITHUB_ENV" # python_memray.rs profiles real runs. memray has no Windows build. - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 if: runner.os != 'Windows' && runner.environment == 'github-hosted' diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 76a75740f8..1fa5d3cbd9 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -1921,8 +1921,9 @@ pub struct PythonSettings { /// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses /// it, else unittest), `pytest` or `unittest`. pub test_runner: String, - /// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it - /// is installed and samples without root, else cProfile), `cprofile` or `py-spy`. + /// What Profile runs Python under (Settings › Python › Profiler): `auto` (yappi when the + /// interpreter can import it, else py-spy where it is installed and samples without root, else + /// cProfile), `cprofile`, `py-spy` or `yappi`. pub profiler: String, /// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND` /// unless the run sets it); off: matplotlib's own window. diff --git a/crates/ide-profiler/src/lib.rs b/crates/ide-profiler/src/lib.rs index 273b031757..06fbb66888 100644 --- a/crates/ide-profiler/src/lib.rs +++ b/crates/ide-profiler/src/lib.rs @@ -7,7 +7,7 @@ //! | runtime | profiler | output | //! |---|---|---| //! | Node.js (scripts, npm scripts) | `node --cpu-prof` (via `NODE_OPTIONS`) | `.cpuprofile` JSON | -//! | Python | cProfile (`python_profile.py`), or `py-spy record --format raw` | pstats, or collapsed stacks | +//! | Python | yappi or cProfile (`python_profile.py`), or `py-spy record --format raw` | pstats, or collapsed stacks | //! | Python allocations (macOS/Linux) | memray (`python_profile.py`), then `memray transform csv` | CSV | //! | JVM applications | async-profiler agent (`JAVA_TOOL_OPTIONS`) | collapsed stacks | //! | native / `cargo run` (Linux) | `perf record -g`, then `perf script` | perf script text | @@ -113,7 +113,7 @@ pub struct CallEdge { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct Profile { - /// `node --cpu-prof`, `py-spy`, `async-profiler`, `perf`. + /// `node --cpu-prof`, `yappi`, `cProfile`, `py-spy`, `async-profiler`, `perf`. pub profiler: String, /// `ms` (time-weighted), `samples` (sample or live-object counts) or `bytes` (allocated). pub unit: String, @@ -127,6 +127,18 @@ pub struct Profile { /// 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, + /// The threads of a yappi run, busiest first; empty when the profiler does not tell them apart. + pub threads: Vec, +} + +/// A thread of a yappi run. Its own profile is `collect`ed with the spec's `thread` set to `id`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ProfileThread { + pub id: u32, + pub name: String, + /// Seconds the thread ran (wall clock). + pub total: f64, } /// Where a prepared run's profile will be, and how to read it. @@ -142,8 +154,9 @@ pub enum ProfileSpec { /// Relative source files of a `pstats` file resolve against `root`, then its directory. SnapshotFile { path: IpcPath, root: Option }, /// What `python_profile.py` wrote in `dir` for a profiled Python run: `profile.pstats`. - /// Relative source files resolve against `root`. - PythonRun { profiler: String, dir: IpcPath, root: IpcPath }, + /// Relative source files resolve against `root`. `thread`: a yappi run's thread to show + /// (`Profile::threads`), else all threads merged. + PythonRun { profiler: String, dir: IpcPath, root: IpcPath, thread: Option }, /// The `memray.bin` capture `python_profile.py` wrote in `dir`, read with /// ` -m memray transform csv`: what was allocated at the memory peak. /// Relative source files resolve against `root`, where the command runs. @@ -181,6 +194,15 @@ fn files_with_ext(dir: &Path, ext: &str) -> Vec { out } +/// The threads `python_profile.py` listed in `threads.json` (yappi runs), busiest first. +fn threads(dir: &Path) -> Vec { + let Ok(text) = std::fs::read_to_string(dir.join("threads.json")) else { return Vec::new() }; + let mut threads: Vec = serde_json::from_str(&text).unwrap_or_default(); + threads.retain(|t| dir.join(format!("thread-{}.pstats", t.id)).is_file()); + threads.sort_by(|a, b| b.total.total_cmp(&a.total).then(a.id.cmp(&b.id))); + threads +} + fn nothing_recorded(what: &str) -> IdeError { let mut msg = format!("The run produced no profile ({what})."); if cfg!(target_os = "macos") && what.contains("py-spy") { @@ -244,15 +266,17 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult { } Ok(profile) } - ProfileSpec::PythonRun { profiler, dir, root } => { - let bytes = std::fs::read(Path::new(dir.as_ref()).join("profile.pstats")).map_err(|e| match e.kind() { + ProfileSpec::PythonRun { profiler, dir, root, thread } => { + let file = thread.map_or_else(|| "profile.pstats".to_owned(), |t| format!("thread-{t}.pstats")); + let bytes = std::fs::read(Path::new(dir.as_ref()).join(file)).map_err(|e| match e.kind() { // A run that was killed (a second Stop) or left through `os._exit`. std::io::ErrorKind::NotFound => nothing_recorded(&format!("{profiler} wrote no profile")), _ => IdeError::invalid(format!("Cannot read the {profiler} profile: {e}")), })?; let bases: [&Path; 2] = [root.as_ref(), dir.as_ref()]; - let profile = pstats::read(&bytes, &bases, profiler) + let mut profile = pstats::read(&bytes, &bases, profiler) .map_err(|e| IdeError::invalid(format!("Cannot read the {profiler} profile: {e}")))?; + profile.threads = threads(dir.as_ref()); if profile.methods.is_empty() { return Err(nothing_recorded(&format!("{profiler} recorded no calls"))); } diff --git a/crates/ide-profiler/src/plan.rs b/crates/ide-profiler/src/plan.rs index b6b6e01465..6235cdee34 100644 --- a/crates/ide-profiler/src/plan.rs +++ b/crates/ide-profiler/src/plan.rs @@ -4,8 +4,10 @@ use crate::{ProfileMode, ProfilePrepared, ProfileSpec, ProfilerInstall}; use ide_run::RunConfig; use ide_run::wrap::{self, program_name}; use std::path::{Path, PathBuf}; +use std::process::Command; const ASYNC_PROFILER_HOME: &str = "https://github.com/async-profiler/async-profiler/releases"; +const YAPPI_HOME: &str = "https://github.com/sumerc/yappi"; const MEMRAY_HOME: &str = "https://github.com/bloomberg/memray"; const PY_SPY_HOME: &str = "https://github.com/benfred/py-spy"; /// Starts `-c` code that imports memray without the working directory on `sys.path`: a project's @@ -105,25 +107,23 @@ fn python( let beside = Path::new(&py.interpreter[0]).parent().map(|d| d.join(if cfg!(windows) { "py-spy.exe" } else { "py-spy" })); let found = beside.filter(|p| p.is_file()).or_else(|| wrap::find_tool("py-spy", config, dir, root)); + // yappi imported by the interpreter itself: it profiles every thread and coroutine. + let yappi = match profiler { + "cprofile" | "py-spy" => false, + _ => has_yappi(config, dir, &py), + }; + if yappi { + return python_launcher(config, dir, out, py, "yappi", "yappi"); + } + if profiler == "yappi" { + return missing_python_tool("yappi", YAPPI_HOME, dir, &py); + } let py_spy = match (profiler, found) { ("cprofile", _) => return cprofile(config, dir, out, py), ("py-spy", Some(found)) => found, // On macOS py-spy samples only as root, which a run from the IDE isn't. (_, Some(found)) if !cfg!(target_os = "macos") => found, - ("py-spy", None) => { - let install = (py.manager.is_none()).then(|| { - let mut argv = py.interpreter.clone(); - argv.extend([s("-m"), s("pip"), s("install"), s("py-spy")]); - let (command, args) = argv.split_first().map(|(c, a)| (c.clone(), a.to_vec())).unwrap_or_default(); - ProfilerInstall { command, args, cwd: Some(dir.to_path_buf().into()) } - }); - return ProfilePrepared::MissingTool { - tool: s("py-spy"), - message: s("Profiling Python with py-spy needs py-spy."), - install, - homepage: Some(PY_SPY_HOME.into()), - }; - } + ("py-spy", None) => return missing_python_tool("py-spy", PY_SPY_HOME, dir, &py), _ => return cprofile(config, dir, out, py), }; let mut args = vec![ @@ -150,6 +150,56 @@ fn python( ready("py-spy", launch, spec) } +/// Whether the run's interpreter (`uv run python`, a virtualenv's) can import yappi. A probe +/// that takes longer than `PROBE_SECS` (a project manager syncing its environment) counts as no. +fn has_yappi(config: &RunConfig, dir: &Path, py: &wrap::PythonCommand) -> bool { + const PROBE_SECS: u64 = 20; + let Some((command, args)) = py.interpreter.split_first() else { return false }; + let Ok(mut child) = ide_core::process::prepare(&mut Command::new(command)) + .args(args) + .args(["-c", "import yappi"]) + .current_dir(dir) + .envs(&config.env) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + else { + return false; + }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(PROBE_SECS); + loop { + match child.try_wait() { + Ok(Some(status)) => return status.success(), + Ok(None) if std::time::Instant::now() < deadline => { + std::thread::sleep(std::time::Duration::from_millis(20)) + } + _ => { + let _ = child.kill(); + let _ = child.wait(); + return false; + } + } + } +} + +/// Profiling needs `tool`, which `pip install` puts into the interpreter's environment; +/// where a project manager (uv, poetry) owns the environment the user adds it there. +fn missing_python_tool(tool: &str, homepage: &str, dir: &Path, py: &wrap::PythonCommand) -> ProfilePrepared { + let install = py.manager.is_none().then(|| { + let mut argv = py.interpreter.clone(); + argv.extend([s("-m"), s("pip"), s("install"), s(tool)]); + let (command, args) = argv.split_first().map(|(c, a)| (c.clone(), a.to_vec())).unwrap_or_default(); + ProfilerInstall { command, args, cwd: Some(dir.to_path_buf().into()) } + }); + ProfilePrepared::MissingTool { + tool: s(tool), + message: format!("Profiling Python with {tool} needs {tool}."), + install, + homepage: Some(homepage.into()), + } +} + /// Runs the program with memray tracking its allocations, through the same launcher as cProfile. fn memray(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -> ProfilePrepared { if cfg!(windows) { @@ -234,8 +284,12 @@ fn python_launcher( } argv.extend(py.target); (launch.command, launch.args) = argv.split_first().map(|(c, a)| (c.clone(), a.to_vec())).unwrap_or_default(); - let spec = - ProfileSpec::PythonRun { profiler: s(profiler), dir: out.to_path_buf().into(), root: dir.to_path_buf().into() }; + let spec = ProfileSpec::PythonRun { + profiler: s(profiler), + dir: out.to_path_buf().into(), + root: dir.to_path_buf().into(), + thread: None, + }; ready(profiler, launch, spec) } @@ -480,7 +534,7 @@ mod tests { ); assert_eq!(std::fs::read_to_string(dir.path().join("python_profile.py")).unwrap(), PYTHON_LAUNCHER); let (out, root) = (dir.path().to_path_buf().into(), dir.path().to_path_buf().into()); - assert_eq!(spec, ProfileSpec::PythonRun { profiler: "cProfile".into(), dir: out, root }); + assert_eq!(spec, ProfileSpec::PythonRun { profiler: "cProfile".into(), dir: out, root, thread: None }); assert_eq!(launch.extras.stop_command.is_some(), cfg!(windows)); // py-spy installed: Automatic takes it except on macOS, where it would need root. @@ -491,6 +545,27 @@ mod tests { assert_eq!(python_plan(&c, dir.path(), "py-spy").0, "py-spy"); } + #[test] + fn choosing_yappi_without_it_offers_to_install_it() { + let dir = tempfile::tempdir().unwrap(); + let python = dir.path().join("python").to_string_lossy().into_owned(); + std::fs::write(&python, "").unwrap(); + let c = cfg("python", &python, &["main.py"]); + match prepare(dir.path(), &c, dir.path(), ProfileMode::Cpu, "yappi") { + ProfilePrepared::MissingTool { tool, install: Some(i), .. } => { + assert_eq!(tool, "yappi"); + assert_eq!((i.command, i.args), (python, v(&["-m", "pip", "install", "yappi"]))); + } + other => panic!("{other:?}"), + } + // Under uv the project's manager owns the environment: no pip command. + let uv = cfg("python", "uv", &["run", "python", "main.py"]); + assert!(matches!( + prepare(dir.path(), &uv, dir.path(), ProfileMode::Cpu, "yappi"), + ProfilePrepared::MissingTool { install: None, .. } + )); + } + #[test] fn cprofile_keeps_the_configurations_interpreter() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-profiler/src/python_profile.py b/crates/ide-profiler/src/python_profile.py index da01a442b0..0e88ad09fe 100644 --- a/crates/ide-profiler/src/python_profile.py +++ b/crates/ide-profiler/src/python_profile.py @@ -1,10 +1,12 @@ """Runs a script, module (-m) or code (-c) under a profiler for the IDE's Profile action. -Usage: python python_profile.py (cprofile | memray) [--stop ] (