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.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
scan --duration for R apps (Unix)
Mohit Mishra7fe0f9efe670
diff --git a/README.md b/README.mdindex 49bd594..259c15e 100644--- a/README.md+++ b/README.md@@ -107,7 +107,7 @@ Or wire it up by hand:| PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`); servers: `scan --duration 30` (with `pcntl`) | ✅ || C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen; servers: `scan --duration 30` | ✅ || C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install; GUIs and servers: `scan --duration 30` | ✅ |-| R 4.0+ (`Rscript app.R`) | the same C bridge, through base R's `.C()`; profiled with Rprof, no packages or R headers needed | ✅ |+| R 4.0+ (`Rscript app.R`) | the same C bridge, through base R's `.C()`; profiled with Rprof, no packages or R headers needed; servers: `scan --duration 30` | ✅ |It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions, `@staticmethod`s and `@classmethod`s that don't use `cls` (dataclasses, NamedTuples and numeric NumPy arrays count as plain data), in Java, C# and PHP static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.diff --git a/src/backend.rs b/src/backend.rsindex d935414..97dea8b 100644--- a/src/backend.rs+++ b/src/backend.rs@@ -141,7 +141,8 @@ impl Lang {/// Whether `scan --duration` can stop this language's apps.pub fn stops_after_duration(self) -> bool {- matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::Java | Lang::Kotlin | Lang::Ruby | Lang::Php | Lang::C | Lang::Cpp | Lang::CSharp)+ // R: scan interrupts it with SIGINT, which Windows doesn't have+ matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::Java | Lang::Kotlin | Lang::Ruby | Lang::Php | Lang::C | Lang::Cpp | Lang::CSharp) || (self == Lang::R && cfg!(unix))}/// `duration` (see stops_after_duration): stop the app after that many seconds.@@ -155,7 +156,7 @@ impl Lang {Lang::Php => php::profile(ctx, exe, args, duration),Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self, duration),Lang::CSharp => csharp::profile(ctx, exe, args, duration),- Lang::R => r::profile(ctx, exe, args),+ Lang::R => r::profile(ctx, exe, args, duration),Lang::Kotlin => kotlin::profile(ctx, exe, args, duration),}}diff --git a/src/main.rs b/src/main.rsindex 0068ad1..696960d 100644--- a/src/main.rs+++ b/src/main.rs@@ -67,7 +67,7 @@ enum Cmd {},/// Run your app under a profiler and rank what's worth portingScan {- /// Stop the app after this many seconds and rank what ran (Python, Node, Go, Java, Kotlin, Ruby, PHP, C, C++, C#: servers and GUIs that don't exit)+ /// Stop the app after this many seconds and rank what ran (Python, Node, Go, Java, Kotlin, Ruby, PHP, C, C++, R, C#: servers and GUIs that don't exit)#[arg(long, value_name = "SECS")]duration: Option<f64>,/// How you run your app, after --diff --git a/src/mcp.rs b/src/mcp.rsindex 5ee131f..c1455c5 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -23,7 +23,7 @@ fn tools() -> Value {tool("fast_scan","Run the app under a profiler and rank functions by time share and portability to Rust.",- json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "duration": { "type": "number", "description": "Python, Node, Go, Java, Kotlin, Ruby, PHP, C, C++ and C#: stop the app after this many seconds (GUIs, servers)" }, "path": path }),+ json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "duration": { "type": "number", "description": "Python, Node, Go, Java, Kotlin, Ruby, PHP, C, C++, R and C#: stop the app after this many seconds (GUIs, servers)" }, "path": path }),json!(["command"])),tool(diff --git a/src/pipeline.rs b/src/pipeline.rsindex d751fa3..fe74d2e 100644--- a/src/pipeline.rs+++ b/src/pipeline.rs@@ -36,7 +36,7 @@ pub fn scan(root: &Path, command: Vec<String>, duration: Option<f64>) -> Result<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.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript, Go, Java, Kotlin, Ruby, PHP, C, C++ and C# apps only so far");+ ensure!(lang.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript, Go, Java, Kotlin, Ruby, PHP, C, C++, R and C# apps only so far");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)?;diff --git a/src/r.rs b/src/r.rsindex c105db8..49556c2 100644--- a/src/r.rs+++ b/src/r.rs@@ -14,6 +14,7 @@ use serde_json::{Value, json};use std::fs;use std::path::{Path, PathBuf};use std::process::{Command, Output, Stdio};+use std::time::Duration;const RUNNER: &str = include_str!("r/runner.R");const STARTUP: &str = include_str!("r/startup.R");@@ -127,8 +128,23 @@ fn runner(ctx: &Ctx, rscript: &str, mode: &str, job: Value) -> Result<Output> {/// Run the app with fast-anything's startup file loaded first (the app's own still runs after it).fn run_app(ctx: &Ctx, rscript: &str, args: &[String], mode: &str, env: &[(&str, &Path)]) -> Result<Output> {+ Ok(run_app_for(ctx, rscript, args, mode, env, None)?.0)+}++/// run_app, ending the app after `duration` seconds (and stopping it from outside 15s later).+fn run_app_for(+ ctx: &Ctx,+ rscript: &str,+ args: &[String],+ mode: &str,+ env: &[(&str, &Path)],+ duration: Option<f64>,+) -> Result<(Output, bool)> {write_scripts(ctx)?;let mut cmd = Command::new(rscript);+ if let Some(d) = duration {+ cmd.env("FAST_ANYTHING_STOP_AFTER", d.to_string());+ }cmd.args(args).current_dir(&ctx.root).env("R_PROFILE_USER", ctx.fast.join("startup.R"))@@ -141,14 +157,23 @@ fn run_app(ctx: &Ctx, rscript: &str, args: &[String], mode: &str, env: &[(&str,for (k, v) in env {cmd.env(k, v);}- output(&mut cmd, "Rscript")+ // R stops on Ctrl+C even in a blocking call, and its error handler (startup.R) then quits cleanly+ crate::util::output_signalling(+ &mut cmd,+ "Rscript",+ duration.map(Duration::from_secs_f64),+ Duration::from_secs(15),+ "INT",+ )}-pub fn profile(ctx: &Ctx, rscript: &str, args: &[String]) -> Result<Profile> {+/// `duration`: end the app after that many seconds (servers that run until closed).+pub fn profile(ctx: &Ctx, rscript: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {let script = entry(args)?.clone();let rprof = ctx.fast.join("Rprof.out");- let run = run_app(ctx, rscript, args, "profile", &[("FAST_ANYTHING_OUT", &rprof)])?;+ let (run, stopped) = run_app_for(ctx, rscript, args, "profile", &[("FAST_ANYTHING_OUT", &rprof)], duration)?;ensure!(run.status.success(), "the app failed ({}):\n{}", run.status, tail(&combined(&run), 30));+ ensure!(!stopped || rprof.exists(), "the app didn't stop on Ctrl+C after --duration");let result = ctx.fast.join("profile.json");let job = json!({ "root": ctx.root, "rprof": rprof, "entry": ctx.root.join(script), "out": result });runner(ctx, rscript, "report", job)?;@@ -609,6 +634,25 @@ pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {mod tests {use super::*;+ #[test]+ fn duration_ends_an_app_that_runs_until_closed() {+ if !Command::new("Rscript").arg("--version").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no Rscript on PATH, skipping");+ return;+ }+ let dir = std::env::temp_dir().join(format!("fa-r-duration-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ // a server's shape: some work, then a long blocking wait+ let app = "work <- function(n) {\n s <- 0\n for (i in seq_len(n)) s <- s + i * i %% 7\n s\n}\n\nif (sys.nframe() == 0) {\n for (k in 1:3) work(400000)\n Sys.sleep(3600)\n}\n";+ fs::write(dir.join("app.R"), app).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let p = profile(&ctx, "Rscript", &["app.R".into()], Some(2.0));+ let _ = fs::remove_dir_all(&dir);+ let p = p.unwrap();+ assert!(p.functions.iter().any(|f| f.name == "work"), "{:?}", p.functions);+ assert!((1.5..12.0).contains(&p.wall), "{}", p.wall);+ }+#[test]fn spots_r_and_its_script() {assert!(is_r("Rscript") && is_r("/usr/bin/Rscript") && is_r("C:\\R\\bin\\Rscript.exe") && !is_r("R"));diff --git a/src/r/startup.R b/src/r/startup.Rindex 9649d1f..5dcf301 100644--- a/src/r/startup.R+++ b/src/r/startup.R@@ -20,6 +20,14 @@ local({}, onexit = TRUE)# kept reachable, so the finalizer runs when R exits, not at the next garbage collectionassign(".fast_anything_profile", fa, envir = globalenv())+ # scan --duration: a server runs until closed, so scan interrupts it (SIGINT) after that long;+ # quitting then runs the finalizer above+ stop_after <- as.numeric(Sys.getenv("FAST_ANYTHING_STOP_AFTER", "0"))+ if (!is.na(stop_after) && stop_after > 0) {+ options(error = function() {+ if (proc.time()[["elapsed"]] - start >= stop_after - 0.5) quit("no", status = 0)+ })+ }}if (mode == "record") {diff --git a/src/util.rs b/src/util.rsindex 3faf875..329b6d7 100644--- a/src/util.rs+++ b/src/util.rs@@ -48,6 +48,17 @@ pub fn output(cmd: &mut Command, what: &str) -> Result<Output> {/// SIGTERM elsewhere), so it can shut down cleanly and write what it has, then ends it for good after `grace`./// Also says whether it had to be stopped.pub fn output_for(cmd: &mut Command, what: &str, limit: Option<Duration>, grace: Duration) -> Result<(Output, bool)> {+ output_signalling(cmd, what, limit, grace, "TERM")+}++/// output_for, asking the process to stop with this signal on Unix (INT is Ctrl+C).+pub fn output_signalling(+ cmd: &mut Command,+ what: &str,+ limit: Option<Duration>,+ grace: Duration,+ signal: &str,+) -> Result<(Output, bool)> {let Some(limit) = limit else { return Ok((output(cmd, what)?, false)) };let mut child = cmd.stdout(Stdio::piped())@@ -72,7 +83,7 @@ pub fn output_for(cmd: &mut Command, what: &str, limit: Option<Duration>, grace:}match asked {None if started.elapsed() >= limit => {- asked = Some(if ask_to_close(child.id()) { Instant::now() } else { Instant::now() - grace });+ asked = Some(if ask_to_close(child.id(), signal) { Instant::now() } else { Instant::now() - grace });}Some(at) if at.elapsed() >= grace => {let _ = child.kill();@@ -87,8 +98,9 @@ pub fn output_for(cmd: &mut Command, what: &str, limit: Option<Duration>, grace:}/// Ask a process to close the way a user would. False if it can't be asked (a console app on Windows).-fn ask_to_close(pid: u32) -> bool {- let (program, args) = if cfg!(windows) { ("taskkill", ["/PID"]) } else { ("kill", ["-TERM"]) };+fn ask_to_close(pid: u32, signal: &str) -> bool {+ let flag = format!("-{signal}");+ let (program, args) = if cfg!(windows) { ("taskkill", ["/PID"]) } else { ("kill", [flag.as_str()]) };Command::new(program).args(args).arg(pid.to_string())