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.

Warn when the original changed since its port was recorded (#29)

chessMane1ddd126b0d7
diff --git a/src/node.rs b/src/node.rs
index f3968df..e4ea84a 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -618,6 +618,7 @@ mod tests {
lang: backend::Lang::Node,
owner: None,
line: 1,
+ sources: vec![],
};
for original in [
"export const pairs = (names: string[]): number => {\n return 0;\n};\n",
@@ -653,6 +654,7 @@ mod tests {
lang: backend::Lang::Node,
owner: None,
line: 1,
+ sources: vec![],
};
let esm = shim(&port, "./.fast/lib/fa_fuzzy_levenshtein.node", true);
assert!(esm.contains("createRequire(import.meta.url)(\"./.fast/lib/fa_fuzzy_levenshtein.node\").levenshtein"));
diff --git a/src/pipeline.rs b/src/pipeline.rs
index fb9368c..e85fc0e 100644
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@ -115,6 +115,14 @@ pub fn port(root: &Path, id: Option<&str>, samples: usize) -> Result<PortOut> {
);
}
let enabled = ctx.state.ports.get(&hs.id).is_some_and(|p| p.enabled);
+ let helpers: Vec<Hotspot> = hs
+ .calls
+ .iter()
+ .filter_map(|name| ctx.state.hotspots.iter().find(|h| h.file == hs.file && &h.name == name))
+ .cloned()
+ .collect();
+ let text = fs::read_to_string(ctx.root.join(&hs.file)).unwrap_or_default();
+ let sources: Vec<&str> = std::iter::once(&hs).chain(&helpers).map(|h| h.source.as_str()).collect();
let port = Port {
id: hs.id.clone(),
file: hs.file.clone(),
@@ -129,13 +137,8 @@ pub fn port(root: &Path, id: Option<&str>, samples: usize) -> Result<PortOut> {
lang,
owner: hs.owner.clone(),
line: hs.line,
+ sources: crate::state::verbatim(&text, &sources),
};
- let helpers: Vec<Hotspot> = hs
- .calls
- .iter()
- .filter_map(|name| ctx.state.hotspots.iter().find(|h| h.file == hs.file && &h.name == name))
- .cloned()
- .collect();
let task = lang.scaffold(&ctx, &hs, &helpers, &port)?;
ctx.state.ports.insert(port.id.clone(), port);
ctx.save()?;
@@ -156,6 +159,9 @@ pub fn verify(root: &Path, id: Option<&str>) -> Result<(String, Verify)> {
let id = ctx.resolve_port(id)?;
let port = ctx.state.ports[&id].clone();
let source_hash = backend::source_hash(&ctx.crate_dir(&port))?;
+ if ctx.stale(&port) {
+ ui::warn(format!("{} changed since {id} was recorded: {}", port.file, stale_hint(&id)));
+ }
ui::step(format!("building {} (release)", ui::bold(&port.ext)));
let v = match backend::build(&ctx, &port)? {
Err(log) => Verify { built: false, build_log: Some(log), ..Verify::default() },
@@ -202,6 +208,13 @@ pub fn verify_all(root: &Path) -> Result<()> {
Ok(())
}
+/// What to do about a port whose original changed after it was recorded.
+pub fn stale_hint(id: &str) -> String {
+ format!(
+ "its recorded calls and Rust may be out of date. Run fast-anything port {id} to record again, update the Rust, then verify (or --force)"
+ )
+}
+
/// What to do about a port that's right but slower than the original.
pub fn slower_hint() -> &'static str {
"calling into Rust costs more than this function's work, so it won't be switched on. Port its caller instead (fewer, bigger calls), or enable --force"
@@ -211,6 +224,9 @@ pub fn enable(root: &Path, id: Option<&str>, force: bool) -> Result<String> {
let mut ctx = Ctx::open(root)?;
let id = ctx.resolve_port(id)?;
let port = ctx.state.ports[&id].clone();
+ if ctx.stale(&port) && !force {
+ bail!("{} changed since {id} was recorded: {}", port.file, stale_hint(&id));
+ }
let verified = port.verify.as_ref().is_some_and(Verify::ok);
if !verified && !force {
bail!("{id} hasn't passed verify yet: run fast-anything verify {id} (or --force)");
@@ -270,6 +286,9 @@ pub fn build_all(root: &Path) -> Result<()> {
pub fn bench(root: &Path, runs: usize) -> Result<BenchResult> {
let mut ctx = Ctx::open(root)?;
+ for p in ctx.state.ports.values().filter(|p| p.enabled && ctx.stale(p)) {
+ ui::warn(format!("{} changed since {} was recorded: {}", p.file, p.id, stale_hint(&p.id)));
+ }
let result = bench::run(&ctx, runs.max(1))?;
ctx.state.bench = Some(result.clone());
ctx.save()?;
diff --git a/src/python.rs b/src/python.rs
index cb8f204..fd53bb8 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -558,6 +558,7 @@ mod tests {
lang: crate::backend::Lang::Python,
owner: None,
line: 1,
+ sources: vec![],
}
}
diff --git a/src/show.rs b/src/show.rs
index d0de7ef..8ad77d0 100644
--- a/src/show.rs
+++ b/src/show.rs
@@ -209,6 +209,9 @@ pub fn status(ctx: &Ctx) {
.map(|m| format!("{} per call", times(m.speedup)))
.unwrap_or_default();
ui::line(format!(" {} {} {}", pad(&p.id, 32), state, dim(speed)));
+ if ctx.stale(p) {
+ ui::line(format!(" {} {}", pad("", 32), red(format!("! {} changed since it was recorded", p.file))));
+ }
}
if let Some(b) = &s.bench {
ui::line("");
diff --git a/src/state.rs b/src/state.rs
index f92945b..8813535 100644
--- a/src/state.rs
+++ b/src/state.rs
@@ -51,6 +51,10 @@ pub struct Port {
/// Where the function started when it was ported (to find it again among overloads).
#[serde(default)]
pub line: u32,
+ /// Source of the function and the helpers ported with it, as recorded (only text found verbatim
+ /// in the file). When one of them is gone, the original changed and the port may be stale.
+ #[serde(default)]
+ pub sources: Vec<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -72,6 +76,36 @@ pub struct Verify {
pub source_hash: Option<String>,
}
+/// The forms a source may take in the file: as recorded, or with const and let swapped (a Node
+/// port switches its function's const to let while enabled).
+fn forms(source: &str) -> [String; 3] {
+ let source = source.replace("\r\n", "\n");
+ [source.replacen("const ", "let ", 1), source.replacen("let ", "const ", 1), source]
+}
+
+/// The source appears in the file as whole lines.
+fn found(text: &str, source: &str) -> bool {
+ let text = format!("\n{}\n", text.replace("\r\n", "\n"));
+ forms(source).iter().any(|s| text.contains(&format!("\n{}\n", s.trim_end_matches('\n'))))
+}
+
+/// The sources that start a line in the file, each extended to the end of its last line so that
+/// found() can match it as whole lines (see Port::sources).
+pub fn verbatim(text: &str, sources: &[&str]) -> Vec<String> {
+ let text = format!("\n{}\n", text.replace("\r\n", "\n"));
+ sources
+ .iter()
+ .filter(|s| !s.trim().is_empty())
+ .filter_map(|s| {
+ forms(s).iter().find_map(|form| {
+ let at = text.find(&format!("\n{form}"))? + 1;
+ let end = at + form.len() + text[at + form.len()..].find('\n')?;
+ Some(text[at..end].to_string())
+ })
+ })
+ .collect()
+}
+
impl Verify {
pub fn ok(&self) -> bool {
self.built && self.total > 0 && self.failed == 0
@@ -109,6 +143,12 @@ pub struct Ctx {
}
impl Ctx {
+ /// The original changed since the port recorded it: its recorded calls and its Rust may be out of date.
+ pub fn stale(&self, port: &Port) -> bool {
+ let Ok(text) = fs::read_to_string(self.root.join(&port.file)) else { return false };
+ port.sources.iter().any(|s| !found(&text, s))
+ }
+
pub fn open(root: &Path) -> Result<Ctx> {
let root = util::absolute(root);
ensure!(root.is_dir(), "{} isn't a folder", root.display());
@@ -188,4 +228,15 @@ mod tests {
assert!(!v(0.0).slower(), "no measurement isn't slower");
assert!(!Verify::default().slower());
}
+
+ #[test]
+ fn sources_are_found_verbatim() {
+ let file = "def f(x):\r\n return x\r\n\r\nexport let g = (n) => n;\n";
+ let kept = verbatim(file, &["def f(x):\n return x", "export const g = (n) => n", "def h(): pass", " "]);
+ assert_eq!(kept, ["def f(x):\n return x", "export let g = (n) => n;"], "extended to the end of the line");
+ assert!(found(&file.replace("export let", "export const"), &kept[1]), "const or let");
+ let edited = file.replace("return x", "return x + 1");
+ assert!(!found(&edited, &kept[0]), "an edited function is no longer found");
+ assert!(found(&format!("x = 1\n{}", kept[0]), &kept[0]), "at the end of a file without a final newline");
+ }
}