Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

Merge #116: scan --duration for every language (resolved against #85, #92, #118, #126)

EL4CTEO46f472e3601c
diff --cc src/php.rs
index 73a3271,13a4500..7f2a493
--- a/src/php.rs
+++ b/src/php.rs
@@@ -372,7 -395,7 +395,7 @@@ mod tests
let app = "<?php\nnamespace Text {\n function width(string $s): int\n {\n return strlen($s);\n }\n}\n\nnamespace {\n echo \\Text\\width('h\u{e9}llo'), \"\\n\";\n}\n";
fs::write(dir.join("app.php"), app).unwrap();
let mut ctx = Ctx::open(&dir).unwrap();
-- let found = profile(&ctx, "php", &["app.php".into()]).unwrap();
++ let found = profile(&ctx, "php", &["app.php".into()], None).unwrap();
assert!(found.functions.iter().any(|f| f.name == "width" && f.blockers.is_empty()), "{:?}", found.functions);
let hs = Hotspot {
id: "Text.width".into(),
diff --cc src/pipeline.rs
index c5f6ce7,e630026..e4231d0
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@@ -36,17 -36,17 +36,17 @@@ pub fn scan(root: &Path, command: Vec<S
let lang = crate::cfamily::refine(Lang::detect(&command[0])?, &command[1..]);
let lang = crate::kotlin::refine(lang, &command[0], &ctx.root);
if let Some(d) = duration {
- ensure!(lang == Lang::CSharp, "--duration works for C# apps only so far");
+ ensure!(lang.stops_after_duration(), "--duration stops R apps with SIGINT, which Windows doesn't have");
ensure!(d.is_finite() && d > 0.0, "--duration takes a number of seconds, e.g. --duration 30");
}
- let exe = lang.resolve(&command[0], &ctx.root)?;
+ let exe = lang.resolve(&command[0], &command[1..], &ctx.root)?;
+ ctx.state.command = command.clone();
ui::step(format!("profiling {}", ui::bold(command.join(" "))));
- let profile = match duration {
- Some(d) => crate::csharp::profile(&ctx, &exe, &command[1..], Some(d))?,
- None => lang.profile(&ctx, &exe, &command[1..])?,
- };
+ if let Some(d) = duration.filter(|_| lang != Lang::CSharp) {
+ ui::line(format!(" stopping it after {d}s"));
+ }
+ let profile = lang.profile(&ctx, &exe, &command[1..], duration)?;
let hotspots = hotspot::rank(profile.functions, profile.wall);
- ctx.state.command = command.clone();
ctx.state.lang = lang;
ctx.state.runtime = Some(exe);
ctx.state.base = profile.base;
diff --cc src/python.rs
index f8e3542,410a926..9d53d88
--- a/src/python.rs
+++ b/src/python.rs
@@@ -128,41 -82,19 +129,53 @@@ pub fn resolve(program: &str, args: &[S
Ok(exe)
}
+/// Drop a leading Windows `py` launcher version selector when `ctx.state.command` started with `py`.
+/// Shared by `profile`, `record` (via `helper`), and `bench` so the resolved `python.exe` and
+/// `runner.py` never receive launcher-only flags like `-3`, `-3.13`, or `-V:3.13`.
+fn strip_launcher_selector<'a>(ctx: &Ctx, args: &'a [String]) -> &'a [String] {
+ if cfg!(windows) {
+ let program = ctx.state.command.first().map(String::as_str).unwrap_or_default();
+ split_py_launcher_selector(program, args).1
+ } else {
+ args
+ }
+}
+
+/// What bench runs for Python: the resolved interpreter with any Windows `py` launcher version
+/// selector stripped.
+pub fn bench_command(ctx: &Ctx, python: &str) -> Result<(String, Vec<String>)> {
+ let args = strip_launcher_selector(ctx, ctx.state.command.get(1..).unwrap_or_default());
+ Ok((python.to_string(), args.to_vec()))
+}
+
+fn helper_command(ctx: &Ctx, python: &str, runner: &Path, mode: &str, job_path: &Path, app_args: &[String]) -> Command {
+ let app_args = strip_launcher_selector(ctx, app_args);
+ let mut cmd = Command::new(python);
+ cmd.arg(runner)
+ .arg(mode)
+ .arg(job_path)
+ .arg("--")
+ .args(app_args)
+ .current_dir(&ctx.root)
+ .env("PYTHONIOENCODING", "utf-8")
+ .env("PYTHONUTF8", "1")
+ .stdin(Stdio::null());
+ cmd
+}
+
fn helper(ctx: &Ctx, python: &str, mode: &str, job: Value, app_args: &[String]) -> Result<Output> {
+ helper_for(ctx, python, mode, job, app_args, None)
+ }
+
+ /// helper, stopping the run from outside after `limit` (the app may ignore the runner's Ctrl+C).
+ fn helper_for(
+ ctx: &Ctx,
+ python: &str,
+ mode: &str,
+ job: Value,
+ app_args: &[String],
+ limit: Option<Duration>,
+ ) -> Result<Output> {
let runner = ctx.fast.join("runner.py");
fs::write(&runner, RUNNER)?;
let job_path = ctx.fast.join(format!("job-{mode}.json"));
diff --cc src/ruby.rs
index 55acaaa,4d4686b..f27cdfd
--- a/src/ruby.rs
+++ b/src/ruby.rs
@@@ -363,77 -348,28 +381,99 @@@ pub fn disable(ctx: &Ctx, port: &Port)
mod tests {
use super::*;
+ #[test]
+ fn duration_stops_an_app_that_runs_until_closed() {
+ if !Command::new("ruby").arg("-v").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no ruby on PATH, skipping");
+ return;
+ }
+ let tmp = std::env::temp_dir();
+ // macOS's temp folder is behind a symlink; the profile has the real paths
+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };
+ let dir = tmp.join(format!("fa-ruby-duration-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ // a server's shape: some work, then a long blocking wait
+ let app = "def work(n)\n (0...n).sum { |i| i * i % 7 }\nend\n\nif __FILE__ == $0\n 3.times { work(200_000) }\n sleep 3600\nend\n";
+ fs::write(dir.join("app.rb"), app).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let p = profile(&ctx, "ruby", &["app.rb".into()], Some(1.0));
+ let _ = fs::remove_dir_all(&dir);
+ let p = p.unwrap();
+ assert!(p.functions.iter().any(|f| f.name == "work" && f.ncalls == 3), "{:?}", p.functions);
+ assert!((0.9..10.0).contains(&p.wall), "{}", p.wall);
+ }
+
+ #[test]
+ fn splat_and_keyword_arguments_are_bound_like_the_method_binds_them() {
+ let Ok(ruby) = resolve("ruby", Path::new(".")) else {
+ eprintln!("no Ruby 3.3+ on PATH, skipping");
+ return;
+ };
+ let tmp = std::env::temp_dir();
+ // macOS's temp folder is behind a symlink; the profile has the real paths
+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };
+ let dir = tmp.join(format!("fa-rb-splat-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ let lib = "module Score\n SCALE = 3\n\n def self.score(word, *weights, scale: SCALE, bonus: 0)\n total = 0\n 200.times { total += word.length * (weights.sum + bonus) * scale }\n total\n end\nend\n";
+ let app = "require_relative \"score\"\n\nt = 0\n2000.times { t += Score.score(\"ab\", 1, 2) + Score.score(\"c\", bonus: 1) + Score.score(\"d\", 4, scale: 2) }\nputs t\n";
+ fs::write(dir.join("score.rb"), lib).unwrap();
+ fs::write(dir.join("app.rb"), app).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let run = || {
- let p = profile(&ctx, &ruby, &["app.rb".into()])?;
++ let p = profile(&ctx, &ruby, &["app.rb".into()], None)?;
+ let f = p.functions.iter().find(|f| f.name == "score").context("no score in the profile")?.clone();
+ let hs = Hotspot {
+ id: "score.Score.score".into(),
+ file: "score.rb".into(),
+ name: "score".into(),
+ module: Some("score".into()),
+ owner: f.owner.clone(),
+ params: f.params.clone(),
+ ..Hotspot::default()
+ };
+ let out = dir.join("cases.jsonl");
+ record(&ctx, &ruby, &["app.rb".into()], &hs, &out, 50)?;
+ let cases = fs::read_to_string(&out)?;
+ // the binder the shim uses, on its own
+ let bind = binder(hs.owner.as_deref(), &hs.params);
+ let script = format!(
+ "require \"json\"\nrequire_relative \"score\"\nbind = {bind}\nputs JSON.generate([Score.instance_exec(\"c\", bonus: 1, &bind), Score.instance_exec(\"d\", 4, 5, &bind)])\n"
+ );
+ fs::write(dir.join("bind.rb"), script)?;
+ let bound = output(Command::new(&ruby).arg("bind.rb").current_dir(&dir), "ruby")?;
+ anyhow::Ok((f, cases, bound))
+ };
+ let got = run();
+ let _ = fs::remove_dir_all(&dir);
+ let (f, cases, bound) = got.unwrap();
+ assert!(f.blockers.is_empty(), "{:?}", f.blockers);
+ let shape: Vec<_> =
+ f.params.iter().map(|p| (p.name.as_str(), p.default.as_deref(), p.kwonly, p.splat)).collect();
+ assert_eq!(
+ shape,
+ [
+ ("word", None, false, false),
+ ("weights", None, false, true),
+ ("scale", Some("SCALE"), true, false),
+ ("bonus", Some("0"), true, false)
+ ]
+ );
+ let args: std::collections::BTreeSet<String> =
+ cases.lines().map(|l| serde_json::from_str::<Value>(l).unwrap()["args"].to_string()).collect();
+ assert_eq!(
+ args.into_iter().collect::<Vec<_>>(),
+ [r#"["ab",[1,2],3,0]"#, r#"["c",[],3,1]"#, r#"["d",[4],2,0]"#],
+ "{cases}"
+ );
+ assert!(cases.lines().all(|l| !l.contains("raises")), "{cases}");
+ assert_eq!(
+ String::from_utf8_lossy(&bound.stdout).trim(),
+ r#"[["c",[],3,1],["d",[4,5],3,0]]"#,
+ "{}",
+ combined(&bound)
+ );
+ }
+
#[test]
fn ruby_defaults_become_json() {
assert_eq!(default_json("2").as_deref(), Some("2"));