//! Allocation profiling of real runs with memray (macOS and Linux). `MEMRAY_PYTHON` names an //! interpreter that has memray, as CI sets it; without it `python3` is tried, and the tests //! return early when that has no memray. #![cfg(unix)] 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, PathBuf}; use std::process::{Command, ExitStatus, Stdio}; const MB: f64 = 1024.0 * 1024.0; fn fixture() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/python-memory").canonicalize().unwrap() } fn python() -> Option { let named = std::env::var("MEMRAY_PYTHON").ok(); let python = named.clone().unwrap_or_else(|| "python3".into()); let ok = Command::new(&python).args(["-c", "import memray"]).output().is_ok_and(|o| o.status.success()); assert!(ok || named.is_none(), "MEMRAY_PYTHON={python} cannot import memray"); ok.then_some(python) } /// The Profile Allocations launch of `args` in `cwd`. fn plan(python: &str, args: &[&str], cwd: &Path, out: &Path) -> (Command, ProfileSpec) { let config = RunConfig { id: "mem".into(), name: "allocate".into(), kind: "python".into(), command: python.into(), args: args.iter().map(|a| a.to_string()).collect(), cwd: Some(cwd.into()), env: BTreeMap::new(), detected: false, is_test: false, debug_adapter: None, allow_parallel: false, extras: Default::default(), }; match prepare(cwd, &config, out, ProfileMode::Allocations, "auto") { ProfilePrepared::Ready { profiler, launch, spec } => { assert_eq!(profiler, "memray"); let mut command = Command::new(&launch.command); command.args(&launch.args).current_dir(cwd).stdout(Stdio::piped()); (command, spec) } other => panic!("{other:?}"), } } fn run(python: &str, args: &[&str], cwd: &Path) -> (ExitStatus, ide_core::IdeResult) { let out = tempfile::tempdir().unwrap(); let (mut command, spec) = plan(python, args, cwd, out.path()); let status = command.output().unwrap().status; (status, collect(&spec)) } /// Bytes allocated by `name` and what it called. fn total(p: &Profile, name: &str) -> f64 { let method = p.methods.iter().find(|m| p.frames[m.frame as usize].name == name); method.unwrap_or_else(|| panic!("no {name}")).total } fn assert_no_launcher(p: &Profile) { for f in &p.frames { let file = f.file.as_ref().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); assert!(!file.ends_with("python_profile.py"), "{}", f.name); } } #[test] fn a_script_reports_what_each_function_held_at_the_peak() { let Some(python) = python() else { return }; let (status, profile) = run(&python, &["allocate.py"], &fixture()); assert!(status.success()); let p = profile.unwrap(); assert_eq!((p.profiler.as_str(), p.unit.as_str(), p.mode), ("memray", "bytes", ProfileMode::Allocations)); assert_no_launcher(&p); // 25,000 KiB blocks, 5,000 of them from the worker thread. assert!(total(&p, "blocks") > 24.0 * MB && total(&p, "blocks") < 40.0 * MB, "{}", total(&p, "blocks")); assert!(total(&p, "worker") > 4.0 * MB && total(&p, "main") > 19.0 * MB); let blocks = p.frames.iter().find(|f| f.name == "blocks").unwrap(); assert_eq!(blocks.file.as_deref(), Some(fixture().join("allocate.py").as_path())); assert_eq!(p.frames.iter().filter(|f| f.name == "blocks").count(), 1); } #[test] fn modules_and_c_code_keep_their_exit_code() { let Some(python) = python() else { return }; let (status, profile) = run(&python, &["-m", "allocate"], &fixture()); assert!(status.success()); let p = profile.unwrap(); assert!(total(&p, "blocks") > 24.0 * MB); assert_no_launcher(&p); let code = "import sys\ndef work(): return bytearray(8_000_000)\nkept = work()\nsys.exit(3)"; let (status, profile) = run(&python, &["-c", code], &fixture()); assert_eq!(status.code(), Some(3)); let p = profile.unwrap(); assert!(total(&p, "work") > 7.0 * MB); assert!(p.frames.iter().find(|f| f.name == "work").unwrap().file.is_none()); } #[test] fn a_failing_run_and_non_ascii_paths_are_profiled() { let Some(python) = python() else { return }; let project = tempfile::tempdir().unwrap(); let dir = project.path().canonicalize().unwrap().join("数据, 项目 dir"); std::fs::create_dir(&dir).unwrap(); std::fs::write( dir.join("分配.py"), "def 成长():\n return bytearray(8_000_000)\nkept = 成长()\nraise ValueError\n", ) .unwrap(); let (status, profile) = run(&python, &["分配.py"], &dir); assert_eq!(status.code(), Some(1)); let p = profile.unwrap(); assert!(total(&p, "成长") > 7.0 * MB); let frame = p.frames.iter().find(|f| f.name == "成长").unwrap(); assert_eq!(frame.file.as_deref(), Some(dir.join("分配.py").as_path())); } #[test] fn a_forked_child_does_not_break_the_capture() { let Some(python) = python() else { return }; let code = "import os\ndef work(): return bytearray(8_000_000)\nkept = work()\nif os.fork() == 0:\n work()\nelse:\n os.wait()"; let (status, profile) = run(&python, &["-c", code], &fixture()); assert!(status.success()); assert!(total(&profile.unwrap(), "work") > 7.0 * MB); } #[test] fn a_stopped_run_still_has_its_allocations() { let Some(python) = python() else { return }; let out = tempfile::tempdir().unwrap(); let (mut command, spec) = plan(&python, &["allocate.py", "--wait"], &fixture(), out.path()); let mut child = command.stderr(Stdio::null()).spawn().unwrap(); let mut line = String::new(); BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap(); assert_eq!(line.trim(), "done"); // What the first Stop sends. assert!(Command::new("kill").args(["-INT", &child.id().to_string()]).status().unwrap().success()); child.wait().unwrap(); assert!(total(&collect(&spec).unwrap(), "blocks") > 24.0 * MB); } #[test] fn small_objects_belong_to_the_function_still_holding_them() { let Some(python) = python() else { return }; let code = "def temp():\n junk = [bytes(200) for _ in range(100_000)]\n return junk[::100]\ndef keeper():\n return [bytes(200) for _ in range(150_000)]\na = temp()\nb = keeper()"; let (_, profile) = run(&python, &["-c", code], &fixture()); let p = profile.unwrap(); assert!(total(&p, "keeper") > 30.0 * MB && total(&p, "temp") < MB, "{} {}", total(&p, "keeper"), total(&p, "temp")); } #[test] fn a_tiny_program_still_gets_a_snapshot() { let Some(python) = python() else { return }; let (status, profile) = run(&python, &["-c", "print('hi')"], &fixture()); assert!(status.success()); assert!(profile.unwrap().total < MB); } #[test] fn the_projects_own_modules_do_not_run_while_the_report_is_read() { let Some(python) = python() else { return }; let project = tempfile::tempdir().unwrap(); // Shadows the standard library's `csv` for anything started with the project on `sys.path`. std::fs::write(project.path().join("csv.py"), "open('ran', 'w')\nraise SystemExit(9)\n").unwrap(); let (status, profile) = run(&python, &["-c", "kept = bytearray(8_000_000)"], project.path()); assert!(status.success()); assert!(profile.unwrap().total > 7.0 * MB); assert!(!project.path().join("ran").exists()); } #[test] fn a_run_that_left_no_capture_says_so() { let Some(python) = python() else { return }; // The program never started: the launcher did not run. let out = tempfile::tempdir().unwrap(); let (_, spec) = plan(&python, &["allocate.py"], &fixture(), out.path()); let error = collect(&spec).unwrap_err(); assert!(error.message.contains("memray wrote no data"), "{}", error.message); // A capture memray cannot read. std::fs::write(out.path().join("memray.bin"), "not a capture").unwrap(); let error = collect(&spec).unwrap_err(); assert!(error.message.contains("memray transform failed"), "{}", error.message); }