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 Go apps

Mohit Mishra18fb27d08449
diff --git a/README.md b/README.md
index f455685..e014307 100644
--- a/README.md
+++ b/README.md
@@ -103,7 +103,7 @@ Or wire it up by hand:
| 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 | ✅ |
| Kotlin/JVM (Gradle, `src/main/kotlin`, JDK 22+) | the Java bridge; top-level functions, `object` and companion members, extension functions | ✅ |
-| Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo) | ✅ |
+| Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo); servers: `scan --duration 30` | ✅ |
| PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`) | ✅ |
| C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ |
| 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` | ✅ |
diff --git a/src/backend.rs b/src/backend.rs
index 2319066..f3e8e0d 100644
--- a/src/backend.rs
+++ b/src/backend.rs
@@ -141,7 +141,7 @@ 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::CSharp)
+ matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::CSharp)
}
/// `duration` (see stops_after_duration): stop the app after that many seconds.
@@ -151,7 +151,7 @@ impl Lang {
Lang::Node => node::profile(ctx, exe, args, duration),
Lang::Ruby => ruby::profile(ctx, exe, args),
Lang::Java => java::profile(ctx, exe, args),
- Lang::Go => golang::profile(ctx, exe, args),
+ Lang::Go => golang::profile(ctx, exe, args, duration),
Lang::Php => php::profile(ctx, exe, args),
Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self),
Lang::CSharp => csharp::profile(ctx, exe, args, duration),
diff --git a/src/golang.rs b/src/golang.rs
index f30d6c4..29dc720 100644
--- a/src/golang.rs
+++ b/src/golang.rs
@@ -14,7 +14,7 @@ use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
-use std::time::Instant;
+use std::time::{Duration, Instant};
const DESCRIBE: &str = include_str!("golang/describe.go");
const REC: &str = include_str!("golang/rec.go");
@@ -300,7 +300,8 @@ fn parse_top(text: &str) -> HashMap<String, (f64, f64)> {
out
}
-pub fn profile(ctx: &Ctx, go: &str, args: &[String]) -> Result<Profile> {
+/// `duration`: end the app after that many seconds (servers and GUIs that run until closed).
+pub fn profile(ctx: &Ctx, go: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {
let run = GoRun::parse(args)?;
let funcs = describe(ctx, go)?;
let (mut patches, extra) = instrument(ctx, &funcs, &run, vec![])?;
@@ -310,16 +311,22 @@ pub fn profile(ctx: &Ctx, go: &str, args: &[String]) -> Result<Profile> {
let pprof = ctx.fast.join("cpu.pprof");
let _ = fs::remove_file(&pprof);
let started = Instant::now();
- let out = output(
- Command::new(&bin)
- .args(&run.args)
+ let mut cmd = Command::new(&bin);
+ if let Some(d) = duration {
+ cmd.env("FAST_ANYTHING_STOP_AFTER_MS", ((d * 1000.0) as u64).to_string());
+ }
+ let (out, killed) = util::output_for(
+ cmd.args(&run.args)
.current_dir(&ctx.root)
.env("FAST_ANYTHING_PPROF", &pprof)
.env(DISABLE_ENV, "1")
.stdin(Stdio::null()),
"the app",
+ duration.map(|d| Duration::from_secs_f64(d + 15.0)),
+ Duration::from_secs(10),
)?;
let wall = started.elapsed().as_secs_f64();
+ ensure!(!killed, "the app was still running 15s after --duration");
ensure!(out.status.success(), "the app failed ({}):\n{}", out.status, tail(&combined(&out), 30));
ensure!(pprof.exists(), "no profile was written: does main return normally (no os.Exit)?");
let top = output(
@@ -736,6 +743,30 @@ func main() {
assert_eq!(after, main, "the app is left as it was");
}
+ #[test]
+ fn duration_ends_an_app_that_runs_until_closed() {
+ if !Command::new("go").arg("version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no go on PATH, skipping");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("fa-go-duration-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("go.mod"), "module demo\n\ngo 1.22\n").unwrap();
+ // a server's shape: work, forever
+ let work = "package main\n\nfunc work(n int) int {\n\ts := 0\n\tfor i := 0; i < n; i++ {\n\t\ts += i * i % 7\n\t}\n\treturn s\n}\n";
+ let main = "package main\n\nimport \"time\"\n\nvar sink int\n\nfunc main() {\n\tfor {\n\t\tsink += work(5000000)\n\t\ttime.Sleep(time.Millisecond)\n\t}\n}\n";
+ fs::write(dir.join("work.go"), work).unwrap();
+ fs::write(dir.join("main.go"), main).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let p = profile(&ctx, "go", &["run".into(), ".".into()], Some(1.5));
+ let after = fs::read_to_string(dir.join("main.go")).unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ let p = p.unwrap();
+ assert!(p.functions.iter().any(|f| f.name == "work" && f.cumtime > 0.0), "{:?}", p.functions);
+ assert!((1.0..12.0).contains(&p.wall), "{}", p.wall);
+ assert_eq!(after, main);
+ }
+
#[test]
fn go_commands_and_profiles() {
let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
diff --git a/src/golang/hooks.go b/src/golang/hooks.go
index 7e04146..6d5b58b 100644
--- a/src/golang/hooks.go
+++ b/src/golang/hooks.go
@@ -5,9 +5,15 @@ import (
"expvar"
"os"
"runtime/pprof"
+ "strconv"
+ "sync"
+ "time"
)
-var fastAnythingProfFile *os.File
+var (
+ fastAnythingProfFile *os.File
+ fastAnythingDoneOnce sync.Once
+)
func init() {
if path := os.Getenv("FAST_ANYTHING_PPROF"); path != "" {
@@ -15,16 +21,25 @@ func init() {
fastAnythingProfFile = f
}
}
+ // scan --duration: a server or GUI runs until closed, so end it after that long, profile saved
+ if ms, err := strconv.Atoi(os.Getenv("FAST_ANYTHING_STOP_AFTER_MS")); err == nil && ms > 0 {
+ time.AfterFunc(time.Duration(ms)*time.Millisecond, func() {
+ fastAnythingDone()
+ os.Exit(0)
+ })
+ }
}
// Deferred at the top of main: stops the profile and saves recordings when main returns.
func fastAnythingDone() {
- if fastAnythingProfFile != nil {
- pprof.StopCPUProfile()
- fastAnythingProfFile.Close()
- fastAnythingProfFile = nil
- }
- if save, ok := expvar.Get("fast_anything_save").(expvar.Func); ok {
- save()
- }
+ fastAnythingDoneOnce.Do(func() {
+ if fastAnythingProfFile != nil {
+ pprof.StopCPUProfile()
+ fastAnythingProfFile.Close()
+ fastAnythingProfFile = nil
+ }
+ if save, ok := expvar.Get("fast_anything_save").(expvar.Func); ok {
+ save()
+ }
+ })
}
diff --git a/src/main.rs b/src/main.rs
index e80847d..ed98bad 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 (Python, Node, C#: servers and GUIs that don't exit)
+ /// Stop the app after this many seconds and rank what ran (Python, Node, Go, 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 1051f10..e62a2f3 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 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 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 1d49cbf..c93bad5 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 and C# apps only so far");
+ ensure!(lang.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript, Go 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)?;