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
Refuse ports of functions that change their arguments; faster port rebuilds
EL4CTEOfe04fea81722
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1371feb..5a48432 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,8 @@## 0.6.0- C# / .NET 8+: `fast-anything scan -- dotnet run -c Release`. Profiled with the runtime's own EventPipe sampler (nothing to install), sources read with Roslyn, ports called through NativeLibrary. Static methods taking numbers, strings, arrays, lists and string-keyed dictionaries; verify adds edge cases and shrunk inputs. Thanks @JuggyBob for the request (#3).+- `port` refuses functions that change their arguments in place (seen while recording): a port only returns a value, so verify could pass a port that drops those changes (#4).+- Ports rebuild about 4× faster after each edit (no LTO, parallel codegen; no measurable runtime cost).## 0.5.1diff --git a/src/backend.rs b/src/backend.rsindex 9ba3f05..cc40a54 100644--- a/src/backend.rs+++ b/src/backend.rs@@ -40,6 +40,9 @@ pub struct Recording {pub kept: usize,pub skipped: usize,pub unsupported: Vec<String>,+ /// The function changed an argument in place during a recorded call.+ #[serde(default)]+ pub mutates: bool,}impl Lang {@@ -225,7 +228,9 @@ pub const CARGO_CONFIG: &str = "# Built for the machine that runs it: .fast/lib[target.aarch64-apple-darwin]\nrustflags = [\"-C\", \"target-cpu=native\", \"-C\", \"link-arg=-undefined\", \"-C\", \"link-arg=dynamic_lookup\"]\n\n\[target.x86_64-apple-darwin]\nrustflags = [\"-C\", \"target-cpu=native\", \"-C\", \"link-arg=-undefined\", \"-C\", \"link-arg=dynamic_lookup\"]\n";-pub const RELEASE_PROFILE: &str = "[profile.release]\nopt-level = 3\nlto = \"fat\"\ncodegen-units = 1\n\n\+/// No LTO and the default codegen units: a port lives in one crate, so cross-crate inlining buys+/// nothing measurable, while rebuilds after each edit get about 4x faster (4.1s to 1.1s).+pub const RELEASE_PROFILE: &str = "[profile.release]\nopt-level = 3\nlto = false\n\n\# A crate of its own, even inside another Cargo workspace.\n[workspace]\n";fn compiler_errors(log: &str) -> String {diff --git a/src/csharp/Rec.cs b/src/csharp/Rec.csindex 77f5971..8a65c56 100644--- a/src/csharp/Rec.cs+++ b/src/csharp/Rec.cs@@ -22,6 +22,7 @@ static class FastAnythingRecstatic readonly List<string?> KeptArgs = new();static readonly List<string> Unsupported = new();static long Calls, Skipped, Ticks;+ static bool Mutates;static Func<object?[], object?>? Fn;static Type[] Types = Array.Empty<Type>();static readonly string[] Texts = { "", "ÀÉÎõü ñ", "日本語のテキスト", "emoji 👍🏽🎉", "é́", "İ ß Dž ΣΑΣ" };@@ -67,6 +68,7 @@ static class FastAnythingRecthrow;}Ticks += Stopwatch.GetTimestamp() - t;+ if (a != null && Json.Enc(args) != a) Mutates = true;if (a != null){try { Store(slot, "{\"args\":" + a + ",\"result\":" + Json.Enc(r) + "}", a); }@@ -272,7 +274,7 @@ static class FastAnythingRecforeach (var s in Unsupported) u.Append(u.Length > 1 ? "," : "").Append(Json.Str(s));double ns = Calls > 0 ? Ticks * 1e9 / Stopwatch.Frequency / Calls : 0;string meta = "{\"calls\":" + Calls + ",\"kept\":" + Kept.Count + ",\"skipped\":" + Skipped + ",\"unsupported\":" + u + "]"- + ",\"original_ns\":" + ns.ToString("R", CultureInfo.InvariantCulture) + "}";+ + ",\"mutates\":" + (Mutates ? "true" : "false") + ",\"original_ns\":" + ns.ToString("R", CultureInfo.InvariantCulture) + "}";System.IO.File.WriteAllText(Environment.GetEnvironmentVariable("FAST_ANYTHING_RECORD_META")!, meta, new UTF8Encoding(false));}}diff --git a/src/golang/rec.go b/src/golang/rec.goindex 092f387..358be5b 100644--- a/src/golang/rec.go+++ b/src/golang/rec.go@@ -28,6 +28,7 @@ var (fastAnythingRecLimit = 500fastAnythingRecWhy = map[string]bool{}fastAnythingRecFn func([]any) any+ fastAnythingRecMutates boolfastAnythingRecRng = rand.New(rand.NewSource(0xFA57)))@@ -63,6 +64,9 @@ func fastAnythingRec(args []any, fn func([]any) any) any {r := fn(args)fastAnythingRecNanos += time.Since(start).Nanoseconds()if ok {+ if after, err := fastAnythingRecJSON(args); err == nil && after != enc {+ fastAnythingRecMutates = true+ }if re, err := fastAnythingRecJSON(r); err == nil {line := `{"args":` + enc + `,"result":` + re + "}"if slot < len(fastAnythingRecKept) {@@ -446,6 +450,6 @@ outer:if fastAnythingRecCalls > 0 {perCall = float64(fastAnythingRecNanos) / float64(fastAnythingRecCalls)}- meta, _ := json.Marshal(map[string]any{"calls": fastAnythingRecCalls, "kept": len(fastAnythingRecKept), "skipped": fastAnythingRecSkip, "unsupported": why, "original_ns": perCall})+ meta, _ := json.Marshal(map[string]any{"calls": fastAnythingRecCalls, "kept": len(fastAnythingRecKept), "skipped": fastAnythingRecSkip, "unsupported": why, "original_ns": perCall, "mutates": fastAnythingRecMutates})os.WriteFile(os.Getenv("FAST_ANYTHING_RECORD_META"), meta, 0o644)}diff --git a/src/java/Rec.java b/src/java/Rec.javaindex 493b426..1214131 100644--- a/src/java/Rec.java+++ b/src/java/Rec.java@@ -8,6 +8,7 @@ final class FastAnythingRec {static final java.util.List<Object[]> keptArgs = new java.util.ArrayList<>();static final java.util.Set<String> unsupported = new java.util.LinkedHashSet<>();static long calls, skipped, nanos;+ static boolean mutates;static java.util.function.Function<Object[], Object> fn;static {@@ -42,6 +43,11 @@ final class FastAnythingRec {}nanos += System.nanoTime() - t;if (a != null) {+ try {+ if (!Json.enc(args).equals(a)) mutates = true;+ } catch (Json.Unsupported e) {+ // seen before the call: can't happen+ }try {store(slot, "{\"args\":" + a + ",\"result\":" + Json.enc(r) + "}", copy);} catch (Json.Unsupported e) {@@ -144,7 +150,7 @@ final class FastAnythingRec {java.nio.file.Files.writeString(java.nio.file.Path.of(System.getenv("FAST_ANYTHING_RECORD_OUT")), b, java.nio.charset.StandardCharsets.UTF_8);StringBuilder u = new StringBuilder("[");for (String s : unsupported) u.append(u.length() > 1 ? "," : "").append(Json.str(s));- String meta = "{\"calls\":" + calls + ",\"kept\":" + kept.size() + ",\"skipped\":" + skipped + ",\"unsupported\":" + u + "]"+ String meta = "{\"calls\":" + calls + ",\"kept\":" + kept.size() + ",\"skipped\":" + skipped + ",\"unsupported\":" + u + "],\"mutates\":" + mutates+ ",\"original_ns\":" + (calls > 0 ? (double) nanos / calls : 0) + "}";java.nio.file.Files.writeString(java.nio.file.Path.of(System.getenv("FAST_ANYTHING_RECORD_META")), meta, java.nio.charset.StandardCharsets.UTF_8);} catch (java.io.IOException e) {diff --git a/src/node/recorder.cjs b/src/node/recorder.cjsindex 2fc0ecc..3f04b33 100644--- a/src/node/recorder.cjs+++ b/src/node/recorder.cjs@@ -7,6 +7,7 @@ const meta = process.env.FAST_ANYTHING_RECORD_META;const limit = Number(process.env.FAST_ANYTHING_RECORD_LIMIT || 500);const kept = [];const unsupported = new Set();+let mutates = false;let calls = 0;let skipped = 0;let seed = 0xfa57;@@ -61,6 +62,9 @@ globalThis.__fastAnythingWrap = (fn) =>throw e;}if (c) {+ try {+ if (JSON.stringify(args.map(enc)) !== JSON.stringify(c.args)) mutates = true;+ } catch {}try {c.result = enc(result);store(slot, c);@@ -74,5 +78,5 @@ globalThis.__fastAnythingWrap = (fn) =>process.on("exit", () => {fs.writeFileSync(out, kept.map((c) => JSON.stringify(c)).join("\n") + (kept.length ? "\n" : ""));- fs.writeFileSync(meta, JSON.stringify({ calls, kept: kept.length, skipped, unsupported: [...unsupported] }));+ fs.writeFileSync(meta, JSON.stringify({ calls, kept: kept.length, skipped, unsupported: [...unsupported], mutates }));});diff --git a/src/pipeline.rs b/src/pipeline.rsindex d2e730b..7a56be2 100644--- a/src/pipeline.rs+++ b/src/pipeline.rs@@ -85,6 +85,12 @@ pub fn port(root: &Path, id: Option<&str>, samples: usize) -> Result<PortOut> {ui::step(format!("running the app again to record real calls to {}", ui::bold(&hs.id)));let app_args = ctx.state.command[1..].to_vec();let rec = lang.record(&ctx, &exe, &app_args, &hs, &dir.join("recordings.jsonl"), samples.max(1))?;+ if rec.mutates {+ bail!(+ "{} changes its arguments in place (seen while recording). A Rust port can only return a value, so it would drop those changes. Have the function return the new value instead, then scan again.",+ hs.id+ );+ }if rec.kept == 0 {let types =if rec.unsupported.is_empty() { String::new() } else { format!(" (got: {})", rec.unsupported.join(", ")) };diff --git a/src/python/runner.py b/src/python/runner.pyindex 10298b0..c7dfcf9 100644--- a/src/python/runner.py+++ b/src/python/runner.py@@ -410,6 +410,11 @@ def cmd_record(job, argv):store(slot, case)raiseif case is not None:+ try:+ if enc(list(args)) != case["args"] or {k: enc(v) for k, v in kwargs.items()} != case["kwargs"]:+ stats["mutates"] = True+ except Unsupported:+ passtry:case["result"] = enc(result)store(slot, case)@@ -435,7 +440,7 @@ def cmd_record(job, argv):f.write(json.dumps(case, ensure_ascii=False) + "\n")with open(job["meta"], "w", encoding="utf-8") as f:json.dump({"calls": stats["calls"], "kept": len(kept), "skipped": stats["skipped"],- "unsupported": sorted(stats["unsupported"])}, f)+ "unsupported": sorted(stats["unsupported"]), "mutates": stats.get("mutates", False)}, f)def cmd_verify(job, _argv):diff --git a/src/ruby/recorder.rb b/src/ruby/recorder.rbindex 8993399..0006585 100644--- a/src/ruby/recorder.rb+++ b/src/ruby/recorder.rb@@ -97,6 +97,11 @@ if ENV["FAST_ANYTHING_RECORD_OUT"]raiseendif c+ begin+ @mutates = true if enc(args) != c["args"]+ rescue Unsupported+ nil+ endbeginc["result"] = enc(result)store(slot, c)@@ -110,7 +115,7 @@ if ENV["FAST_ANYTHING_RECORD_OUT"]def saveFile.write(ENV.fetch("FAST_ANYTHING_RECORD_OUT"), @kept.map { |c| JSON.generate(c) + "\n" }.join)File.write(ENV.fetch("FAST_ANYTHING_RECORD_META"),- JSON.generate({ "calls" => @calls, "kept" => @kept.length, "skipped" => @skipped, "unsupported" => @unsupported.keys }))+ JSON.generate({ "calls" => @calls, "kept" => @kept.length, "skipped" => @skipped, "unsupported" => @unsupported.keys, "mutates" => @mutates || false }))endendend