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
verify: don't enable a port too cheap to time per call
Milosz2ea3e03bb3b6
diff --git a/README.md b/README.mdindex a5dcb3c..fcd6479 100644--- a/README.md+++ b/README.md@@ -56,7 +56,7 @@ Or step by step:<p align="center"><img src="https://raw.githubusercontent.com/EL4CTEO/fast-anything/main/docs/assets/verify.gif" alt="verify catches a wrong port" width="820"></p>-That port looked right but compared bytes instead of characters. 148 of 500 real calls caught it. On top of the recorded calls, fast-anything derives extra cases and lets the original answer them: edge cases (NaN, ±infinity, -0.0, zero and ±1, non-ASCII text, empty and up to 16× bigger inputs) and shrunk inputs (tiny and random slices). Nothing is enabled until every case matches: same values (floats within 1e-9 of their size or of the largest value in the same list, -0.0 not 0.0), errors where the original errors. A port that is right but slower per call than the original (calling into Rust costs more than the work saved) isn't enabled either. `FAST_ANYTHING_DISABLE=1` runs the original any time.+That port looked right but compared bytes instead of characters. 148 of 500 real calls caught it. On top of the recorded calls, fast-anything derives extra cases and lets the original answer them: edge cases (NaN, ±infinity, -0.0, zero and ±1, non-ASCII text, empty and up to 16× bigger inputs) and shrunk inputs (tiny and random slices). Nothing is enabled until every case matches: same values (floats within 1e-9 of their size or of the largest value in the same list, -0.0 not 0.0), errors where the original errors. A port that is right but slower per call than the original (calling into Rust costs more than the work saved) isn't enabled either, nor is one whose original takes about as long as a clock read (where each call is timed on its own: C, C++, Go, Java, Kotlin, PHP, C#), since the per-call times can't show a saving there. `FAST_ANYTHING_DISABLE=1` runs the original any time.Every 5th recorded call (from 5 calls up) is held out of the crate folder the agent works in: verify replays it too but reports a mismatch there without the values, so a port that special-cases the calls it was shown still fails.diff --git a/src/cfamily.rs b/src/cfamily.rsindex 667d143..9dd4f86 100644--- a/src/cfamily.rs+++ b/src/cfamily.rs@@ -1226,6 +1226,7 @@ pub const FLAVOR_C: Flavor = Flavor {"A `const T *` followed by a length arrives as a Vec, and the length parameter still arrives on its own.","`const char *` arrives as a UTF-8 String: `strlen` and `s[i]` are bytes, use `as_bytes()` for the same behavior.","Floats: compilers may fuse `a * b + c` into one FMA instruction (clang does on ARM), which rounds differently. If recorded results differ in the last digits, the original was built that way: use `f64::mul_add` there, or build the app with `-ffp-contract=off`.",+ "`long double` arrives and returns as `f64`: the bridge and the recordings narrow it to `double`.","Returns are numbers or bools. Undefined behavior in the original (overflow of signed ints, out-of-bounds reads) isn't a spec: match the defined cases.",],floats: None,@@ -2250,6 +2251,71 @@ mod tests {// both sides timed per call: within 3x of the original (through JSON it was 22x slower)let m = v.micro.expect("timed");assert!(m.rust_ns > 0.0 && m.rust_ns < 3.0 * m.original_ns, "{m:?}");+ assert!(m.clock_ns > 0.0 && m.clock_ns < m.original_ns, "the clock is part of the original's time: {m:?}");+ }++ #[cfg(unix)]+ #[test]+ fn too_cheap_to_time_stays_off_and_microseconds_get_switched_on() {+ let geo = "double dist2(double x1, double y1, double x2, double y2) {\n double dx = x1 - x2, dy = y1 - y2;\n return dx * dx + dy * dy;\n}\n";+ let ranges = "/* Mean of [lo, hi), the slow way: NaN for an empty range (0/0). */\ndouble mean_of_range(long long lo, long long hi) {\n double s = 0.0;\n for (long long i = lo; i < hi; i++) s += (double) i;\n return s / (double) (hi - lo);\n}\n";+ let main = "#include <math.h>\n#include <stdio.h>\ndouble dist2(double x1, double y1, double x2, double y2);\ndouble mean_of_range(long long lo, long long hi);\nint main(void) {\n double acc = 0.0, total = 0.0;\n int empty = 0;\n for (int i = 0; i < 200000; i++) acc += dist2(i * 1e-5, 1.0 - i * 1e-5, 0.5, 0.25);\n for (int k = 0; k < 20000; k++) {\n long long lo = k * 37 % 1000, hi = lo + (k % 50) * 100;\n double m = mean_of_range(lo, hi);\n if (isnan(m)) empty++;\n else total += m;\n }\n printf(\"%.6f, total %.3f, empty ranges %d\\n\", acc, total, empty);\n return 0;\n}\n";+ let ports = [+ (+ "geo.dist2",+ "pub fn dist2(x1: f64, y1: f64, x2: f64, y2: f64) -> Result<f64, String> {\n let (dx, dy) = (x1 - x2, y1 - y2);\n Ok(dx * dx + dy * dy)\n}\n",+ ),+ (+ "ranges.mean_of_range",+ "pub fn mean_of_range(lo: i64, hi: i64) -> Result<f64, String> {\n if hi <= lo {\n return Ok(0.0 / (hi - lo) as f64);\n }\n Ok((lo + hi - 1) as f64 / 2.0)\n}\n",+ ),+ ];+ let files = [("geo.c", geo), ("ranges.c", ranges), ("main.c", main)];+ let Some((dir, cc)) = enabled_c_project("cheap", &files, &ports) else {+ eprintln!("no C compiler or cargo on PATH, skipping");+ return;+ };+ for (id, _) in ports {+ crate::pipeline::disable(&dir, Some(id)).unwrap();+ }+ // other tests building meanwhile can slow the recorded calls down: record those again+ for _ in 0..5 {+ if replay(&dir, "geo.dist2").too_cheap() {+ break;+ }+ let out = crate::pipeline::port(&dir, Some("geo.dist2"), 200).unwrap();+ fs::write(&out.lib_rs, ports[0].1).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ assert!(backend::build(&ctx, &ctx.state.ports["geo.dist2"]).unwrap().is_ok());+ }+ // what verify keeps for enable+ let mut ctx = Ctx::open(&dir).unwrap();+ let [cheap, costly] = ports.map(|(id, _)| {+ let v = Verify { built: true, lang: Lang::C, ..replay(&dir, id) };+ ctx.state.ports.get_mut(id).unwrap().verify = Some(v.clone());+ v+ });+ ctx.save().unwrap();+ let refused = crate::pipeline::enable(&dir, Some("geo.dist2"), false);+ let switched = crate::pipeline::enable(&dir, Some("ranges.mean_of_range"), false);+ let original = run_c(&dir, cc, &["main.c", "geo.c", "ranges.c"], true);+ let enabled = run_c(&dir, cc, &["main.c", "geo.c", "ranges.c"], false);+ let on = Ctx::open(&dir).unwrap().state.ports.values().map(|p| (p.id.clone(), p.enabled)).collect::<Vec<_>>();+ let forced = crate::pipeline::enable(&dir, Some("geo.dist2"), true);+ let _ = fs::remove_dir_all(&dir);+ assert!(cheap.ok() && cheap.too_cheap(), "{:?}", cheap.micro);+ let refused = refused.unwrap_err().to_string();+ assert!(+ refused.starts_with("geo.dist2 takes about as long as reading the clock (")+ && refused.contains(" in C, the clock "),+ "{refused}"+ );+ assert!(costly.ok() && !costly.too_cheap() && !costly.slower(), "{:?}", costly.micro);+ switched.unwrap();+ assert_eq!(on, [("geo.dist2".to_string(), false), ("ranges.mean_of_range".to_string(), true)]);+ assert!(original.ends_with("empty ranges 400\n"), "{original}");+ assert_eq!(enabled, original);+ forced.unwrap();}/// The typed glue generated into every C port, compiled here as it is there.diff --git a/src/main.rs b/src/main.rsindex 448b80b..b9c8280 100644--- a/src/main.rs+++ b/src/main.rs@@ -168,7 +168,7 @@ fn run(cmd: Cmd, root: &Path) -> Result<()> {if !v.ok() {bail!("{agent} couldn't get {} right in {attempts} attempts", out.id);}- if !v.slower() {+ if !v.slower() && !v.too_cheap() {show::next(&format!("fast-anything enable {}", out.id));}}@@ -181,7 +181,7 @@ fn run(cmd: Cmd, root: &Path) -> Result<()> {if !v.ok() {bail!("{id} doesn't match the original yet");}- if !v.slower() {+ if !v.slower() && !v.too_cheap() {show::next(&format!("fast-anything enable {id}"));}Ok(())diff --git a/src/native.rs b/src/native.rsindex e02a550..95c28fd 100644--- a/src/native.rs+++ b/src/native.rs@@ -424,14 +424,25 @@ pub fn replay(job_path: &Path) -> Result<()> {}};if rust_ns >= 0.0 {- v.micro =- Some(Micro { original_ns, rust_ns, speedup: if rust_ns > 0.0 { original_ns / rust_ns } else { 0.0 } });+ let speedup = if rust_ns > 0.0 { original_ns / rust_ns } else { 0.0 };+ v.micro = Some(Micro { original_ns, rust_ns, speedup, clock_ns: clock_ns() });}}fs::write(&job.out, serde_json::to_vec(&v)?)?;Ok(())}+/// What one clock read costs here: the least of a thousand back-to-back reads. The recorders time+/// each call of the original with a read before and after it, so about this much of original_ns+/// is the clock.+fn clock_ns() -> f64 {+ let read = || {+ let t = Instant::now();+ t.elapsed()+ };+ (0..1000).map(|_| read()).min().unwrap_or_default().as_secs_f64() * 1e9+}+/// Same value, give or take float rounding.pub fn same(a: &Value, b: &Value, loose_empty: bool) -> bool {same_in(a, b, 0.0, loose_empty)diff --git a/src/pipeline.rs b/src/pipeline.rsindex a6689cf..643ff1f 100644--- a/src/pipeline.rs+++ b/src/pipeline.rs@@ -235,6 +235,18 @@ 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"}+/// Why a port too cheap to time (see Verify::too_cheap) isn't switched on.+pub fn too_cheap_hint(id: &str, v: &Verify) -> String {+ let m = v.micro.unwrap_or_default();+ format!(+ "{id} takes about as long as reading the clock ({} per call in {}, the clock {}), so verify can't tell whether Rust saves anything: {}",+ util::nanos(m.original_ns),+ v.lang.label(),+ util::nanos(m.clock_ns),+ slower_hint()+ )+}+/// Whether the crate is not exactly the one covered by the last verify. Old state without a hash/// keeps its legacy behavior; re-porting clears verify and therefore always needs a new one.fn crate_needs_verify(ctx: &Ctx, port: &Port) -> Result<bool> {@@ -257,6 +269,10 @@ pub fn enable(root: &Path, id: Option<&str>, force: bool) -> Result<String> {if !force && crate_needs_verify(&ctx, &port)? {bail!("{id}'s Rust changed since it passed verify: run fast-anything verify {id} (or --force)");}+ // too cheap to time comes first: a few-ns function measures 1.0x either way, so "slower" is noise+ if let Some(v) = port.verify.as_ref().filter(|v| v.too_cheap() && !force) {+ bail!("{}", too_cheap_hint(&id, v));+ }if let Some(m) = port.verify.as_ref().filter(|v| v.slower() && !force).and_then(|v| v.micro) {bail!("{id} is {} slower per call in Rust: {}", util::times(1.0 / m.speedup), slower_hint());}@@ -421,7 +437,7 @@ pub fn agent_port(root: &Path, id: &str, agent_spec: &str, attempts: usize) -> Rlet attempts = attempts.max(1);let mut last: Option<Verify> = None;// A port that's right but slower goes back to the agent to speed up; if no later attempt is both- // right and faster, its sources are put back.+ // right and faster, its sources are put back. One too cheap to time can't be shown faster.let mut right: Option<(Verify, Snapshot)> = None;for attempt in 1..=attempts {let ctx = Ctx::open(root)?;@@ -435,7 +451,7 @@ pub fn agent_port(root: &Path, id: &str, agent_spec: &str, attempts: usize) -> Ragent::run(agent_spec, &dir, &prompt, &dir.join("agent.log"))?;let (_, v) = verify(root, Some(id))?;show::verify(id, &v);- if v.ok() && !v.slower() {+ if v.ok() && (!v.slower() || v.too_cheap()) {return Ok(v);}if v.ok() && right.as_ref().is_none_or(|(best, _)| speedup(&v) > speedup(best)) {@@ -553,7 +569,9 @@ pub fn go(for id in &picks {show::port(&port(root, Some(id), samples)?, false);let v = agent_port(root, id, agent_spec, attempts)?;- if v.ok() && v.slower() {+ if v.ok() && v.too_cheap() {+ ui::warn(too_cheap_hint(id, &v));+ } else if v.ok() && v.slower() {ui::warn(format!("{id}: right, but slower in Rust per call; {}", slower_hint()));} else if v.ok() {enable(root, Some(id), false)?;@@ -582,7 +600,7 @@ mod tests {built: true,total: 10,passed: 10,- micro: Some(Micro { original_ns: 1000.0, rust_ns: 4000.0, speedup: 0.25 }),+ micro: Some(Micro { original_ns: 1000.0, rust_ns: 4000.0, speedup: 0.25, clock_ns: 20.0 }),..Verify::default()};let text = feedback(&v);diff --git a/src/show.rs b/src/show.rsindex c1ef57d..1934c6f 100644--- a/src/show.rs+++ b/src/show.rs@@ -138,7 +138,9 @@ pub fn verify(id: &str, v: &Verify) {} else {ui::ok(format!("{}/{} recorded calls give the same result", v.passed, v.total));}- if let Some(m) = v.micro {+ if v.too_cheap() {+ ui::warn(crate::pipeline::too_cheap_hint(&bold(id), v));+ } else if let Some(m) = v.micro {ui::ok(format!("{} per call: {} in {}, {} in Rust: {}",bold(id),diff --git a/src/state.rs b/src/state.rsindex 925ed6a..6e641c3 100644--- a/src/state.rs+++ b/src/state.rs@@ -156,6 +156,12 @@ impl Verify {pub fn slower(&self) -> bool {self.micro.is_some_and(|m| m.speedup > 0.0 && m.speedup < 1.0)}++ /// The original's own work per call is under one clock read, so per-call times are mostly the+ /// clock and can't show Rust saving anything (only where clock_ns was measured).+ pub fn too_cheap(&self) -> bool {+ self.micro.is_some_and(|m| m.clock_ns > 0.0 && m.original_ns < 2.0 * m.clock_ns)+ }}#[derive(Debug, Clone, Default, Serialize, Deserialize)]@@ -175,6 +181,9 @@ pub struct Micro {pub original_ns: f64,pub rust_ns: f64,pub speedup: f64,+ /// What one clock read costs, where the original was timed with a read before and after each+ /// call (C-bridge languages); 0 where whole passes were timed.+ pub clock_ns: f64,}pub struct Ctx {@@ -273,14 +282,33 @@ mod tests {#[test]fn slower_only_when_measured_below_one() {- let v =- |speedup| Verify { micro: Some(Micro { original_ns: 1.0, rust_ns: 1.0, speedup }), ..Verify::default() };+ let v = |speedup| Verify {+ micro: Some(Micro { original_ns: 1.0, rust_ns: 1.0, speedup, clock_ns: 0.0 }),+ ..Verify::default()+ };assert!(v(0.5).slower());assert!(!v(1.4).slower());assert!(!v(0.0).slower(), "no measurement isn't slower");assert!(!Verify::default().slower());}+ #[test]+ fn too_cheap_only_under_two_clock_reads() {+ let v = |original_ns, clock_ns| Verify {+ micro: Some(Micro { original_ns, rust_ns: original_ns, speedup: 1.0, clock_ns }),+ ..Verify::default()+ };+ assert!(v(25.0, 22.0).too_cheap() && !v(25.0, 22.0).slower(), "1.0x, but mostly the clock");+ assert!(v(43.9, 22.0).too_cheap());+ assert!(!v(44.0, 22.0).too_cheap(), "work of one clock read on top of the read itself");+ assert!(!v(1800.0, 22.0).too_cheap());+ assert!(!v(25.0, 0.0).too_cheap(), "whole passes timed: no clock to compare");+ assert!(!Verify::default().too_cheap());+ let old: Micro = serde_json::from_str(r#"{"original_ns": 25.0, "rust_ns": 24.0, "speedup": 1.04}"#).unwrap();+ assert_eq!(old.clock_ns, 0.0);+ assert!(!Verify { micro: Some(old), ..Verify::default() }.too_cheap(), "state from before clock_ns");+ }+#[test]fn blocks_in_the_body_are_not_changes() {let original = "static int lev(String a) {\n return a.length();\n}\n";