Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

23.7 KB
Raw Blame

Generated bridge code, part 1 (audit id A7a)

Scope and coverage ledger

Read in full, line by line (Read tool, chunks of at most ~800 lines):

file lines read
src/codegen.rs 1700 1-1700 (napi/wasm lib.rs, index.cjs codec, guard, js.rs, deps)
src/codegen_tswire.rs 784 1-784 (JS/Rust binary wire for napi and wasm)
src/codegen_batch.rs 733 1-733
src/codegen_batch_native.rs 1180 1-1180 (Ruby, Go, Java batches)
src/codegen_ffi.rs 371 1-371 (JSON dispatcher for Go/Ruby/Java)
src/codegen_py.rs 1532 1-1532 (PyO3 layer, pyconv.rs, pynum.rs)
src/codegen_go.rs 2100 1-2100 (cgo wrapper, typed/wire calls, Go driver, Go shadow)

Read because the generated code depends on it: src/wire.rs 1-1013 (all), DECISIONS.md (all).

tests/loop.rs (2777 lines): read 20-150, 218-343 and 1982-2100; the other tests were skimmed by function name and by grep only. Also read for evidence: tests/native.rs 577-720 and 1144-1230, src/harness.rs 2195-2330 and 2760-2840 (the JS diff comparison and the record watchdog), src/bridge.rs 1085-1135 (how index.cjs is assembled), src/harness_go.rs 180-260.

Not read: codegen_java.rs, codegen_ruby.rs and the other codegen_*.rs (part 2); lang/*; the rest of tests/loop.rs. Nothing here was executed against a built napi, wasm, PyO3 or cgo artifact (no cargo in the repo during the audit). Two small experiments ran in the scratch folder /tmp/claude-0/-home-user-rust-anything/3155f14a-830f-5883-9a8b-e7611d724b3a/scratchpad/A7a/: join.js (the batch string-join algorithm) and r.rs (the batch rank sort). Every other statement comes from reading code, and the findings say so.

Summary

  • 0 CRITICAL, 2 HIGH, 4 MEDIUM, 6 LOW. Nothing found says PASS on the common path for a plainly wrong port, but there are three gaps that let a wrong port through.
  • The biggest gap is that --batch classes and hand-written <Fn>Index types are never recorded or diffed (any language), yet STATUS says "Verified" and go steers users to them (A7a-02).
  • Under --kind wasm a Rust panic (unwrap, unimplemented!) becomes a RuntimeError: unreachable. diff only rejects messages that start with Rust panic:, so such a port agrees with every recorded error case. The "stubs never match" test covers napi only (A7a-01).
  • Go: a Rust panic on the JSON-dispatcher path carries no Rust panic: prefix, so it counts as the recorded Go panic (typed and wire paths do not). The Go record driver also drops cases silently, and string results are compared after Go's JSON turns invalid UTF-8 into U+FFFD (A7a-03, 04, 05).
  • The generated napi wire registers its two buffers in a thread-local shared by every index.cjs instance that loads the same .node on one thread. A second instance (Jest module reset, HMR) makes the first read the wrong buffer silently. diff uses one instance and cannot see it (A7a-06).
  • Checked and sound: the diff harness calls the same index.cjs that production loads; lone-surrogate and NaN/-0 handling in the wire; unsafe blocks all carry a real argument (see the last section).

Findings

A7a-01 [H1] [HIGH] [CONFIRMED by reading; not executed] wasm panics look like ordinary thrown errors, so diff accepts them

  • Where: src/codegen.rs:956-986 (NAPI_RUN and run_async are the only catch_unwind; there is none for wasm), src/codegen_tswire.rs:441-485 (wasm wire_io has none), src/harness.rs:2820 (panicked = actual.error.startsWith('Rust panic:')), tests/native.rs:636-643 (unported_stubs_never_match_in_typescript uses Kind::Napi only).
  • What happens: napi turns a panic into Error("Rust panic: ..."), which diff refuses to count as agreement. wasm32 is panic=abort: the trap reaches JS as WebAssembly.RuntimeError with message unreachable. jsError only recognises TypeError: ..., Rust panic: etc., so it passes the error through unchanged. The diff predicate is !panicked && both threw, and panicked is false.
  • Failing scenario: --kind wasm; the original throws for an empty string, a bad number or an out-of-range index (recorded as error). The port keeps the stub unimplemented!(), or uses .unwrap(), v[i] or s[..n] on that input. Every such case counts as passed. The napi build of the same port fails them, which is why the napi stub test exists. In production the trap also leaves the instance with a leaked shadow stack, and an object whose &mut self method trapped stays "recursive use of an object detected" (wasm-bindgen's borrow flag is never reset).
  • Fix / verification improvement:
    1. In the wasm index.cjs, turn WebAssembly.RuntimeError into Error('Rust panic: ' + message) with code: 'RUST_PANIC' inside jsError, or install a panic hook through a wasm-bindgen import that records the message and have jsError read it.
    2. Run stubs_fail with Kind::Wasm (needs wasm-bindgen-cli, so gate it like the others), and add a mutation self-test: replace the port body with unimplemented!(), record, diff, and assert passed == 0 for every kind the tool offers. The same stub test is also missing for C#, PHP, Kotlin, PowerShell and Swift.

A7a-02 [H1/H2] [HIGH] [CONFIRMED] Batch classes and custom <Fn>Index are never recorded, diffed or gated

  • Where: src/codegen_batch.rs (all), src/codegen_batch_native.rs (all); grep -i batch finds nothing in src/harness.rs, src/gate.rs or the record and diff paths. The only tests are string assertions in tests/loop.rs:1982-2040 and one smoke run in tests/native.rs:1144 (seven strings, no recorded comparison). docs/STATUS.md:46 lists --batch as "Verified (Fuse.js, vercel/ms, x18n search)"; go (src/go.rs:567-576) tells the user to move the hot loop onto ScoreBatch.
  • What happens: record and diff call exported functions one by one. A batch class is another code path: its new, run, rank, fromJoined/runJoined, and the hand-written FooIndex::run and rank (S10, S15: "ranking can be cheaper... narrows to the last query's matches"). The default index calls the port per item, but S10's purpose is to replace that with code the agent writes, and that code sits behind no case. gate checks port.rs for literals and unwraps; it does not run the index against recorded cases.
  • Failing scenario: fuzzyScore is ported and passes 1,233/1,233. The agent adds FuzzyScoreIndex that lowercases once and narrows with a cache of the previous query. Results change when queries arrive in another order, or for non-ASCII lowercase (İ). Every verification step is green; the app calls FuzzyScoreBatch.rank(...).
  • Fix: add a batch conformance step to diff (and to gate as a required check when rust-anything.json lists batches): for each recorded function with a batch, group cases by their non-item arguments, build the batch from all item values of the group, and require run(fixed)[i] to equal the recorded result of item i (comparing with the same tolerance as the per-call diff). Also check rank(fixed, min) against a stable sort of run, and run the groups twice in shuffled order so state dependence shows. For napi this is a JS driver loop; the Go, Java, Ruby and Python drivers need the same. Mutation self-test: make the custom index drop its first item or cache by query prefix, and require diff to fail.
  • STATUS wording: change "Verified" to say what was measured (speed on those three projects, the same hit count in the go fixture), not "checked against recordings".

A7a-03 [H1] [MEDIUM] [CONFIRMED by reading] Go: a Rust panic on the JSON-dispatcher path matches a recorded Go panic

  • Where: src/codegen_go.rs:1560-1566 (driver diff), src/codegen_go.rs:849-859 (typed run adds the prefix Rust panic:), src/codegen_ffi.rs:216-225 (call_json answers {"panic": message} with no prefix), src/codegen_go.rs:465-467 (wrapper does panic(*a.Panic)).
  • What happens: the driver rejects an actual panic only if its text contains Rust panic:. The typed path (scalars/strings) and the wire path carry that text; the JSON path (uint64, any, map[string]any, interface-ish arguments, several-result types the wire cannot carry) does not. If the recorded case is a Go panic, "that it panicked is the behavior" and any Rust panic passes.
  • Failing scenario: a Go function with a uint64 or JSON-typed parameter that panics on an index error. The port is still unimplemented!() or uses .unwrap(); every recorded panic case passes. tests/native.rs:698 (unported_stubs_never_match_a_go_panic) uses Shout(string) string, the typed path, so the gap is untested.
  • Fix: have call_json put the same Rust panic: prefix in its message (one line in codegen_ffi.rs), keep the driver check, and extend the stub test to a function that takes uint64 or a map[string]any.

A7a-04 [H6] [MEDIUM] [CONFIRMED by reading] The Go record driver drops cases silently

  • Where: src/codegen_go.rs:1491-1494 (if result["invalid"] != nil { continue }) and 1499-1502 (json.Marshal(line) error: continue); src/harness_go.rs:184-210 returns only the path; record_cases (src/harness.rs:2205-2313) reports only timed-out inputs.
  • What happens: an argument that does not decode into the Go parameter type, or a result that encoding/json cannot encode, removes the case with no message and no count. rustAnythingEncode handles only a top-level float, so []float64{NaN}, a struct field +Inf or a map value NaN is an UnsupportedValueError. Those results are the ones most likely to differ in a port (division, math.Log of zero).
  • Failing scenario: Normalize([]float64{0, 0}) returns [NaN NaN] in Go; the case is not in cases.jsonl; the port returns [0, 0] or panics and diff never sees it. This is the pitfall "A broken port passed because its case was never recorded", unfixed for Go.
  • Fix: count dropped_invalid and dropped_unencodable in the driver, write them to the progress channel, and have record print N of M inputs recorded and fail (or require a flag) when any input was lost for a reason other than the timeout. Add an encoder for nested non-finite floats (use the $num marker everywhere, as the PyO3 and JS sides do).

A7a-05 [H1/H5] [MEDIUM] [CONFIRMED mechanism] Go strings are coerced to valid UTF-8 on both sides of the comparison

  • Where: src/codegen_go.rs:874 (go_str is from_utf8_lossy), src/codegen_batch_native.rs:431 (same for batches), src/wire.rs:425 (opt_string), src/codegen_go.rs:1499 (json.Marshal of a record line) and 1452-1465 (canon).
  • What happens: Go strings are byte strings. A Go function can return invalid UTF-8 (s[:n] cutting a multi-byte rune is the usual way) and callers can pass binary data in a string. In a recording encoding/json replaces each invalid byte by U+FFFD; in diff both expected and got pass through json.Marshal again, so a port returning the three-byte U+FFFD matches, whereas production gets 3 bytes where Go returned 1. Arguments with invalid bytes cannot be recorded at all (JSON), and at the cgo boundary they turn into U+FFFD, so a hashing or length-counting port sees different data than the original in production.
  • Failing scenario: Truncate("héllo", 2) returns "h\xc3" in Go. The port that returns "h\u{FFFD}" passes; len() of the result is 2 in Go and 4 in the port.
  • Fix: record strings with invalid UTF-8 as a $bytes marker (like the Python and JS codecs) and make diff compare bytes. Until then, document in DECISIONS.md Known limits ("Go: strings cross as UTF-8; invalid bytes become U+FFFD") and have analyze/bridge list a Go function that slices a string by byte index (s[:n], s[i]) as a risk.

A7a-06 [H5] [MEDIUM] [PLAUSIBLE] Wire buffers are one thread-local per native module, but index.cjs state is per instance

  • Where: src/codegen_tswire.rs:360-374 (thread-local WIRE, replaced by every rustAnythingWireInit), 221-248 and 276-317 (module-level wIn, wOut, wLen, at, p in each index.cjs evaluation).
  • What happens: each evaluation of index.cjs allocates its own buffers and registers them. If the same .node file is loaded twice on one thread (Jest resetModules/isolateModules or one vm context per test file, Vite/Next HMR, a loader that evaluates the CJS file again), the thread-local points to the newer instance's buffers. A call through the older instance writes arguments to its own buffer and sets its own wLen; Rust reads the newer instance's buffer and length, and writes the answer into the newer instance's output. There is no error: the older instance decodes whatever its own wOut holds, usually zeros or a previous result.
  • Failing scenario: a long-lived module imports the package, the test framework (or HMR) reloads it, the old import is still referenced by a singleton. diff and shadow use one instance, so they cannot show this.
  • Fix: put an instance id in every call (fooWire(id) with the id compared inside wire_io; the cheap form is a 4-byte magic that JS writes at wIn[0..4] and Rust verifies against the registered buffer's own first bytes, reporting wire buffers belong to another instance), or re-register when native.rustAnythingWireOwner() !== id. Test: load index.cjs twice with Module._load bypassing the cache, call each alternately, and assert equal results.

A7a-07 [H1] [LOW-MEDIUM] [CONFIRMED by simulating the algorithm] Joined string batches corrupt neighbours that hold split surrogate halves

  • Where: src/codegen_batch.rs:581-596 (items.join('') with UTF-16 end offsets) and 527-555 (split_joined).
  • What happens: the joined JS string is one string, so a high surrogate at the end of item k and a low surrogate at the start of item k+1 form a valid pair; the napi UTF-8 conversion makes one 4-byte char, and split_joined hands the whole char to item k. Item k+1 loses its first unit.
  • Failing scenario (join.js): items ['x\uD83D', '\uDE00y', 'z'] arrive in Rust as ['x😀', 'y', 'z']. Lone surrogates come from slice on emoji (the very reason for L6/X2), and "search over text fragments" is the batch use case. A lone surrogate alone becomes U+FFFD, and tests/native.rs:1176 asserts <b�c> as expected, while the per-call path refuses such strings with a TypeError: the two paths disagree.
  • Fix: in the JS joinItems, throw the same TypeError as the per-call guard when any item is not well formed (!item.isWellFormed()), which also removes the silent U+FFFD; add that case to napi_string_batches_cross_joined.

A7a-08 [H2] [LOW] [CONFIRMED by experiment] rank is not stable for ±0 although it says it is

  • Where: src/codegen_batch.rs:310-313 (hits.sort_by(|a, b| b.0.total_cmp(&a.0)), comment "Stable ... as JS sort").
  • What happens: total_cmp orders +0.0 above -0.0. For results [0, -0, 0, -0] and min = -0 Rust gives indexes [0, 2, 1, 3]; JS sort((a,b) => b - a) gives [0, 1, 2, 3] (r.rs and a node one-liner in the scratch folder).
  • Fix: compare with partial_cmp(...).unwrap_or(Equal) after the >= min filter (NaN is already excluded), and add a -0 item to the rank test.

A7a-09 [H1] [LOW] [CONFIRMED by reading] T | null returns undefined from wasm functions and from class methods

  • Where: src/codegen.rs:711-725 (binding_ret: the Either<_, ()>/null logic is napi-only, none_is_null is passed false for classes at bind_class, lines 765 and 795), src/codegen.rs:612-621 (computed per function only).
  • What happens: wasm-bindgen turns None into undefined, as does the napi class path. A source declared string | null therefore returns undefined through those routes. diff fails such a case (the codec tells null from undefined), so this is fail-closed, but the agent cannot repair it because the generated layer decides, and a team could "accept" the mismatch with a known-diff.
  • Fix: for wasm and for classes, wrap Option returns in index.cjs (r === undefined ? null : r when none_is_null), or generate the same null as napi. Add a wasm round-trip test for string | null.

A7a-10 [H5] [LOW] [CONFIRMED by reading] Class methods and constructors skip the guard layer

  • Where: src/codegen.rs:1076-1095 (guard_cjs loops over api.functions only), 1178-1188 (class wrapper has no try/catch).
  • What happens: a lone surrogate passed to a class method is converted to U+FFFD by napi (not refused as for functions), and an error thrown by the port is a plain Error, not the TypeError/RangeError the source throws (jsError is not applied). diff treats both-threw as agreement, so a caller's instanceof TypeError check breaks without any signal.
  • Fix: apply illFormed and jsError to class constructors and methods, and add stepsMatch support for comparing the error class name (at least when the recorded error carried one) in the class scenario driver.

A7a-11 [H5] [LOW] [CONFIRMED by reading] The wire fallback runs the port twice

  • Where: src/codegen_tswire.rs:599 (let out = &call; <write>) and src/wire.rs:808-812 (MISMATCH raised in write_value after the call), src/codegen_tswire.rs:408-411 and 479 (NaN/u32::MAX makes JS re-run through json(...)).
  • What happens: when the port's result does not fit the declared TS type, the call already ran; JS calls it again through JSON. A port with a counter, cache, or static/thread_local state sees two calls.
  • Fix: check the shape before any side effect is impossible, so document it and, in shadow mode, count wire fallbacks per function in the report; or return the already computed value by writing it as Dyn in the same call instead of re-running.

A7a-12 [H5] [LOW] [PLAUSIBLE] Send + Sync is not asserted for a custom batch index in Go, Java and Ruby

  • Where: src/codegen_batch_native.rs:545-546 (&*h shared across goroutines), 865-868 (batch_ref), Go and Java docs "Safe for concurrent Run and Rank" / "Safe for concurrent use" (lines 684 and 1130).
  • What happens: PyO3 requires Sync of a #[pyclass], so Python catches a RefCell cache at compile time; the other three bridges compile anything. S15's "remembers the last query" index is written with Cell/RefCell, and a concurrent Run is then a data race.
  • Fix: emit const _: fn() = || { fn is_sync<T: Send + Sync>() {} is_sync::<port::FooIndex>(); }; for every batch. Related and smaller: a Java close() concurrent with run() frees the handle under a running call (State.get is synchronized but the handle is used outside the lock), and the Go Run after Close passes a null handle to &*h.

A7a-13 [H6] [LOW] [PLAUSIBLE, not compiled] Generated helper names can collide with port function names

  • Where: napi run, run_async, panic_message (codegen.rs:958-986), wire_io, joined, split_joined, JoinedStrings, WIRE, PENDING, SCRATCH (codegen_tswire.rs, codegen_batch.rs); PyO3 error, native_module (codegen_py.rs:247, 474); wasm {name}_inner for function name against a port function name_inner. Go has a reserved-name test (codegen_go.rs:1818); the JS and Python generators do not.
  • What happens: pub fn run(...) (a plain export name) and fn run<T> are the same item. The crate fails to compile. That is fail-closed, but go picks "the outermost portable exported function", and run/error are likely names.
  • Fix: prefix every generated item (ra_run, ra_panic_message, ...) the way the C and Go generators already do; add a bridge test with exports run, error and joined.

A7a-14 [H3] [LOW] [WEAK] Python parameter names follow snake_case, not the original

  • Where: src/codegen_py.rs:15-47 (py_name = name, the Rust identifier).
  • What happens: PyO3 has no per-parameter rename, so an original def f(maxLen=3) called as f(maxLen=5) raises TypeError: unexpected keyword. diff replays recorded keyword calls, so the case fails (fail-closed), and the agent cannot change generated names.
  • Fix: refuse such functions in bridge with the reason ("parameter names that are not snake_case cannot be kept") instead of generating a wrapper that cannot match.

Verification improvements for this area (ranked)

  1. Batch conformance in diff and gate (A7a-02): replay recorded cases through Batch.run/rank, shuffled twice.
  2. Stub and panic mutation test for every kind and every language: unimplemented!() port must give passed == 0 (wasm, Go JSON path, C#, PHP, Kotlin, PowerShell, Swift); then a second mutation, .unwrap() on the error inputs.
  3. Make every record driver report inputs, recorded, timed out, dropped and fail when dropped > 0 (Go first, A7a-04).
  4. One generic "generated layer self-test" in CI for every JS kind: load index.cjs twice and call both (A7a-06); call with lone surrogates, undefined, null, -0, NaN, 2^53, extra and missing arguments; assert the answers equal a plain-JS reference function. Today tests/loop.rs replaces index.cjs with a JS stand-in and asserts on generated source text, so the generated JS wrappers run only in tests/native.rs, which returns early (green) when node, python3, go or javac is missing.
  5. Prefix all generated identifiers (A7a-13) and run a bridge test whose exports are named like every generated helper.
  6. Fix the wording in STATUS for --batch and for any "Verified" row whose evidence is speed, not recordings.

Things checked and found sound (so nobody re-checks them)

  • Diff and production use the same loader: harness::diff loads the crate's index.cjs (src/harness.rs:1245, 1528), the same file enable and the package load; PyO3 diffs import the generated package; Go diffs import the cgo wrapper (M3). The paths do differ in one respect: the driver passes enc/dec decoded values, so a production caller that hands over class instances or objects with extra keys takes the JSON fallback, which the cases do not reach (A7a-11 is the same property).
  • Number handling in the wire: f64 is written raw (NaN, -0, 2^53 and above survive); js::number, float_value and js_number use $num for non-finite and negative zero, i64 only below 2^53; serde_json runs with float_roundtrip.
  • Strings in the wire: units are written as UTF-16; lone surrogates are tagged (4) and refused for Rust String parameters by illFormed; Reader::string16 would turn them into U+FFFD, but only Map16 keys and Dyn object keys can reach it unguarded (edge: two different lone-surrogate keys collide).
  • napi panics are caught on the sync, async, class and batch paths; Go typed, wire and batch exports and the JSON dispatcher all use catch_unwind; no panic crosses an extern "C".
  • Order and determinism of batches: par_iter().map().collect::<Vec<_>>() keeps item order, the first error in item order wins, rank is a stable sort over (result, index); rayon cannot change results unless the port itself is not pure.
  • Memory: SCRATCH/PENDING are bounded by the largest result; Go batch strings are copied into a Go buffer and the Rust vector is freed once (take_strings); Java's handle is freed once by close or the Cleaner; rust_anything_free matches CString::into_raw.
  • Unsafe blocks: every unsafe in the files read has a // SAFETY: line and a contract that the generated caller meets (synchronous call, valid pointer and length from Go, handle kept alive by KeepAlive/reachabilityFence). The open points are the concurrency items in A7a-12, not missing arguments.
  • Embedded NUL: JSON dispatcher text escapes NUL; typed Go strings pass pointer and length; error messages replace NUL with a space.
  • Arguments: wrong arity falls to the JSON path for wired functions (arguments.length <= n), omitted structured parameters become undefined (prepare), PyO3 signatures keep Python's required, default and keyword-only rules.