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.
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
--batchclasses and hand-written<Fn>Indextypes are never recorded or diffed (any language), yet STATUS says "Verified" andgosteers users to them (A7a-02). - Under
--kind wasma Rust panic (unwrap,unimplemented!) becomes aRuntimeError: unreachable.diffonly rejects messages that start withRust 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.cjsinstance that loads the same.nodeon one thread. A second instance (Jest module reset, HMR) makes the first read the wrong buffer silently.diffuses one instance and cannot see it (A7a-06). - Checked and sound: the diff harness calls the same
index.cjsthat 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_RUNandrun_asyncare the onlycatch_unwind; there is none for wasm),src/codegen_tswire.rs:441-485(wasmwire_iohas none),src/harness.rs:2820(panicked = actual.error.startsWith('Rust panic:')),tests/native.rs:636-643(unported_stubs_never_match_in_typescriptusesKind::Napionly). - What happens: napi turns a panic into
Error("Rust panic: ..."), whichdiffrefuses to count as agreement. wasm32 ispanic=abort: the trap reaches JS asWebAssembly.RuntimeErrorwith messageunreachable.jsErroronly recognisesTypeError: ...,Rust panic:etc., so it passes the error through unchanged. The diff predicate is!panicked && both threw, andpanickedis false. - Failing scenario:
--kind wasm; the original throws for an empty string, a bad number or an out-of-range index (recorded aserror). The port keeps the stubunimplemented!(), or uses.unwrap(),v[i]ors[..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 selfmethod trapped stays "recursive use of an object detected" (wasm-bindgen's borrow flag is never reset). - Fix / verification improvement:
- In the wasm
index.cjs, turnWebAssembly.RuntimeErrorintoError('Rust panic: ' + message)withcode: 'RUST_PANIC'insidejsError, or install a panic hook through a wasm-bindgen import that records the message and havejsErrorread it. - Run
stubs_failwithKind::Wasm(needswasm-bindgen-cli, so gate it like the others), and add a mutation self-test: replace the port body withunimplemented!(), record, diff, and assertpassed == 0for every kind the tool offers. The same stub test is also missing for C#, PHP, Kotlin, PowerShell and Swift.
- In the wasm
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 batchfinds nothing insrc/harness.rs,src/gate.rsor the record and diff paths. The only tests are string assertions intests/loop.rs:1982-2040and one smoke run intests/native.rs:1144(seven strings, no recorded comparison).docs/STATUS.md:46lists--batchas "Verified (Fuse.js, vercel/ms, x18n search)";go(src/go.rs:567-576) tells the user to move the hot loop ontoScoreBatch. - What happens:
recordanddiffcall exported functions one by one. A batch class is another code path: itsnew,run,rank,fromJoined/runJoined, and the hand-writtenFooIndex::runandrank(S10, S15: "ranking can be cheaper... narrows to the last query's matches"). The default index calls the port per item, butS10's purpose is to replace that with code the agent writes, and that code sits behind no case.gatechecksport.rsfor literals and unwraps; it does not run the index against recorded cases. - Failing scenario:
fuzzyScoreis ported and passes 1,233/1,233. The agent addsFuzzyScoreIndexthat 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 callsFuzzyScoreBatch.rank(...). - Fix: add a batch conformance step to
diff(and togateas a required check whenrust-anything.jsonlists 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 requirerun(fixed)[i]to equal the recorded result of item i (comparing with the same tolerance as the per-call diff). Also checkrank(fixed, min)against a stable sort ofrun, 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 requirediffto fail. - STATUS wording: change "Verified" to say what was measured (speed on those three projects, the same hit count in the
gofixture), 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(driverdiff),src/codegen_go.rs:849-859(typedrunadds the prefixRust panic:),src/codegen_ffi.rs:216-225(call_jsonanswers{"panic": message}with no prefix),src/codegen_go.rs:465-467(wrapper doespanic(*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
uint64or JSON-typed parameter that panics on an index error. The port is stillunimplemented!()or uses.unwrap(); every recorded panic case passes.tests/native.rs:698(unported_stubs_never_match_a_go_panic) usesShout(string) string, the typed path, so the gap is untested. - Fix: have
call_jsonput the sameRust panic:prefix in its message (one line incodegen_ffi.rs), keep the driver check, and extend the stub test to a function that takesuint64or amap[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 }) and1499-1502(json.Marshal(line)error:continue);src/harness_go.rs:184-210returns 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/jsoncannot encode, removes the case with no message and no count.rustAnythingEncodehandles only a top-level float, so[]float64{NaN}, a struct field+Infor a map valueNaNis anUnsupportedValueError. Those results are the ones most likely to differ in a port (division,math.Logof zero). - Failing scenario:
Normalize([]float64{0, 0})returns[NaN NaN]in Go; the case is not incases.jsonl; the port returns[0, 0]or panics anddiffnever sees it. This is the pitfall "A broken port passed because its case was never recorded", unfixed for Go. - Fix: count
dropped_invalidanddropped_unencodablein the driver, write them to the progress channel, and haverecordprintN of M inputs recordedand 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$nummarker 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_strisfrom_utf8_lossy),src/codegen_batch_native.rs:431(same for batches),src/wire.rs:425(opt_string),src/codegen_go.rs:1499(json.Marshalof a record line) and1452-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 astring. In a recordingencoding/jsonreplaces each invalid byte by U+FFFD; indiffbothexpectedandgotpass throughjson.Marshalagain, 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
$bytesmarker (like the Python and JS codecs) and makediffcompare bytes. Until then, document inDECISIONS.mdKnown limits ("Go: strings cross as UTF-8; invalid bytes become U+FFFD") and haveanalyze/bridgelist 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-localWIRE, replaced by everyrustAnythingWireInit),221-248and276-317(module-levelwIn,wOut,wLen,at,pin eachindex.cjsevaluation). - What happens: each evaluation of
index.cjsallocates its own buffers and registers them. If the same.nodefile is loaded twice on one thread (JestresetModules/isolateModulesor 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 ownwLen; 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 ownwOutholds, 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.
diffandshadowuse one instance, so they cannot show this. - Fix: put an instance id in every call (
fooWire(id)with the id compared insidewire_io; the cheap form is a 4-byte magic that JS writes atwIn[0..4]and Rust verifies against the registered buffer's own first bytes, reportingwire buffers belong to another instance), or re-register whennative.rustAnythingWireOwner() !== id. Test: loadindex.cjstwice withModule._loadbypassing 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) and527-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_joinedhands 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 fromsliceon emoji (the very reason for L6/X2), and "search over text fragments" is the batch use case. A lone surrogate alone becomes U+FFFD, andtests/native.rs:1176asserts<b�c>as expected, while the per-call path refuses such strings with aTypeError: the two paths disagree. - Fix: in the JS
joinItems, throw the sameTypeErroras the per-call guard when any item is not well formed (!item.isWellFormed()), which also removes the silent U+FFFD; add that case tonapi_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 JSsort"). - What happens:
total_cmporders+0.0above-0.0. For results[0, -0, 0, -0]andmin = -0Rust gives indexes[0, 2, 1, 3]; JSsort((a,b) => b - a)gives[0, 1, 2, 3](r.rsand a node one-liner in the scratch folder). - Fix: compare with
partial_cmp(...).unwrap_or(Equal)after the>= minfilter (NaN is already excluded), and add a-0item 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: theEither<_, ()>/null logic is napi-only,none_is_nullis passedfalsefor classes atbind_class, lines 765 and 795),src/codegen.rs:612-621(computed per function only). - What happens: wasm-bindgen turns
Noneintoundefined, as does the napi class path. A source declaredstring | nulltherefore returnsundefinedthrough those routes.difffails such a case (the codec tellsnullfromundefined), 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
Optionreturns inindex.cjs(r === undefined ? null : rwhennone_is_null), or generate the samenullas napi. Add a wasm round-trip test forstring | null.
A7a-10 [H5] [LOW] [CONFIRMED by reading] Class methods and constructors skip the guard layer
- Where:
src/codegen.rs:1076-1095(guard_cjsloops overapi.functionsonly),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 theTypeError/RangeErrorthe source throws (jsErroris not applied).difftreats both-threw as agreement, so a caller'sinstanceof TypeErrorcheck breaks without any signal. - Fix: apply
illFormedandjsErrorto class constructors and methods, and addstepsMatchsupport 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>) andsrc/wire.rs:808-812(MISMATCHraised inwrite_valueafter the call),src/codegen_tswire.rs:408-411and479(NaN/u32::MAXmakes JS re-run throughjson(...)). - 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_localstate 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
Dynin 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(&*hshared 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
Syncof a#[pyclass], so Python catches aRefCellcache at compile time; the other three bridges compile anything. S15's "remembers the last query" index is written withCell/RefCell, and a concurrentRunis 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 Javaclose()concurrent withrun()frees the handle under a running call (State.getis synchronized but the handle is used outside the lock), and the GoRunafterClosepasses 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); PyO3error,native_module(codegen_py.rs:247,474); wasm{name}_innerfor functionnameagainst a port functionname_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) andfn run<T>are the same item. The crate fails to compile. That is fail-closed, butgopicks "the outermost portable exported function", andrun/errorare 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 exportsrun,errorandjoined.
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 asf(maxLen=5)raisesTypeError: unexpected keyword.diffreplays recorded keyword calls, so the case fails (fail-closed), and the agent cannot change generated names. - Fix: refuse such functions in
bridgewith 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)
- Batch conformance in
diffandgate(A7a-02): replay recorded cases throughBatch.run/rank, shuffled twice. - Stub and panic mutation test for every kind and every language:
unimplemented!()port must givepassed == 0(wasm, Go JSON path, C#, PHP, Kotlin, PowerShell, Swift); then a second mutation,.unwrap()on the error inputs. - Make every record driver report
inputs,recorded,timed out,droppedand fail whendropped > 0(Go first, A7a-04). - One generic "generated layer self-test" in CI for every JS kind: load
index.cjstwice 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. Todaytests/loop.rsreplacesindex.cjswith a JS stand-in and asserts on generated source text, so the generated JS wrappers run only intests/native.rs, which returns early (green) whennode,python3,goorjavacis missing. - Prefix all generated identifiers (A7a-13) and run a bridge test whose exports are named like every generated helper.
- Fix the wording in STATUS for
--batchand 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::diffloads the crate'sindex.cjs(src/harness.rs:1245,1528), the same fileenableand 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 passesenc/decdecoded 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_valueandjs_numberuse$numfor non-finite and negative zero,i64only below 2^53;serde_jsonruns withfloat_roundtrip. - Strings in the wire: units are written as UTF-16; lone surrogates are tagged (4) and refused for Rust
Stringparameters byillFormed;Reader::string16would turn them into U+FFFD, but onlyMap16keys andDynobject 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 anextern "C". - Order and determinism of batches:
par_iter().map().collect::<Vec<_>>()keeps item order, the first error in item order wins,rankis a stable sort over(result, index); rayon cannot change results unless the port itself is not pure. - Memory:
SCRATCH/PENDINGare 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 bycloseor the Cleaner;rust_anything_freematchesCString::into_raw. - Unsafe blocks: every
unsafein 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 byKeepAlive/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 becomeundefined(prepare), PyO3 signatures keep Python's required, default and keyword-only rules.