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.

scan --duration for Python apps

Mohit Mishra2d63847f4457
diff --git a/README.md b/README.md
index 9ba4554..729436d 100644
--- a/README.md
+++ b/README.md
@@ -98,7 +98,7 @@ Or wire it up by hand:
| language | binding | status |
|---|---|---|
-| Python 3.10+ | PyO3 | ✅ |
+| Python 3.10+ | PyO3; servers and GUIs: `scan --duration 30` (stops them like Ctrl+C) | ✅ |
| JavaScript / TypeScript (Node 22+, Bun, Deno 2+: `bun app.ts`, `deno run -A app.ts`) | napi-rs | ✅ |
| Ruby 3.3+ | C ABI + JSON, through Ruby's built-in Fiddle | ✅ |
| Java 22+ (`java App.java`, Maven, Gradle) | the same C bridge, through the FFM API | ✅ |
diff --git a/src/backend.rs b/src/backend.rs
index fb730fc..cbd92ba 100644
--- a/src/backend.rs
+++ b/src/backend.rs
@@ -139,16 +139,22 @@ impl Lang {
}
}
- pub fn profile(self, ctx: &Ctx, exe: &str, args: &[String]) -> Result<Profile> {
+ /// Whether `scan --duration` can stop this language's apps.
+ pub fn stops_after_duration(self) -> bool {
+ matches!(self, Lang::Python | Lang::CSharp)
+ }
+
+ /// `duration` (see stops_after_duration): stop the app after that many seconds.
+ pub fn profile(self, ctx: &Ctx, exe: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {
match self {
- Lang::Python => python::profile(ctx, exe, args),
+ Lang::Python => python::profile(ctx, exe, args, duration),
Lang::Node => node::profile(ctx, exe, args),
Lang::Ruby => ruby::profile(ctx, exe, args),
Lang::Java => java::profile(ctx, exe, args),
Lang::Go => golang::profile(ctx, exe, args),
Lang::Php => php::profile(ctx, exe, args),
Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self),
- Lang::CSharp => csharp::profile(ctx, exe, args, None),
+ Lang::CSharp => csharp::profile(ctx, exe, args, duration),
Lang::R => r::profile(ctx, exe, args),
Lang::Kotlin => kotlin::profile(ctx, exe, args),
}
diff --git a/src/main.rs b/src/main.rs
index d1bd8a6..d31e29b 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 porting
Scan {
- /// Stop the app after this many seconds and rank what ran (C#: GUIs and servers that don't exit)
+ /// Stop the app after this many seconds and rank what ran (Python, 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.rs
index 34dab80..edb3722 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": "C# only: 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 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.rs
index e0c2bdc..14175a5 100644
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@ -36,15 +36,15 @@ 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 == Lang::CSharp, "--duration works for C# apps only so far");
+ ensure!(lang.stops_after_duration(), "--duration works for Python 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)?;
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;
diff --git a/src/python.rs b/src/python.rs
index f26a4bd..ae6bfd1 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -10,6 +10,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!("python/runner.py");
const HOOK: &str = include_str!("python/sitecustomize.py");
@@ -82,6 +83,18 @@ pub fn resolve(program: &str, root: &Path) -> Result<String> {
}
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"));
@@ -99,7 +112,13 @@ fn helper(ctx: &Ctx, python: &str, mode: &str, job: Value, app_args: &[String])
if mode != "verify" {
watch_workers(ctx, &mut cmd, &runner, &job_path, mode)?;
}
- let out = output(&mut cmd, "python")?;
+ let (out, killed) = crate::util::output_for(&mut cmd, "python", limit, Duration::from_secs(10))?;
+ if killed {
+ bail!(
+ "the app was still running {}s after --duration: does it stop on Ctrl+C?",
+ limit.unwrap_or_default().as_secs()
+ );
+ }
if !out.status.success() {
bail!("the python {mode} run failed ({}):\n{}", out.status, tail(&combined(&out), 30));
}
@@ -127,9 +146,12 @@ fn watch_workers(ctx: &Ctx, cmd: &mut Command, runner: &Path, job: &Path, mode:
Ok(())
}
-pub fn profile(ctx: &Ctx, python: &str, app_args: &[String]) -> Result<Profile> {
+/// `duration`: stop the app after that many seconds (as Ctrl+C would), for servers and GUIs.
+pub fn profile(ctx: &Ctx, python: &str, app_args: &[String], duration: Option<f64>) -> Result<Profile> {
let out = ctx.fast.join("profile.json");
- helper(ctx, python, "profile", json!({ "root": ctx.root, "out": out, "max": 40 }), app_args)?;
+ let job = json!({ "root": ctx.root, "out": out, "max": 40, "duration": duration });
+ let limit = duration.map(|d| Duration::from_secs_f64(d + 15.0));
+ helper_for(ctx, python, "profile", job, app_args, limit)?;
serde_json::from_str(&fs::read_to_string(&out)?).context("reading the profile")
}
@@ -859,6 +881,34 @@ mod tests {
assert_eq!(strip_shim(&on, "fuzzy.levenshtein"), "class Text:\n pass\n");
}
+ #[test]
+ fn duration_stops_an_app_that_runs_until_closed() {
+ let Some(python) = ["python3", "python"]
+ .into_iter()
+ .find(|p| Command::new(p).arg("--version").output().is_ok_and(|o| o.status.success()))
+ else {
+ eprintln!("no python on PATH, skipping");
+ return;
+ };
+ let dir = std::env::temp_dir().join(format!("fa-py-duration-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ // a server's shape: some work, then a long blocking wait
+ let app = "import time\n\ndef work(n):\n return sum(i * i for i in range(n))\n\nif __name__ == '__main__':\n while True:\n work(20000)\n time.sleep(0.05)\n if work(1) > 0:\n time.sleep(3600)\n";
+ fs::write(dir.join("app.py"), app.replace("work(1) > 0", "time.time() < 0")).unwrap();
+ fs::write(dir.join("slow.py"), app).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let started = std::time::Instant::now();
+ let looping = profile(&ctx, python, &["app.py".into()], Some(1.0));
+ let blocked = profile(&ctx, python, &["slow.py".into()], Some(1.0));
+ let took = started.elapsed().as_secs_f64();
+ let _ = fs::remove_dir_all(&dir);
+ for p in [looping.unwrap(), blocked.unwrap()] {
+ assert!(p.functions.iter().any(|f| f.name == "work"), "{:?}", p.functions);
+ assert!((0.9..5.0).contains(&p.wall), "{}", p.wall);
+ }
+ assert!(took < 12.0, "{took}");
+ }
+
#[test]
fn reading_the_environment_or_argv_blocks() {
let Some(python) = ["python3", "python"]
diff --git a/src/python/runner.py b/src/python/runner.py
index 243d6b9..3af372f 100644
--- a/src/python/runner.py
+++ b/src/python/runner.py
@@ -235,6 +235,30 @@ def prepare_path(kind, target):
return entry, base
+def stop_after(seconds):
+ """Interrupt the app after `seconds`, like Ctrl+C would: for servers and GUIs that run until
+ closed. Returns a function telling whether it did."""
+ import threading
+
+ fired = []
+
+ def fire():
+ fired.append(True)
+ if os.name == "nt":
+ import _thread
+
+ _thread.interrupt_main()
+ else:
+ import signal
+
+ os.kill(os.getpid(), signal.SIGINT) # wakes a main thread blocked in a system call
+
+ timer = threading.Timer(seconds, fire)
+ timer.daemon = True
+ timer.start()
+ return lambda: timer.cancel() or bool(fired)
+
+
def run_target(kind, target, rest):
sys.argv = [target] + list(rest)
try:
@@ -713,12 +737,18 @@ def cmd_profile(job, argv):
root = job["root"]
prof = cProfile.Profile()
sys.modules["_fast_anything_state"] = ChildState("profile", os.environ.get("FAST_ANYTHING_CHILDREN", ""))
+ stopped = stop_after(job["duration"]) if job.get("duration") else None
start = time.perf_counter()
prof.enable()
try:
run_target(kind, target, rest)
+ except (KeyboardInterrupt, SystemExit):
+ if not (stopped and stopped()):
+ raise # the app's own, not the one --duration sent
finally:
prof.disable()
+ if stopped:
+ stopped()
wall = time.perf_counter() - start
del sys.modules["_fast_anything_state"]