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: keep what the app printed in .fast/app.log and say where it is (#142)
EL4CTEO5b845ac79c07
diff --git a/src/backend.rs b/src/backend.rsindex d251df5..4ac81f0 100644--- a/src/backend.rs+++ b/src/backend.rs@@ -3,13 +3,13 @@use crate::hotspot::Hotspot;use crate::state::{Ctx, Port, Verify};-use crate::util::{output, tail};+use crate::util::{combined, output, tail};use crate::{cfamily, csharp, golang, java, kotlin, node, php, python, r, ruby};use anyhow::{Context, Result, bail, ensure};use serde::{Deserialize, Serialize};use std::fs;use std::path::{Path, PathBuf};-use std::process::Command;+use std::process::{Command, Output};#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]@@ -37,6 +37,16 @@ pub struct Profile {/// What the scan should tell the user besides the ranking.#[serde(default)]pub notes: Vec<String>,+ /// What the app printed while it was profiled (stdout, then stderr).+ #[serde(skip)]+ pub output: String,+}++impl Profile {+ /// The profile, keeping what the profiled run printed.+ pub fn printed(self, run: &Output) -> Profile {+ Profile { output: combined(run), ..self }+ }}#[derive(Deserialize)]@@ -553,6 +563,18 @@ pub fn line_starting(text: &str, prefixes: &[&str]) -> Option<usize> {mod tests {use super::*;+ #[test]+ fn a_profile_keeps_what_the_app_printed() {+ let run = Command::new(if cfg!(windows) { "cmd" } else { "sh" })+ .args(if cfg!(windows) { ["/C", "echo out& echo err 1>&2"] } else { ["-c", "echo out; echo err >&2"] })+ .output()+ .unwrap();+ let profile: Profile = serde_json::from_str(r#"{"wall": 1.0, "base": ".", "functions": []}"#).unwrap();+ assert!(profile.output.is_empty(), "not in the JSON a backend's helper writes");+ let text = profile.printed(&run).output.replace("\r\n", "\n");+ assert!(text.starts_with("out") && text.trim_end().ends_with("err"), "{text:?}");+ }+#[test]fn source_hash_follows_the_sources() {let dir = std::env::temp_dir().join(format!("fa-hash-test-{}", std::process::id()));diff --git a/src/cfamily.rs b/src/cfamily.rsindex c29074d..b4b0b5b 100644--- a/src/cfamily.rs+++ b/src/cfamily.rs@@ -919,7 +919,7 @@ pub fn profile(ctx: &Ctx, cc: &str, args: &[String], lang: Lang, duration: OptioNone => {}}}- Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new() })+ Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new(), output: combined(&ran) })}// ------------------------------------------------------------------ recordingdiff --git a/src/csharp.rs b/src/csharp.rsindex e9a7e7c..5790d73 100644--- a/src/csharp.rs+++ b/src/csharp.rs@@ -498,7 +498,7 @@ pub fn profile(ctx: &Ctx, dotnet: &str, args: &[String], duration: Option<f64>)}}).collect();- Ok(Profile { wall, base: ".".into(), functions, notes })+ Ok(Profile { wall, base: ".".into(), functions, notes, output: combined(&out) })}// ------------------------------------------------------------------ editing the sourcediff --git a/src/golang.rs b/src/golang.rsindex d391c67..bf78b23 100644--- a/src/golang.rs+++ b/src/golang.rs@@ -346,7 +346,7 @@ pub fn profile(ctx: &Ctx, go: &str, args: &[String], duration: Option<f64>) -> Rfunctions.push(hotspot(ctx, f, flat, cum));}}- Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new() })+ Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new(), output: combined(&out) })}fn pkg_name(ctx: &Ctx, hs: &Hotspot) -> Result<String> {diff --git a/src/java.rs b/src/java.rsindex 9d5cf30..a8489ed 100644--- a/src/java.rs+++ b/src/java.rs@@ -426,7 +426,7 @@ pub(crate) fn profile_with()}).collect();- Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new() })+ Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new(), output: combined(&run) })}// ------------------------------------------------------------------ editing the sourcediff --git a/src/node.rs b/src/node.rsindex b7abcfb..588d42a 100644--- a/src/node.rs+++ b/src/node.rs@@ -167,7 +167,8 @@ pub fn profile(ctx: &Ctx, node: &str, args: &[String], duration: Option<f64>) ->let result = ctx.fast.join("profile.json");let job = json!({ "root": ctx.root, "dir": dir, "entry": ctx.root.join(script), "out": result });runner(ctx, node, "profile", job)?;- serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")+ let profile: Profile = serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")?;+ Ok(profile.printed(&out))}/// The entry script's main block, if its main code sits under one.diff --git a/src/php.rs b/src/php.rsindex 4a4987b..d4ab322 100644--- a/src/php.rs+++ b/src/php.rs@@ -230,7 +230,7 @@ pub fn profile(ctx: &Ctx, php: &str, args: &[String], duration: Option<f64>) ->None => {}}}- Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new() })+ Ok(Profile { wall, base: ".".into(), functions, notes: Vec::new(), output: combined(&run) })}fn name_const(hs: &Hotspot) -> &'static str {diff --git a/src/pipeline.rs b/src/pipeline.rsindex 3348157..12b4354 100644--- a/src/pipeline.rs+++ b/src/pipeline.rs@@ -17,6 +17,8 @@ pub struct ScanOut {pub wall: f64,pub hotspots: Vec<Hotspot>,pub notes: Vec<String>,+ /// Where what the app printed while it was profiled is kept; None when it printed nothing.+ pub app_output: Option<PathBuf>,}/// `duration`: stop the app after that many seconds (a GUI or a server that doesn't exit on its own).@@ -59,7 +61,10 @@ pub fn scan(root: &Path, command: Vec<String>, duration: Option<f64>) -> Result<if let Some(d) = duration.filter(|_| lang != Lang::CSharp) {ui::line(format!(" stopping it after {d}s"));}+ let app_output = ctx.fast.join("app.log");+ let _ = fs::remove_file(&app_output);let profile = lang.profile(&ctx, &exe, &command[1..], duration).map_err(explain)?;+ let app_output = keep_output(&app_output, &profile.output)?;let hotspots = hotspot::rank(profile.functions, profile.wall);let mut notes = profile.notes;notes.extend(attribution_notes(&hotspots));@@ -69,7 +74,16 @@ pub fn scan(root: &Path, command: Vec<String>, duration: Option<f64>) -> Result<ctx.state.wall = profile.wall;ctx.state.hotspots = hotspots.clone();ctx.save()?;- Ok(ScanOut { command, wall: profile.wall, hotspots, notes })+ Ok(ScanOut { command, wall: profile.wall, hotspots, notes, app_output })+}++/// Keep what the app printed, so a successful scan doesn't swallow it (#142).+fn keep_output(path: &Path, printed: &str) -> Result<Option<PathBuf>> {+ if printed.trim().is_empty() {+ return Ok(None);+ }+ fs::write(path, printed).with_context(|| format!("saving the app's output to {}", path.display()))?;+ Ok(Some(path.to_path_buf()))}/// What the ranking can't show by itself: no call counts from a sampling profiler, and a run that@@ -641,6 +655,18 @@ mod tests {assert!(low.len() == 2 && low[1].starts_with("your biggest function takes only 20% of the run"), "{low:?}");}+ #[test]+ fn the_apps_output_is_kept_when_it_printed_something() {+ let dir = std::env::temp_dir().join(format!("fa-app-log-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ let log = dir.join("app.log");+ assert_eq!(keep_output(&log, " \n").unwrap(), None);+ assert!(!log.exists());+ assert_eq!(keep_output(&log, "done: 42\n").unwrap(), Some(log.clone()));+ assert_eq!(fs::read_to_string(&log).unwrap(), "done: 42\n");+ let _ = fs::remove_dir_all(dir);+ }+#[test]fn slow_but_right_gets_asked_for_speed() {let v = Verify {diff --git a/src/python.rs b/src/python.rsindex 8e14922..bcc0241 100644--- a/src/python.rs+++ b/src/python.rs@@ -223,8 +223,9 @@ pub fn profile(ctx: &Ctx, python: &str, app_args: &[String], duration: Option<f6let out = ctx.fast.join("profile.json");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")+ let run = helper_for(ctx, python, "profile", job, app_args, limit)?;+ let profile: Profile = serde_json::from_str(&fs::read_to_string(&out)?).context("reading the profile")?;+ Ok(profile.printed(&run))}const MAIN_GUARD: &[&str] =diff --git a/src/r.rs b/src/r.rsindex 3ac0021..1537ac9 100644--- a/src/r.rs+++ b/src/r.rs@@ -177,7 +177,8 @@ pub fn profile(ctx: &Ctx, rscript: &str, args: &[String], duration: Option<f64>)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)?;- serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")+ let profile: Profile = serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")?;+ Ok(profile.printed(&run))}fn wrap_line(name: &str) -> String {diff --git a/src/ruby.rs b/src/ruby.rsindex e544c1e..32331e7 100644--- a/src/ruby.rs+++ b/src/ruby.rs@@ -82,8 +82,9 @@ fn runner_for(pub fn profile(ctx: &Ctx, ruby: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {let result = ctx.fast.join("profile.json");let job = json!({ "root": ctx.root, "out": result, "duration": duration });- runner_for(ctx, ruby, "profile", job, args, duration.map(|d| Duration::from_secs_f64(d + 15.0)))?;- serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")+ let run = runner_for(ctx, ruby, "profile", job, args, duration.map(|d| Duration::from_secs_f64(d + 15.0)))?;+ let profile: Profile = serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")?;+ Ok(profile.printed(&run))}fn owner(hs_owner: Option<&str>) -> &str {diff --git a/src/show.rs b/src/show.rsindex cb73fc8..11db3d3 100644--- a/src/show.rs+++ b/src/show.rs@@ -49,6 +49,7 @@ pub fn scan(s: &ScanOut) {for n in &s.notes {ui::line(format!(" {}", yellow(format!("! {n}"))));}+ app_output(s);return;}ui::line(dim(format!(" # {} {:<16} {:>6}{:>11} verdict", pad("function", 30), "total", "self", "calls")));@@ -85,6 +86,7 @@ pub fn scan(s: &ScanOut) {if !s.notes.is_empty() {ui::line("");}+ app_output(s);match s.hotspots.iter().find(|h| h.worth_it()) {Some(h) => next(&format!("fast-anything port {}", h.id)),None => {@@ -93,6 +95,12 @@ pub fn scan(s: &ScanOut) {}}+fn app_output(s: &ScanOut) {+ if let Some(path) = &s.app_output {+ ui::line(dim(format!(" what the app printed is in {}", path.display())));+ }+}+pub fn port(p: &PortOut, show_next: bool) {ui::ok(format!("recorded {} real call{} to {} (of {} made){}",@@ -330,6 +338,7 @@ pub fn scan_json(s: &ScanOut) -> Value {"wall_seconds": s.wall,"hotspots": hotspots,"notes": s.notes,+ "app_output": s.app_output,})}@@ -441,8 +450,10 @@ mod tests {},],notes: vec!["note".into()],+ app_output: Some(PathBuf::from(".fast/app.log")),};let parsed = parse(scan_json(&scan));+ assert_eq!(parsed["app_output"], ".fast/app.log");assert_eq!(parsed["command"], json!(["python", "app.py"]));assert_eq!(parsed["wall_seconds"], 2.5);assert_eq!(