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
fast-anything 0.5.0: edge cases in verify, no slower ports
EL4CTEO7d8121caa4ae
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5e75d12..4089bfa 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "fast-anything",- "version": "0.4.0",+ "version": "0.5.0","description": "Find the slow 5% of your app, port just that to Rust, and prove it still behaves the same.","author": {"name": "EL4CTEO"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55487e7..1ca3c8f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,10 @@# Changelog+## 0.5.0++- Edge cases in verify: NaN, ±infinity, -0.0, 0 and ±1, non-ASCII text (accents, CJK, emoji, combining marks), empty and up to 4,096-item inputs, built from the recorded calls and answered by the original. Python, Node.js/TypeScript, Ruby, Go and C++.+- A port that's right but slower per call than the original (the call into Rust costs more than the work) isn't enabled; `enable --force` overrides.+## 0.4.0- C and C++ (gcc or clang): `fast-anything scan -- clang -O2 main.c lib.c`. fast-anything builds the app itself, profiles every function for one run, and loads ports with LoadLibrary or dlopen. C ports take numbers, strings and `const T *` + length arrays; C++ ports also take std::string, vector, array, map and pair.diff --git a/Cargo.lock b/Cargo.lockindex 3b7abbc..14e8245 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -112,7 +112,7 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"[[package]]name = "fast-anything"-version = "0.4.0"+version = "0.5.0"dependencies = ["anyhow","clap",diff --git a/Cargo.toml b/Cargo.tomlindex de633f6..246cabe 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[package]name = "fast-anything"-version = "0.4.0"+version = "0.5.0"edition = "2024"rust-version = "1.88"description = "Find the slow 5% of your app, have your coding agent rewrite just that in Rust, and prove it still behaves the same."diff --git a/README.md b/README.mdindex eacd0ee..20b6da9 100644--- a/README.md+++ b/README.md@@ -52,7 +52,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 by shrinking recorded inputs (empty, tiny, random slices) and lets the original answer them. Nothing is enabled until every case matches: same values (floats within 1e-9), errors where the original errors. `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), 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.## Resultsdiff --git a/npm/fast-anything/package.json b/npm/fast-anything/package.jsonindex 53fd5c1..abf6549 100644--- a/npm/fast-anything/package.json+++ b/npm/fast-anything/package.json@@ -1,6 +1,6 @@{"name": "@el4cteo/fast-anything",- "version": "0.4.0",+ "version": "0.5.0","description": "Don't rewrite it in Rust. Rewrite the 5% that's slow: profile Python, Node, Ruby, Java, Go, PHP, C or C++ apps, port the hot functions with your coding agent, prove they behave the same.","keywords": ["rust",@@ -47,11 +47,11 @@"node": ">=18"},"optionalDependencies": {- "@el4cteo/fast-anything-win32-x64": "0.4.0",- "@el4cteo/fast-anything-linux-x64": "0.4.0",- "@el4cteo/fast-anything-linux-arm64": "0.4.0",- "@el4cteo/fast-anything-darwin-arm64": "0.4.0",- "@el4cteo/fast-anything-darwin-x64": "0.4.0"+ "@el4cteo/fast-anything-win32-x64": "0.5.0",+ "@el4cteo/fast-anything-linux-x64": "0.5.0",+ "@el4cteo/fast-anything-linux-arm64": "0.5.0",+ "@el4cteo/fast-anything-darwin-arm64": "0.5.0",+ "@el4cteo/fast-anything-darwin-x64": "0.5.0"},"publishConfig": {"access": "public"diff --git a/src/cfamily/rec.hpp b/src/cfamily/rec.hppindex 87d8fe4..a809d95 100644--- a/src/cfamily/rec.hpp+++ b/src/cfamily/rec.hpp@@ -24,6 +24,9 @@ struct State {bool inside = false;std::vector<std::string> kept, derived;long long calls = 0, skipped = 0, nanos = 0, derive_started = 0;+ size_t edges = 0, edge_calls = 0;+ std::map<std::string, bool> seen;+ std::map<size_t, bool> grown;size_t limit = 0;unsigned long long rng = 0xFA57;};@@ -64,7 +67,78 @@ inline bool derive_ok() {const char *d = std::getenv("FAST_ANYTHING_RECORD_DERIVE");if (d && d[0] == '0') return false;if (!s.derive_started) s.derive_started = now();- return s.derived.size() < 200 && now() - s.derive_started < 3000000000LL;+ return s.derived.size() < 200 + s.edges && now() - s.derive_started < 3000000000LL;+}+inline bool edge_ok() {+ auto &s = st();+ const char *d = std::getenv("FAST_ANYTHING_RECORD_DERIVE");+ if (d && d[0] == '0') return false;+ if (!s.derive_started) s.derive_started = now();+ return s.edges < 100 && now() - s.derive_started < 1500000000LL;+}+inline long long edge_left() { return 1500000000LL - (now() - st().derive_started); }++// Edge cases: inputs where ports and originals tend to part ways, of the same type as the recorded value.+template <class T> typename std::enable_if<!std::is_arithmetic<T>::value, std::vector<T>>::type edges(const T &) { return {}; }+template <class T> typename std::enable_if<std::is_arithmetic<T>::value, std::vector<T>>::type edges(const T &v) {+ std::vector<T> out;+ if (std::is_same<T, bool>::value) return out;+ std::vector<double> xs = {0, 1};+ if (std::is_signed<T>::value) xs.push_back(-1);+ if (std::is_floating_point<T>::value) xs.push_back(sizeof(T) >= 8 ? 1e300 : 1e30);+ for (double x : xs)+ if ((T) x != v) out.push_back((T) x);+ return out;+}+inline std::vector<std::string> edges(const std::string &v) {+ size_t mid = 0, chars = 0;+ for (size_t i = 0; i < v.size(); i++) chars += ((unsigned char) v[i] & 0xC0) != 0x80;+ for (size_t i = 0, c = 0; i <= v.size(); i++) {+ if (i == v.size() || ((unsigned char) v[i] & 0xC0) != 0x80) {+ if (c == chars / 2) { mid = i; break; }+ c++;+ }+ }+ // an accent, CJK, an emoji with a modifier, a combining mark (UTF-8 bytes)+ const std::string a = "\xC3\xA9", cjk = "\xE6\x97\xA5\xE6\x9C\xAC", emoji = "\xF0\x9F\x91\x8D\xF0\x9F\x8F\xBD", comb = "e\xCC\x81";+ return {v.substr(0, mid) + a + v.substr(mid), v + cjk, emoji + v, v + comb, ""};+}+template <class T, class Al> std::vector<std::vector<T, Al>> edges(const std::vector<T, Al> &v) {+ std::vector<std::vector<T, Al>> out;+ if (v.empty()) return out;+ out.emplace_back();+ auto es = edges(v[0]);+ for (size_t k = 0; k < es.size() && k < 4; k++) {+ out.push_back(v);+ out.back()[0] = es[k];+ }+ return out;+}+// A short version of a recorded value, so edge cases stay cheap when the real inputs are big.+template <class T> T small(const T &v) { return v; }+inline std::string small(const std::string &v) {+ size_t i = 0, chars = 0;+ for (; i < v.size(); i++)+ if (((unsigned char) v[i] & 0xC0) != 0x80 && chars++ == 64) break;+ return v.substr(0, i);+}+template <class T, class Al> std::vector<T, Al> small(const std::vector<T, Al> &v) {+ return v.size() > 8 ? std::vector<T, Al>(v.begin(), v.begin() + 8) : v;+}+template <class Tup, size_t... I> Tup small_tuple(const Tup &t, std::index_sequence<I...>) { return Tup(small(std::get<I>(t))...); }++template <class T> bool bigger(const T &, int, T &) { return false; }+inline bool bigger(const std::string &v, int factor, std::string &out) {+ if (v.empty() || v.size() * (size_t) factor > 4096 * 4) return false;+ out.clear();+ for (int k = 0; k < factor; k++) out += v;+ return true;+}+template <class T, class Al> bool bigger(const std::vector<T, Al> &v, int factor, std::vector<T, Al> &out) {+ if (v.empty() || v.size() * (size_t) factor > 4096) return false;+ out.clear();+ for (int k = 0; k < factor; k++) out.insert(out.end(), v.begin(), v.end());+ return true;}static const size_t SLICES[] = {0, 1, 2, 3, 5, 8, 13, 21, 34, 55};@@ -121,7 +195,63 @@ template <size_t I, class F, class Tup, class Seq> void derive_one(F &f, const T}}}+template <class F, class Tup, class Seq> long long edge_try(F &f, const Tup &next_args, Seq seq) {+ std::string in = "[";+ if (!encode_tuple(in, next_args, seq)) return -1;+ in += "]";+ auto &s = st();+ if (s.seen[in]) return -1;+ s.seen[in] = true;+ try {+ Tup copy = next_args;+ long long t = now();+ auto r = apply(f, copy, seq);+ long long took = now() - t;+ std::string out;+ if (!enc(out, r)) return -1;+ s.derived.push_back("{\"args\":" + in + ",\"result\":" + out + ",\"derived\":\"edge\"}");+ s.edges++;+ return took;+ } catch (...) {+ return -1; // outside the function's domain: not a fair test+ }+}+template <size_t I, class F, class Tup, class Seq> void edge_one(F &f, const Tup &args, Seq seq) {+ const Tup base = small_tuple(args, seq);+ for (auto &e : edges(std::get<I>(base))) {+ if (!edge_ok()) return;+ Tup next_args = base;+ std::get<I>(next_args) = e;+ edge_try(f, next_args, seq);+ }+ auto &s = st();+ typename std::decay<decltype(std::get<I>(args))>::type big;+ if (s.grown[I] || !bigger(std::get<I>(base), 4, big)) return;+ // much bigger inputs, only while their time (assumed quadratic) fits the budget+ s.grown[I] = true;+ long long took;+ try {+ Tup copy = base;+ long long t = now();+ apply(f, copy, seq);+ took = now() - t;+ } catch (...) {+ return;+ }+ // 4x bigger each step, from the short version of the input, up to 4096 items+ for (int factor : {4, 16, 64, 256, 512}) {+ if (!edge_ok() || !bigger(std::get<I>(base), factor, big) || took * 16 > edge_left() / 2) return;+ Tup next_args = base;+ std::get<I>(next_args) = big;+ took = edge_try(f, next_args, seq);+ if (took < 0) return;+ }+}template <class F, class Tup, size_t... I> void derive_all(F &f, const Tup &args, std::index_sequence<I...> seq) {+ if (st().edge_calls++ < 20) {+ int edge_dummy[] = {0, (edge_one<I>(f, args, seq), 0)...};+ (void) edge_dummy;+ }int dummy[] = {0, (derive_one<I>(f, args, seq), 0)...};(void) dummy;}diff --git a/src/golang/rec.go b/src/golang/rec.goindex 776484c..092f387 100644--- a/src/golang/rec.go+++ b/src/golang/rec.go@@ -225,6 +225,99 @@ func fastAnythingRecVariants(v any) []any {return out}+// Non-ASCII text that ports often get wrong: an accent, CJK, an emoji with a modifier, a combining mark.+var fastAnythingRecNonASCII = []string{"é", "日本", "👍🏽", "é"}++// Inputs where ports and originals tend to part ways, of the same type as the recorded value.+func fastAnythingRecEdges(v any) []any {+ rv := reflect.ValueOf(v)+ if !rv.IsValid() {+ return nil+ }+ out := []any{}+ put := func(set func(reflect.Value)) {+ n := reflect.New(rv.Type()).Elem()+ set(n)+ if !reflect.DeepEqual(n.Interface(), v) {+ out = append(out, n.Interface())+ }+ }+ switch rv.Kind() {+ case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:+ for _, x := range []int64{0, 1, -1} {+ put(func(n reflect.Value) { n.SetInt(x) })+ }+ case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:+ for _, x := range []uint64{0, 1} {+ put(func(n reflect.Value) { n.SetUint(x) })+ }+ case reflect.Float32, reflect.Float64:+ for _, x := range []float64{0, 1, -1, 1e300, 5e-324} {+ put(func(n reflect.Value) { n.SetFloat(x) })+ }+ case reflect.String:+ s := []rune(rv.String())+ mid := len(s) / 2+ na := fastAnythingRecNonASCII+ for _, x := range []string{string(s[:mid]) + na[0] + string(s[mid:]), string(s) + na[1], na[2] + string(s), string(s) + na[3], ""} {+ put(func(n reflect.Value) { n.SetString(x) })+ }+ case reflect.Slice:+ if rv.Len() == 0 {+ break+ }+ out = append(out, reflect.MakeSlice(rv.Type(), 0, 0).Interface())+ for k, e := range fastAnythingRecEdges(rv.Index(0).Interface()) {+ if k == 4 {+ break+ }+ c := fastAnythingRecCopy(rv)+ c.Index(0).Set(reflect.ValueOf(e))+ out = append(out, c.Interface())+ }+ }+ return out+}++// A short version of a recorded value, so edge cases stay cheap when the real inputs are big.+func fastAnythingRecSmall(v any) any {+ rv := reflect.ValueOf(v)+ if !rv.IsValid() {+ return v+ }+ switch rv.Kind() {+ case reflect.Slice:+ if rv.Len() > 8 {+ return fastAnythingRecCopy(rv.Slice(0, 8)).Interface()+ }+ case reflect.String:+ if r := []rune(rv.String()); len(r) > 64 {+ n := reflect.New(rv.Type()).Elem()+ n.SetString(string(r[:64]))+ return n.Interface()+ }+ }+ return v+}++// The value repeated factor times (nil past 4096 items or characters).+func fastAnythingRecBigger(v any, factor int) any {+ rv := reflect.ValueOf(v)+ if !rv.IsValid() || (rv.Kind() != reflect.String && rv.Kind() != reflect.Slice) || rv.Len() == 0 || rv.Len()*factor > 4096 {+ return nil+ }+ if rv.Kind() == reflect.String {+ n := reflect.New(rv.Type()).Elem()+ n.SetString(strings.Repeat(rv.String(), factor))+ return n.Interface()+ }+ out := reflect.MakeSlice(rv.Type(), 0, rv.Len()*factor)+ for k := 0; k < factor; k++ {+ out = reflect.AppendSlice(out, fastAnythingRecCopy(rv))+ }+ return out.Interface()+}+func fastAnythingRecSave() {fastAnythingRecMu.Lock()defer fastAnythingRecMu.Unlock()@@ -240,6 +333,78 @@ func fastAnythingRecSave() {}()return fastAnythingRecFn(a), true}+ // Edge cases first, from a sample of recorded calls: special numbers, non-ASCII text, empty and+ // much bigger inputs. The original answers them; inputs it panics on are skipped.+ edgeLeft := func() time.Duration { return 1500*time.Millisecond - time.Since(start) }+ attempt := func(next []any) (time.Duration, bool) {+ enc, err := fastAnythingRecJSON(next)+ if err != nil || seen[enc] {+ return 0, false+ }+ seen[enc] = true+ t := time.Now()+ r, ok := call(fastAnythingRecCopy(reflect.ValueOf(next)).Interface().([]any))+ took := time.Since(t)+ if !ok {+ return 0, false+ }+ re, err := fastAnythingRecJSON(r)+ if err != nil {+ return 0, false+ }+ derived = append(derived, `{"args":`+enc+`,"result":`+re+`,"derived":"edge"}`)+ return took, true+ }+ grown := map[int]bool{}+ sampled := 0+edges:+ for _, args := range fastAnythingRecArgs {+ if args == nil || fastAnythingRecFn == nil {+ continue+ }+ if sampled++; sampled > 20 {+ break+ }+ base := make([]any, len(args))+ for i := range args {+ base[i] = fastAnythingRecSmall(args[i])+ }+ for i := range args {+ for _, e := range fastAnythingRecEdges(base[i]) {+ if len(derived) >= 100 || edgeLeft() <= 0 {+ break edges+ }+ next := fastAnythingRecCopy(reflect.ValueOf(base)).Interface().([]any)+ next[i] = e+ attempt(next)+ }+ if grown[i] || fastAnythingRecBigger(base[i], 4) == nil {+ continue+ }+ // much bigger inputs, only while their time (assumed quadratic) fits the budget+ grown[i] = true+ t := time.Now()+ if _, ok := call(fastAnythingRecCopy(reflect.ValueOf(base)).Interface().([]any)); !ok {+ continue+ }+ took := time.Since(t)+ // 4x bigger each step, from the short version of the input, up to 4096 items or characters+ for _, factor := range []int{4, 16, 64, 256, 512} {+ big := fastAnythingRecBigger(base[i], factor)+ if big == nil || len(derived) >= 100 || took*16 > edgeLeft()/2 {+ break+ }+ next := fastAnythingRecCopy(reflect.ValueOf(base)).Interface().([]any)+ next[i] = big+ var ok bool+ if took, ok = attempt(next); !ok {+ break+ }+ }+ }+ }+ edgeCount := len(derived)+ start = time.Now()outer:for _, args := range fastAnythingRecArgs {if args == nil || fastAnythingRecFn == nil {@@ -247,7 +412,7 @@ outer:}for i := range args {for _, smaller := range fastAnythingRecVariants(args[i]) {- if len(derived) >= 200 || time.Since(start) > 3*time.Second {+ if len(derived) >= 200+edgeCount || time.Since(start) > 3*time.Second {break outer}next := fastAnythingRecCopy(reflect.ValueOf(args)).Interface().([]any)diff --git a/src/main.rs b/src/main.rsindex 2a9a5f3..f03431a 100644--- a/src/main.rs+++ b/src/main.rs@@ -145,7 +145,9 @@ fn run(cmd: Cmd, root: &Path) -> Result<()> {if !v.ok() {bail!("{agent} couldn't get {} right in {attempts} attempts", out.id);}- show::next(&format!("fast-anything enable {}", out.id));+ if !v.slower() {+ show::next(&format!("fast-anything enable {}", out.id));+ }}Ok(())}@@ -155,7 +157,9 @@ fn run(cmd: Cmd, root: &Path) -> Result<()> {if !v.ok() {bail!("{id} doesn't match the original yet");}- show::next(&format!("fast-anything enable {id}"));+ if !v.slower() {+ show::next(&format!("fast-anything enable {id}"));+ }Ok(())}Cmd::Enable { id, force } => {diff --git a/src/native.rs b/src/native.rsindex b069be2..fad53db 100644--- a/src/native.rs+++ b/src/native.rs@@ -188,7 +188,7 @@ Only edit files in this folder. Don't touch the {label} project.\n\n\## Real calls\n\n\fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON. A few:\n\n{fence}\n{samples}\n{fence}\n\n\## Rules\n\n\-- Same result for every input, edge cases included: empty input, zero, negatives, unicode.\n\+- Same result for every input, edge cases included: empty input, zero, negatives, non-ASCII text, very long input. verify tests these too.\n\{rules}\- Return `Err(message)` where the original would fail.\n\- Make it fast: no needless allocation, borrow, `with_capacity`, fast paths for common cases. Threads are fine if the result is the same.\n\@@ -312,14 +312,16 @@ pub fn replay(job_path: &Path) -> Result<()> {let text = fs::read_to_string(&job.cases).context("reading recordings.jsonl")?;let cases: Vec<Value> =text.lines().filter(|l| !l.trim().is_empty()).filter_map(|l| serde_json::from_str(l).ok()).collect();- let (mut passed, mut failed, mut derived) = (0, 0, 0);+ let (mut passed, mut failed, mut derived, mut edges) = (0, 0, 0, 0);let mut failures = Vec::new();let mut inputs = Vec::new();for (i, case) in cases.iter().enumerate() {let input = serde_json::to_vec(&case["args"])?;let is_derived = case.get("derived").is_some();+ let is_edge = case["derived"] == "edge";if is_derived {derived += 1;+ edges += usize::from(is_edge);} else {inputs.push(input.clone());}@@ -341,7 +343,18 @@ pub fn replay(job_path: &Path) -> Result<()> {case["args"].as_array().map(|a| a.iter().map(|v| show(v, 80)).collect()).unwrap_or_default();failures.push(Failure {case: i,- call: format!("{}{}({})", if is_derived { "(derived) " } else { "" }, job.func, args.join(", ")),+ call: format!(+ "{}{}({})",+ if is_edge {+ "(edge) "+ } else if is_derived {+ "(derived) "+ } else {+ ""+ },+ job.func,+ args.join(", ")+ ),expected,got: match got {Ok(v) => show(&v, 160),@@ -351,7 +364,7 @@ pub fn replay(job_path: &Path) -> Result<()> {}}- let mut v = Verify { total: cases.len(), derived, passed, failed, failures, ..Verify::default() };+ let mut v = Verify { total: cases.len(), derived, edges, passed, failed, failures, ..Verify::default() };let original_ns = fs::read_to_string(&job.meta).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok())diff --git a/src/node.rs b/src/node.rsindex c1841c8..83515f2 100644--- a/src/node.rs+++ b/src/node.rs@@ -331,7 +331,7 @@ Only edit files in this folder. Don't touch the JavaScript project.\n\n\{helpers}## Real calls\n\n\fast-anything recorded {recorded} real calls (out of {seen} while the app ran). A few:\n\n{fence}\n{samples}\n{fence}\n\n\## Rules\n\n\-- Same result for every input, edge cases included: empty input, zero, negatives, NaN, unicode.\n\+- Same result for every input, edge cases included: empty input, zero, negatives, NaN and infinity, non-ASCII text, very long input. verify tests these too.\n\- JavaScript strings are UTF-16: `.length`, indexing and `charCodeAt` count UTF-16 code units. \Use `s.encode_utf16()` for anything index- or length-based (bytes are fine after checking `is_ascii()`).\n\- JavaScript numbers are f64. Integer math is exact only up to 2^53; use `f64` unless the values are clearly small integers.\n\diff --git a/src/node/runner.mjs b/src/node/runner.mjsindex 1c8eea9..8206d1b 100644--- a/src/node/runner.mjs+++ b/src/node/runner.mjs@@ -338,11 +338,103 @@ function variants(value, rand) {);}-/** Extra test cases: recorded calls with smaller inputs, answered by the original itself. */+const NON_ASCII = ["\u{e9}", "\u{65e5}\u{672c}", "\u{1f44d}\u{1f3fd}", "e\u{301}"];+const BIG = 4096; // the longest "huge" input, in items or characters+const EDGE_SAMPLE = 20;+const EDGE_LIMIT = 100;+const GROW = [4, 16, 64, 256, 512]; // how much bigger, step by step, than the short version of an input++/** Inputs where ports and originals tend to part ways, of the same type as the recorded value. */+function edges(v) {+ if (typeof v === "number") {+ return Number.isInteger(v) ? [0, 1, -1].filter((x) => x !== v) : [NaN, Infinity, -Infinity, -0, 0, 1e308, 5e-324];+ }+ if (typeof v === "bigint") return [0n, 1n, -1n].filter((x) => x !== v);+ if (typeof v === "string") {+ const cs = [...v];+ const mid = cs.length >> 1;+ return [cs.slice(0, mid).join("") + NON_ASCII[0] + cs.slice(mid).join(""), v + NON_ASCII[1], NON_ASCII[2] + v, v + NON_ASCII[3], ""];+ }+ if (Array.isArray(v) && v.length) return [[], ...edges(v[0]).slice(0, 4).map((e) => [e, ...v.slice(1)])];+ return [];+}++/** A short version of a recorded value, so edge cases stay cheap when the real inputs are big. */+function small(v) {+ if (Array.isArray(v)) return v.slice(0, 8);+ if (typeof v === "string") return [...v].slice(0, 64).join("");+ return v;+}++/** The value repeated factor times (null past BIG items or characters). */+function bigger(v, factor) {+ if (!(typeof v === "string" || Array.isArray(v)) || !v.length || v.length * factor > BIG) return null;+ return typeof v === "string" ? v.repeat(factor) : Array.from({ length: factor }, () => v).flat(1);+}++/** Edge cases from a sample of recorded calls: special numbers, non-ASCII text, empty and much bigger+ * inputs. The original answers them; inputs it rejects are skipped. */+function deriveEdges(original, cases, budget, limit) {+ const derived = [];+ const seen = new Set();+ const start = performance.now();+ const left = () => budget - (performance.now() - start) / 1000;+ const attempt = (args) => {+ let encoded;+ let took;+ try {+ encoded = { args: args.map(enc) };+ const key = JSON.stringify(encoded);+ if (seen.has(key)) return null;+ seen.add(key);+ const t = performance.now();+ const r = original(...structuredClone(args));+ took = (performance.now() - t) / 1000;+ encoded.result = enc(r);+ } catch {+ return null; // outside the function's domain: not a fair test+ }+ encoded.derived = "edge";+ derived.push(encoded);+ return took;+ };+ const grown = new Set();+ for (const c of cases.filter((c) => !("raises" in c)).slice(0, EDGE_SAMPLE)) {+ const args = dec(c.args);+ const base = args.map(small);+ for (let i = 0; i < args.length; i++) {+ for (const e of edges(base[i])) {+ if (derived.length >= limit || left() <= 0) return derived;+ attempt(base.map((a, j) => (j === i ? e : a)));+ }+ if (grown.has(i) || bigger(base[i], 4) === null) continue;+ // much bigger inputs, only while their time (assumed quadratic) fits the budget+ grown.add(i);+ let took;+ try {+ const t = performance.now();+ original(...structuredClone(base));+ took = (performance.now() - t) / 1000;+ } catch {+ continue;+ }+ for (const factor of GROW) {+ const big = bigger(base[i], factor);+ if (big === null || derived.length >= limit || took * 16 > left() / 2) break;+ took = attempt(base.map((a, j) => (j === i ? big : a)));+ if (took === null) break;+ }+ }+ }+ return derived;+}++/** Extra test cases: edge cases, then recorded calls with smaller inputs, answered by the original. */function derive(original, cases, budget, limit) {let seed = 0xfa57;const rand = () => ((seed = (Math.imul(seed, 1103515245) + 12345) >>> 0) / 4294967296);- const derived = [];+ const derived = deriveEdges(original, cases, budget / 2, EDGE_LIMIT);+ limit += derived.length;const seen = new Set();const start = performance.now();for (const c of cases) {@@ -421,7 +513,7 @@ async function verify(job) {const recorded = cases.length;const derived = typeof original === "function" ? derive(original, cases, job.derive_budget ?? 3, job.derive_limit ?? 200) : [];cases.push(...derived);- const report = { total: cases.length, derived: derived.length, passed: 0, failed: 0, failures: [] };+ const report = { total: cases.length, derived: derived.length, edges: derived.filter((c) => c.derived === "edge").length, passed: 0, failed: 0, failures: [] };const calls = [];cases.forEach((c, i) => {const args = dec(c.args);@@ -448,7 +540,7 @@ async function verify(job) {if (report.failures.length < 8)report.failures.push({case: i,- call: (c.derived ? "(derived) " : "") + job.func + "(" + args.map((a) => show(a, 80)).join(", ") + ")",+ call: (c.derived === "edge" ? "(edge) " : c.derived ? "(derived) " : "") + job.func + "(" + args.map((a) => show(a, 80)).join(", ") + ")",expected,got: err === null ? show(got) : "threw " + (err?.name ?? "Error") + ": " + show(String(err?.message ?? err), 200),});diff --git a/src/pipeline.rs b/src/pipeline.rsindex df0e3bd..d2e730b 100644--- a/src/pipeline.rs+++ b/src/pipeline.rs@@ -163,6 +163,11 @@ pub fn verify(root: &Path, id: Option<&str>) -> Result<(String, Verify)> {Ok((id, v))}+/// 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"+}+pub fn enable(root: &Path, id: Option<&str>, force: bool) -> Result<String> {let mut ctx = Ctx::open(root)?;let id = ctx.resolve_port(id)?;@@ -171,6 +176,9 @@ pub fn enable(root: &Path, id: Option<&str>, force: bool) -> Result<String> {if !verified && !force {bail!("{id} hasn't passed verify yet: run fast-anything verify {id} (or --force)");}+ 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());+ }port.lang.enable(&ctx, &port)?;if let Some(p) = ctx.state.ports.get_mut(&id) {p.enabled = true;@@ -300,7 +308,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() {+ 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)?;ui::ok(format!("{} now runs in Rust", ui::bold(id)));enabled += 1;@@ -310,7 +320,7 @@ pub fn go());}}- ensure!(enabled > 0, "no port passed verification");+ ensure!(enabled > 0, "no port both passed verification and ran faster");show::bench(&bench(root, runs)?);show::report(&report(root)?);Ok(())diff --git a/src/python.rs b/src/python.rsindex 834d595..a36eb48 100644--- a/src/python.rs+++ b/src/python.rs@@ -347,7 +347,7 @@ Only edit files in this folder. Don't touch the Python project.\n\n\{helpers}## Real calls\n\n\fast-anything recorded {recorded} real calls (out of {seen} while the app ran). A few:\n\n{fence}\n{samples}\n{fence}\n\n\## Rules\n\n\-- Same result for every input, edge cases included: empty input, zero, negatives, unicode.\n\+- Same result for every input, edge cases included: empty input, zero, negatives, NaN and infinity, non-ASCII text, very long input. verify tests these too.\n\- Python `str` indexes by Unicode code point: use `.chars()` (or bytes only after checking `is_ascii()`).\n\- Python ints don't overflow. `i64` is fine unless the recorded values are bigger.\n\- Float results are compared with a relative tolerance of 1e-9. Keep the same order of operations.\n\diff --git a/src/python/runner.py b/src/python/runner.pyindex c15c2b2..9402f0a 100644--- a/src/python/runner.py+++ b/src/python/runner.py@@ -459,7 +459,8 @@ def cmd_verify(job, _argv):derived = derive(original, cases, job.get("derive_budget", 3.0), job.get("derive_limit", 200))cases += derived- report = {"total": len(cases), "derived": len(derived), "passed": 0, "failed": 0, "failures": []}+ report = {"total": len(cases), "derived": len(derived), "passed": 0, "failed": 0, "failures": [],+ "edges": sum(1 for c in derived if c.get("derived") == "edge")}calls = []for i, case in enumerate(cases):args = dec(case["args"])@@ -484,7 +485,7 @@ def cmd_verify(job, _argv):shown = [show(a, 80) for a in args] + [k + "=" + show(v, 80) for k, v in kwargs.items()]report["failures"].append({"case": i,- "call": ("(derived) " if case.get("derived") else "") + job["func"] + "(" + ", ".join(shown) + ")",+ "call": {"edge": "(edge) ", True: "(derived) "}.get(case.get("derived"), "") + job["func"] + "(" + ", ".join(shown) + ")","expected": expected,"got": show(got) if err is None else "raised " + type(err).__name__ + ": " + show(str(err), 200),})@@ -517,12 +518,115 @@ def variants(value, rng):return out+NON_ASCII = ("\u00e9", "\u65e5\u672c", "\U0001f44d\U0001f3fd", "e\u0301")+BIG = 4096 # the longest "huge" input, in items or characters+EDGE_SAMPLE, EDGE_LIMIT = 20, 100+GROW = (4, 16, 64, 256, 512) # how much bigger, step by step, than the short version of an input+++def edges(value):+ """Inputs where ports and originals tend to part ways, of the same type as the recorded value."""+ if isinstance(value, bool):+ return []+ if isinstance(value, int):+ return [x for x in (0, 1, -1) if x != value]+ if isinstance(value, float):+ return [math.nan, math.inf, -math.inf, -0.0, 0.0, 1e308, 5e-324]+ if isinstance(value, str):+ mid = len(value) // 2+ return [value[:mid] + NON_ASCII[0] + value[mid:], value + NON_ASCII[1], NON_ASCII[2] + value,+ value + NON_ASCII[3], ""]+ if isinstance(value, bytes):+ return [b"", value + b"\x00", b"\xff" + value]+ if isinstance(value, (list, tuple)) and value:+ out = [type(value)()]+ for e in edges(value[0])[:4]:+ out.append((e,) + tuple(value[1:]) if isinstance(value, tuple) else [e] + list(value[1:]))+ return out+ return []+++def small(value):+ """A short version of a recorded value, so edge cases stay cheap when the real inputs are big."""+ if isinstance(value, (list, tuple)):+ return value[:8]+ if isinstance(value, (str, bytes)):+ return value[:64]+ return value+++def bigger(value, factor):+ """The value repeated factor times (None past BIG items or characters)."""+ if not isinstance(value, (list, tuple, str, bytes)) or not value or len(value) * factor > BIG:+ return None+ return value * factor+++def derive_edges(original, cases, budget, limit):+ """Edge cases built from a sample of recorded calls: special numbers, non-ASCII text, empty and+ much bigger inputs. The original answers them; inputs it rejects are skipped."""+ import copy++ derived, seen, start = [], set(), time.perf_counter()++ def left():+ return budget - (time.perf_counter() - start)++ def attempt(args, kwargs):+ try:+ encoded = {"args": enc(args), "kwargs": {k: enc(v) for k, v in kwargs.items()}}+ key = json.dumps(encoded, sort_keys=True)+ if key in seen:+ return None+ seen.add(key)+ t = time.perf_counter()+ result = original(*copy.deepcopy(args), **copy.deepcopy(kwargs))+ took = time.perf_counter() - t+ encoded["result"] = enc(result)+ except Exception:+ return None # outside the function's domain: not a fair test+ encoded["derived"] = "edge"+ derived.append(encoded)+ return took++ grown = set()+ for case in [c for c in cases if "raises" not in c][:EDGE_SAMPLE]:+ args = dec(case["args"])+ kwargs = {k: dec(v) for k, v in case.get("kwargs", {}).items()}+ base = [small(a) for a in args]+ for i, arg in enumerate(args):+ for e in edges(base[i]):+ if len(derived) >= limit or left() <= 0:+ return derived+ attempt(base[:i] + [e] + base[i + 1:], kwargs)+ if i in grown or bigger(base[i], 4) is None:+ continue+ # much bigger inputs, only while their time (assumed quadratic) fits the budget+ grown.add(i)+ try:+ t = time.perf_counter()+ original(*copy.deepcopy(base), **copy.deepcopy(kwargs))+ took = time.perf_counter() - t+ except Exception:+ continue+ for factor in GROW:+ big = bigger(base[i], factor)+ if big is None or len(derived) >= limit or took * 16 > left() / 2:+ break+ took = attempt(base[:i] + [big] + base[i + 1:], kwargs)+ if took is None:+ break+ return derived++def derive(original, cases, budget, limit):- """Extra test cases: recorded calls with smaller inputs, answered by the original itself."""+ """Extra test cases: edge cases, then recorded calls with smaller inputs, answered by the original."""import copy+ edge_cases = derive_edges(original, cases, budget / 2, EDGE_LIMIT)rng = random.Random(0xFA57)- derived, seen, start = [], set(), time.perf_counter()+ derived, seen, start = edge_cases, set(), time.perf_counter()+ limit += len(edge_cases)for case in cases:if "raises" in case:continuediff --git a/src/ruby.rs b/src/ruby.rsindex b415faf..a9d291f 100644--- a/src/ruby.rs+++ b/src/ruby.rs@@ -192,7 +192,7 @@ Only edit files in this folder. Don't touch the Ruby project.\n\n\## Real calls\n\n\fast-anything recorded {recorded} real calls (out of {seen} while the app ran). Arguments arrive as JSON. A few:\n\n{fence}\n{samples}\n{fence}\n\n\## Rules\n\n\-- Same result for every input, edge cases included: empty input, zero, negatives, unicode.\n\+- Same result for every input, edge cases included: empty input, zero, negatives, NaN and infinity, non-ASCII text, very long input. verify tests these too.\n\- Change the `serde_json::Value` parameter and return types to concrete ones: they're deserialized for you.\n\- Ruby strings index by character: use `.chars()` (or bytes only after checking `is_ascii()`).\n\- Ruby Integers don't overflow. `i64` is fine unless the recorded values are bigger. Keep Integer vs Float as Ruby has it.\n\diff --git a/src/ruby/runner.rb b/src/ruby/runner.rbindex 00bfd16..cdc326b 100644--- a/src/ruby/runner.rb+++ b/src/ruby/runner.rb@@ -230,9 +230,104 @@ def variants(value, rng)endend+NON_ASCII = ["\u{e9}", "\u{65e5}\u{672c}", "\u{1f44d}\u{1f3fd}", "e\u{301}"].freeze+BIG = 4096 # the longest "huge" input, in items or characters+EDGE_SAMPLE = 20+EDGE_LIMIT = 100+GROW = [4, 16, 64, 256, 512].freeze # how much bigger, step by step, than the short version of an input++# Inputs where ports and originals tend to part ways, of the same type as the recorded value.+def edges(value)+ case value+ when Integer then [0, 1, -1].reject { |x| x == value }+ when Float then [Float::NAN, Float::INFINITY, -Float::INFINITY, -0.0, 0.0, 1e308, 5e-324]+ when String+ mid = value.length / 2+ [value[0, mid] + NON_ASCII[0] + value[mid..], value + NON_ASCII[1], NON_ASCII[2] + value, value + NON_ASCII[3], ""]+ when Array+ return [] if value.empty?++ [[]] + edges(value[0]).first(4).map { |e| [e] + value[1..] }+ else []+ end+end++# A short version of a recorded value, so edge cases stay cheap when the real inputs are big.+def small(value)+ case value+ when Array then value.first(8)+ when String then value[0, 64]+ else value+ end+end++# The value repeated factor times (nil past BIG items or characters).+def bigger(value, factor)+ return nil unless (value.is_a?(Array) || value.is_a?(String)) && !value.empty? && value.length * factor <= BIG++ value * factor+end++# Edge cases from a sample of recorded calls: special numbers, non-ASCII text, empty and much bigger+# inputs. The original answers them; inputs it rejects are skipped.+def derive_edges(original, cases, budget, limit)+ derived = []+ seen = {}+ clock = Process::CLOCK_MONOTONIC+ started = Process.clock_gettime(clock)+ left = -> { budget - (Process.clock_gettime(clock) - started) }+ attempt = lambda do |args|+ encoded = { "args" => FastAnything.enc(args) }+ key = JSON.generate(encoded)+ return nil if seen[key]++ seen[key] = true+ t = Process.clock_gettime(clock)+ encoded["result"] = FastAnything.enc(original.call(*Marshal.load(Marshal.dump(args))))+ took = Process.clock_gettime(clock) - t+ encoded["derived"] = "edge"+ derived << encoded+ took+ rescue StandardError+ nil # outside the function's domain: not a fair test+ end+ grown = {}+ cases.reject { |c| c.key?("raises") }.first(EDGE_SAMPLE).each do |c|+ args = FastAnything.dec(c["args"])+ base = args.map { |a| small(a) }+ args.each_with_index do |arg, i|+ edges(base[i]).each do |e|+ return derived if derived.length >= limit || left.call <= 0++ attempt.call(base.each_with_index.map { |a, j| j == i ? e : a })+ end+ next if grown[i] || bigger(base[i], 4).nil?++ # much bigger inputs, only while their time (assumed quadratic) fits the budget+ grown[i] = true+ took = begin+ t = Process.clock_gettime(clock)+ original.call(*Marshal.load(Marshal.dump(base)))+ Process.clock_gettime(clock) - t+ rescue StandardError+ next+ end+ GROW.each do |factor|+ big = bigger(base[i], factor)+ break if big.nil? || derived.length >= limit || took * 16 > left.call / 2++ took = attempt.call(base.each_with_index.map { |a, j| j == i ? big : a })+ break if took.nil?+ end+ end+ end+ derived+end+def derive(original, cases, budget, limit)rng = Random.new(0xFA57)- derived = []+ derived = derive_edges(original, cases, budget / 2.0, EDGE_LIMIT)+ limit += derived.lengthseen = {}started = Process.clock_gettime(Process::CLOCK_MONOTONIC)cases.each do |c|@@ -301,7 +396,8 @@ def cmd_verify(job, _argv)recorded = cases.lengthderived = derive(original, cases, job.fetch("derive_budget", 3.0), job.fetch("derive_limit", 200))cases += derived- report = { "total" => cases.length, "derived" => derived.length, "passed" => 0, "failed" => 0, "failures" => [] }+ report = { "total" => cases.length, "derived" => derived.length, "edges" => derived.count { |c| c["derived"] == "edge" },+ "passed" => 0, "failed" => 0, "failures" => [] }calls = []cases.each_with_index do |c, i|args = FastAnything.dec(c["args"])@@ -329,7 +425,7 @@ def cmd_verify(job, _argv)report["failures"] << {"case" => i,- "call" => "#{c["derived"] ? "(derived) " : ""}#{job["func"]}(#{args.map { |a| show(a, 80) }.join(", ")})",+ "call" => "#{{ "edge" => "(edge) ", true => "(derived) " }.fetch(c["derived"], "")}#{job["func"]}(#{args.map { |a| show(a, 80) }.join(", ")})","expected" => expected,"got" => err ? "raised #{err.class}: #{show(err.message, 200)}" : show(got),}diff --git a/src/show.rs b/src/show.rsindex 5d96c29..643600a 100644--- a/src/show.rs+++ b/src/show.rs@@ -107,7 +107,16 @@ pub fn verify(id: &str, v: &Verify) {"{}/{} calls give the same result {}",v.passed,v.total,- dim(format!("({} recorded + {} derived)", v.total - v.derived, v.derived))+ dim(if v.edges > 0 {+ format!(+ "({} recorded + {} edge cases + {} derived)",+ v.total - v.derived,+ v.edges,+ v.derived - v.edges+ )+ } else {+ format!("({} recorded + {} derived)", v.total - v.derived, v.derived)+ })));} else {ui::ok(format!("{}/{} recorded calls give the same result", v.passed, v.total));@@ -119,8 +128,15 @@ pub fn verify(id: &str, v: &Verify) {nanos(m.original_ns),v.lang.label(),nanos(m.rust_ns),- rust(bold(format!("{} faster", times(m.speedup))))+ if v.slower() {+ red(bold(format!("{} slower", times(1.0 / m.speedup))))+ } else {+ rust(bold(format!("{} faster", times(m.speedup))))+ }));+ if v.slower() {+ ui::warn(crate::pipeline::slower_hint());+ }}return;}diff --git a/src/state.rs b/src/state.rsindex 2caba0b..023d131 100644--- a/src/state.rs+++ b/src/state.rs@@ -61,6 +61,8 @@ pub struct Verify {pub total: usize,/// Of total: extra cases made by shrinking recorded inputs, answered by the original.pub derived: usize,+ /// Of derived: edge cases (special numbers, non-ASCII text, empty and much bigger inputs).+ pub edges: usize,pub passed: usize,pub failed: usize,pub failures: Vec<Failure>,@@ -72,6 +74,11 @@ impl Verify {pub fn ok(&self) -> bool {self.built && self.total > 0 && self.failed == 0}++ /// Right, but slower per call than the original: the cost of crossing into Rust outweighs the work.+ pub fn slower(&self) -> bool {+ self.micro.is_some_and(|m| m.speedup > 0.0 && m.speedup < 1.0)+ }}#[derive(Debug, Clone, Default, Serialize, Deserialize)]@@ -165,3 +172,18 @@ impl Ctx {}}}++#[cfg(test)]+mod tests {+ use super::*;++ #[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() };+ assert!(v(0.5).slower());+ assert!(!v(1.4).slower());+ assert!(!v(0.0).slower(), "no measurement isn't slower");+ assert!(!Verify::default().slower());+ }+}