//! Profiling Python under yappi with real interpreters: threads, thread pools, asyncio, exit //! codes, Stop, virtualenvs and `uv`. Tests that need yappi use `YAPPI_PYTHON` (an interpreter //! that imports it) or `python3` when that can; without one they return early. CI installs yappi. use ide_profiler::{Profile, ProfileMode, ProfilePrepared, ProfileSpec, collect, prepare}; use ide_run::RunConfig; use std::collections::BTreeMap; use std::io::{BufRead, BufReader}; use std::path::Path; use std::process::{Command, Stdio}; fn runs(python: &str, code: &str) -> bool { Command::new(python).args(["-c", code]).output().is_ok_and(|o| o.status.success()) } /// An interpreter that imports yappi. fn yappi_python() -> Option { let name = std::env::var("YAPPI_PYTHON").unwrap_or_else(|_| (if cfg!(windows) { "python" } else { "python3" }).into()); runs(&name, "import yappi").then_some(name) } fn config(python: &str, cwd: &Path, args: &[&str]) -> RunConfig { RunConfig { id: "y".into(), name: "yappi_run".into(), kind: "python".into(), command: python.into(), args: args.iter().map(|a| a.to_string()).collect(), cwd: Some(cwd.to_path_buf().into()), env: BTreeMap::new(), detected: false, is_test: false, debug_adapter: None, allow_parallel: false, extras: Default::default(), } } fn prepared(c: &RunConfig, cwd: &Path, out: &Path, setting: &str) -> ProfilePrepared { prepare(cwd, c, out, ProfileMode::Cpu, setting) } /// The yappi launch for `args` and where its profile goes. fn plan(python: &str, cwd: &Path, args: &[&str], out: &Path) -> (Command, ProfileSpec) { let ProfilePrepared::Ready { profiler, launch, spec } = prepared(&config(python, cwd, args), cwd, out, "auto") else { panic!("not ready"); }; assert_eq!(profiler, "yappi"); let mut cmd = Command::new(&launch.command); cmd.args(&launch.args).current_dir(cwd).stdout(Stdio::piped()); (cmd, spec) } fn thread_spec(spec: &ProfileSpec, id: u32) -> ProfileSpec { let ProfileSpec::PythonRun { profiler, dir, root, .. } = spec else { panic!("not a Python run") }; ProfileSpec::PythonRun { profiler: profiler.clone(), dir: dir.clone(), root: root.clone(), thread: Some(id) } } fn method<'a>(p: &'a Profile, name: &str) -> Option<&'a ide_profiler::MethodStat> { p.methods.iter().find(|m| p.frames[m.frame as usize].name.contains(name)) } fn finish(mut child: std::process::Child) -> std::process::ExitStatus { for _ in 0..600 { if let Some(status) = child.try_wait().unwrap() { return status; } std::thread::sleep(std::time::Duration::from_millis(100)); } child.kill().unwrap(); panic!("the profiled run did not end"); } fn write(dir: &Path, name: &str, text: &str) { std::fs::write(dir.join(name), text).unwrap(); } const THREADS: &str = "import threading, time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef in_thread():\n time.sleep(0.05)\n\ndef in_pool(i):\n time.sleep(0.02)\n\ndef main_work():\n sum(range(1000))\n\nt = threading.Thread(target=in_thread, name='worker')\nt.start()\nwith ThreadPoolExecutor(2) as pool:\n list(pool.map(in_pool, range(4)))\nt.join()\nmain_work()\n"; #[test] fn threads_and_thread_pools_are_listed_and_selectable() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); write(project.path(), "threads.py", THREADS); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["threads.py"], out.path()); assert!(finish(cmd.spawn().unwrap()).success()); let all = collect(&spec).unwrap(); assert_eq!(all.profiler, "yappi"); let names: Vec<&str> = all.threads.iter().map(|t| t.name.as_str()).collect(); for expected in ["MainThread", "worker", "ThreadPoolExecutor-0_0"] { assert!(names.contains(&expected), "{names:?}"); } // Merged: every thread's functions, with call counts. assert_eq!(method(&all, "in_pool").unwrap().calls, Some(4.0)); assert!(method(&all, "in_thread").is_some() && method(&all, "main_work").is_some()); // Busiest first. assert!(all.threads.windows(2).all(|w| w[0].total >= w[1].total)); // One thread shows only its own functions. let worker = all.threads.iter().find(|t| t.name == "worker").unwrap(); let w = collect(&thread_spec(&spec, worker.id)).unwrap(); assert!(method(&w, "in_thread").is_some()); assert!(method(&w, "in_pool").is_none() && method(&w, "main_work").is_none()); assert_eq!(w.threads, all.threads, "the selector lists every thread whichever is shown"); let main = all.threads.iter().find(|t| t.name == "MainThread").unwrap(); let m = collect(&thread_spec(&spec, main.id)).unwrap(); assert!(method(&m, "main_work").is_some() && method(&m, "in_thread").is_none()); } #[test] fn a_coroutines_time_includes_its_awaits() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); write( project.path(), "aio.py", "import asyncio\n\nasync def nap():\n await asyncio.sleep(0.1)\n\nasync def main():\n await asyncio.gather(nap(), nap())\n\nasyncio.run(main())\n", ); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["aio.py"], out.path()); assert!(finish(cmd.spawn().unwrap()).success()); let p = collect(&spec).unwrap(); let nap = method(&p, "nap").unwrap(); assert_eq!(nap.calls, Some(2.0)); // Two naps of 0.1 s, unit ms: cProfile would charge only the time between awaits. assert!(nap.total >= 180.0, "{}", nap.total); } #[test] fn exit_codes_c_code_and_modules_are_kept() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan( &python, project.path(), &["-c", "import sys\ndef work(): return sum(range(9))\nwork()\nsys.exit(3)"], out.path(), ); assert_eq!(finish(cmd.spawn().unwrap()).code(), Some(3)); assert_eq!(method(&collect(&spec).unwrap(), "work (:2)").unwrap().calls, Some(1.0)); write(project.path(), "app.py", "import sys\nprint(__name__, sys.argv[1:])\nsys.exit(4)\n"); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["-m", "app", "x", "--y"], out.path()); let mut child = cmd.spawn().unwrap(); let mut printed = String::new(); std::io::Read::read_to_string(&mut child.stdout.take().unwrap(), &mut printed).unwrap(); assert_eq!(printed.trim(), "__main__ ['x', '--y']"); assert_eq!(finish(child).code(), Some(4)); collect(&spec).unwrap(); } #[test] fn an_uncaught_exception_still_leaves_a_profile() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["-c", "def boom():\n raise ValueError\nboom()"], out.path()); cmd.stderr(Stdio::null()); assert_eq!(finish(cmd.spawn().unwrap()).code(), Some(1)); assert!(method(&collect(&spec).unwrap(), "boom").is_some()); } #[test] fn paths_with_spaces_work() { let Some(python) = yappi_python() else { return }; let root = tempfile::tempdir().unwrap(); let project = root.path().join("my project"); let out = root.path().join("out dir"); std::fs::create_dir_all(&project).unwrap(); std::fs::create_dir_all(&out).unwrap(); write(&project, "spaced script.py", "def spaced_fn():\n return 1\nspaced_fn()\n"); let (mut cmd, spec) = plan(&python, &project, &["spaced script.py"], &out); assert!(finish(cmd.spawn().unwrap()).success()); let p = collect(&spec).unwrap(); let f = method(&p, "spaced_fn").unwrap(); assert_eq!(p.frames[f.frame as usize].file.as_deref(), Some(project.join("spaced script.py").as_path())); } #[test] fn recursion_counts_total_and_primitive_calls_as_cprofile_does() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); write(project.path(), "rec.py", "def rec(n):\n return 0 if n == 0 else 1 + rec(n - 1)\nrec(50)\n"); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["rec.py"], out.path()); assert!(finish(cmd.spawn().unwrap()).success()); let p = collect(&spec).unwrap(); let rec = method(&p, "rec").unwrap(); assert_eq!((rec.calls, rec.primitive_calls), (Some(51.0), Some(1.0))); } #[test] fn builtins_are_named_like_cprofile_names_them() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); // A project file named like a built-in module must not be taken for its source. write(project.path(), "time", ""); write(project.path(), "builtins", ""); write(project.path(), "b.py", "import time\ntime.sleep(0.01)\nsorted([1])\nprint(len([]))\n"); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["b.py"], out.path()); cmd.stdout(Stdio::null()); assert!(finish(cmd.spawn().unwrap()).success()); let p = collect(&spec).unwrap(); for name in ["", ""] { let m = method(&p, name).unwrap_or_else(|| panic!("no {name}")); let frame = &p.frames[m.frame as usize]; assert_eq!((frame.name.as_str(), frame.file.is_none()), (name, true), "{frame:?}"); } } /// The interpreter joins non-daemon threads after the main thread returns; their work counts. #[test] fn work_of_threads_that_outlive_the_main_thread_is_profiled() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); write( project.path(), "late.py", "import threading, time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef late():\n time.sleep(0.3)\n sum(range(100))\n\nthreading.Thread(target=late, name='late').start()\nThreadPoolExecutor(1).submit(late)\n", ); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["late.py"], out.path()); assert!(finish(cmd.spawn().unwrap()).success()); let p = collect(&spec).unwrap(); // One call from the thread, one from the pool's worker. assert_eq!(method(&p, "").unwrap().calls, Some(2.0)); let late = p.threads.iter().find(|t| t.name == "late").unwrap(); assert!(late.total >= 0.25, "{late:?}"); } #[test] fn many_short_threads_list_only_the_busiest() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); write( project.path(), "many.py", "import threading, time\n\ndef short():\n pass\n\ndef busy():\n time.sleep(0.2)\n\nb = threading.Thread(target=busy, name='busy')\nb.start()\nfor _ in range(300):\n t = threading.Thread(target=short)\n t.start()\n t.join()\nb.join()\n", ); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["many.py"], out.path()); assert!(finish(cmd.spawn().unwrap()).success()); let p = collect(&spec).unwrap(); assert_eq!(p.threads.len(), 64); assert!(p.threads.iter().any(|t| t.name == "busy")); assert_eq!(method(&p, "short").unwrap().calls, Some(300.0), "the merged profile has every thread"); let files = std::fs::read_dir(out.path()) .unwrap() .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().starts_with("thread-")) .count(); assert_eq!(files, 64); } /// Child processes (multiprocessing) run as they would without the profiler; the exit code is kept. #[test] fn a_multiprocessing_pool_and_a_subprocess_exit_cleanly() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); write( project.path(), "mp.py", "import multiprocessing as mp, subprocess, sys\n\ndef square(x):\n return x * x\n\nif __name__ == '__main__':\n with mp.get_context('spawn').Pool(2) as pool:\n print(pool.map(square, [1, 2, 3]))\n sys.exit(subprocess.call([sys.executable, '-c', 'raise SystemExit(5)']))\n", ); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["mp.py"], out.path()); cmd.env("PYTHON_GIL", "1"); let mut child = cmd.spawn().unwrap(); let mut printed = String::new(); std::io::Read::read_to_string(&mut child.stdout.take().unwrap(), &mut printed).unwrap(); assert_eq!(printed.trim(), "[1, 4, 9]"); assert_eq!(finish(child).code(), Some(5)); collect(&spec).unwrap(); } #[test] fn a_missing_or_damaged_thread_list_leaves_the_merged_profile() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); write(project.path(), "t.py", THREADS); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["t.py"], out.path()); assert!(finish(cmd.spawn().unwrap()).success()); std::fs::write(out.path().join("threads.json"), "{ not json").unwrap(); assert!(collect(&spec).unwrap().threads.is_empty()); std::fs::remove_file(out.path().join("threads.json")).unwrap(); let p = collect(&spec).unwrap(); assert!(p.threads.is_empty() && method(&p, "in_pool").is_some()); // A thread whose file is gone is not listed; asking for it reports the missing file. std::fs::write( out.path().join("threads.json"), r#"[{"id":0,"name":"MainThread","total":1.0},{"id":99,"name":"gone","total":2.0}]"#, ) .unwrap(); assert_eq!(collect(&spec).unwrap().threads.iter().map(|t| t.id).collect::>(), [0]); assert!(collect(&thread_spec(&spec, 99)).is_err()); } /// The first Stop (SIGINT) writes the snapshot, threads included. #[cfg(unix)] #[test] fn a_stopped_run_still_writes_its_profile_and_threads() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); write( project.path(), "loop.py", "import threading, time\ndef spin():\n while True:\n sum(range(1000))\nthreading.Thread(target=spin, daemon=True, name='spinner').start()\nprint('started', flush=True)\nwhile True:\n time.sleep(0.05)\n", ); let out = tempfile::tempdir().unwrap(); let (mut cmd, spec) = plan(&python, project.path(), &["loop.py"], out.path()); let mut child = cmd.spawn().unwrap(); let mut line = String::new(); BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap(); assert_eq!(line.trim(), "started"); std::thread::sleep(std::time::Duration::from_millis(300)); assert!(Command::new("kill").args(["-INT", &child.id().to_string()]).status().unwrap().success()); finish(child); let p = collect(&spec).unwrap(); let spinner = p.threads.iter().find(|t| t.name == "spinner").unwrap_or_else(|| panic!("{:?}", p.threads)); // `spin` itself never returned; what it called did. assert!(method(&collect(&thread_spec(&spec, spinner.id)).unwrap(), "sum").is_some()); } /// What Stop does on Windows: the stop command opens the pipe (a FIFO elsewhere). #[test] fn the_stop_pipe_ends_the_run_and_keeps_its_profile() { let Some(python) = yappi_python() else { return }; let project = tempfile::tempdir().unwrap(); let out = tempfile::tempdir().unwrap(); let code = "print('started', flush=True)\nwhile True:\n sum(range(1000))"; let ProfilePrepared::Ready { mut launch, spec, .. } = prepared(&config(&python, project.path(), &["-c", code]), project.path(), out.path(), "yappi") else { panic!("not ready"); }; let fifo = out.path().join("stop"); if launch.extras.stop_command.is_none() { let at = launch.args.iter().position(|a| a == "-c").unwrap(); launch.args.splice(at..at, ["--stop".to_owned(), fifo.to_string_lossy().into_owned()]); } let mut cmd = Command::new(&launch.command); cmd.args(&launch.args).current_dir(project.path()).stdout(Stdio::piped()); let mut child = cmd.spawn().unwrap(); let mut line = String::new(); BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap(); assert_eq!(line.trim(), "started"); std::thread::sleep(std::time::Duration::from_millis(300)); match &launch.extras.stop_command { #[cfg(windows)] Some(stop) => { use std::os::windows::process::CommandExt; assert!(Command::new("cmd").arg("/C").raw_arg(stop).status().unwrap().success()); } _ => drop(std::fs::OpenOptions::new().write(true).open(&fifo).unwrap()), } assert!(!finish(child).success()); let p = collect(&spec).unwrap(); assert!(method(&p, "sum").is_some()); // The watcher that waited for Stop stays out of the profile. assert!(method(&p, "watch").is_none() && method(&p, "stop_waiter").is_none()); // A run that was stopped is one thread, not two with the watcher. assert_eq!(p.threads.len(), 1, "{:?}", p.threads); } fn venv(base: &str, dir: &Path) -> String { assert!(Command::new(base).args(["-m", "venv"]).arg(dir).status().unwrap().success()); let bin = dir.join(if cfg!(windows) { "Scripts" } else { "bin" }); bin.join(if cfg!(windows) { "python.exe" } else { "python" }).to_string_lossy().into_owned() } /// Automatic follows what the run's own interpreter imports; the setting overrides it. #[test] fn a_virtualenv_with_yappi_is_profiled_with_it_and_one_without_falls_back() { let Some(base) = yappi_python() else { return }; let root = tempfile::tempdir().unwrap(); let project = root.path().join("p"); std::fs::create_dir_all(&project).unwrap(); let out = tempfile::tempdir().unwrap(); let plain = venv(&base, &root.path().join("plain")); let profiler_of = |py: &str, setting: &str| match prepared(&config(py, &project, &["app.py"]), &project, out.path(), setting) { ProfilePrepared::Ready { profiler, .. } => profiler, ProfilePrepared::MissingTool { tool, install, .. } => { format!("missing {tool}: {}", install.map(|i| i.args.join(" ")).unwrap_or_default()) } other => panic!("{other:?}"), }; // A fresh virtualenv does not see the base interpreter's yappi. assert_eq!(profiler_of(&plain, "auto"), "cProfile"); assert_eq!(profiler_of(&plain, "yappi"), "missing yappi: -m pip install yappi"); assert!(Command::new(&plain).args(["-m", "pip", "install", "-q", "yappi"]).status().unwrap().success()); assert_eq!(profiler_of(&plain, "auto"), "yappi"); assert_eq!(profiler_of(&plain, "cprofile"), "cProfile"); assert!(profiler_of(&plain, "py-spy").starts_with("missing py-spy")); } #[test] fn uv_runs_are_probed_through_uv() { if !Command::new("uv").arg("--version").output().is_ok_and(|o| o.status.success()) { return; } let project = tempfile::tempdir().unwrap(); write(project.path(), "app.py", "def uv_fn():\n return 1\nuv_fn()\n"); let out = tempfile::tempdir().unwrap(); let c = config("uv", project.path(), &["run", "--no-project", "--with", "yappi", "python", "app.py"]); let ProfilePrepared::Ready { profiler, launch, spec } = prepared(&c, project.path(), out.path(), "auto") else { panic!("not ready"); }; assert_eq!(profiler, "yappi"); let mut cmd = Command::new(&launch.command); assert!(cmd.args(&launch.args).current_dir(project.path()).status().unwrap().success()); assert!(method(&collect(&spec).unwrap(), "uv_fn").is_some()); }