# How it works How rust-anything checks a port, what its commands decide, and where its limits are. Back to the [README](../README.md). ## How it works ``` profile ──> analyze ──> bridge ──> record ──> port.rs ──> diff ──> bench ──> shadow ──> gate where the what to the Rust what the you or every faster? both side done means time goes port first crate and original your agent recorded the by side in this passes wrapper does write it case verdict production ``` The original stays the source of truth: `record` runs it on edge cases (and your own inputs) and saves what it returns or throws; `diff` replays every case against the Rust; nothing ships until they all match and `gate` passes. Callers keep the original API throughout. A whole app goes through the same loop unit by unit, inside a frame that proves the whole program ([Port a whole app](whole-apps.md#port-a-whole-app)): ``` analyze --whole-app ──> app record ──> app front-door ──> per unit: the loop above, then app wire ──> app lift shape, every what the app Rust owns the gate passes, so the unit answers in pure Rust, dependency, the does from the entry point; the Rust: replay 100%, fallback rate down proved by decisions to make outside original answers replay ``` ## The loop | Step | Command | What it does | | --- | --- | --- | | All in one | `rust-anything go --agent claude -- python3 app.py` | The hot-path loop end to end: profile, pick the outermost portable function (batched where `profile` says so), bridge it into `rust/-rs`, record generated cases plus the calls the run makes, hand `src/port.rs` to the agent (`claude`, `codex`, or any command reading a prompt on stdin; without `--agent` it writes `TASK.md` and stops), then build, diff, gate and bench, and `enable` only when all pass and the port is not slower as its callers call it (otherwise it says where the speed is: the batch class to call from the loop, or the caller to port with it). Run it again after porting by hand: finished steps are kept | | 0. Profile | `rust-anything profile -- node bench.mjs` | Runs a real workload under the language's profiler (node, cProfile, `go test` pprof, JFR, a Ruby tracer): hot functions by inclusive time, their callers, and which loops to batch; flags code that is already compiled (numba, Cython, JAX), where Rust gains little, and time spent waiting on child processes, which porting does not shorten | | 1. Plan | `rust-anything analyze ` | Units, port order, risks with `file:line`, bridge per unit, dependency-to-crate fit, best first ports; `--whole-app` adds entry points and shape, every dependency (imported or declared) with its crate, pieces (units that import each other move together) and numbered decisions with a recommended answer | | 2. Bridge | `rust-anything bridge ` | Crate with the bindings (`lib.rs`, plus the wrapper the source language loads) and stubs to port (`port.rs`); `--batch fn:param` adds a class that keeps many `param` values in Rust; `--as-json T` bridges a type parameter the app only fills with data as JSON values | | 3. Record | `rust-anything record ` | Runs the original on generated edge cases (non-ASCII, emoji, `-0`, `NaN`, ints where floats are expected, ...) and on every semantic trap in every parameter (string length and case, signed division, overflow edges, float printing, map and sort order), and saves `cases.jsonl`; `--from-tests -- npx jest` (or `-- pytest`) also records every call the original's own test suite makes; `--float-tolerance 1e-9` lets floats match within that share for numeric code; `--pin-clock` (TS/JS, Python) fixes the clock and random numbers during record and diff, and `src/port/pinned.rs` gives the port the same ones | | 3. Build | `rust-anything build ` | Builds the Rust side: `.node`, wasm package, Python extension or shared library | | 3. Diff | `rust-anything diff ` | Replays the recorded cases against Rust, called the way the original's callers call it; lists mismatches | | 3. Fuzz | `rust-anything fuzz ` | Fresh inputs from a new seed (`--seed`, `--cases`, `--time`) through the original and Rust; reports what the recording missed, and `--keep` adds those cases to it | | 3. Bench | `rust-anything bench ` | Times the recorded cases on the original and on Rust, bridge included | | 4. Shadow | `rust-anything shadow ` | Drop-in that runs both, returns the original's result, reports mismatches; `RUST_ANYTHING_MODE=old\|shadow\|new` | | 5. Gate | `rust-anything gate ` | fmt, clippy `-D warnings`, tests, `unsafe` audit, nothing unported, a recorded failing case for every error path of the original, no `unwrap`/`expect`/`panic!` where the original returns an error (unless marked `// INFALLIBLE: `), build, API, behavior | | 6. Switch | `rust-anything enable ` / `disable ` | Turns a gated TS/JS or Python port on for every caller, and off again byte for byte ([Switch a port on and off](#switch-a-port-on-and-off)) | | 7. Report | `rust-anything report ` | `report/REPORT.md` and `report/card.svg` for a pull request: recorded cases matched, speedup from `bench`, fallback rate, on or off, the machine and its cores | | Cache | `rust-anything clean` | Removes the build folder every port and bridge shares ([One build cache](#one-build-cache)) | | Agents | `rust-anything setup` | Registers the MCP server (`rust-anything mcp`, every step as a tool) and the workflow skill ([`skills/rust-anything/SKILL.md`](../skills/rust-anything/SKILL.md)) with your coding agents | ## Hot paths: keep the data in Rust A port called once per item pays the bridge once per item, and loses to a JIT. What wins is moving the loop: `profile` finds it, and `--batch` generates a class that takes the items once and runs the function over all of them per call, on all cores, with typed-array results. ```sh rust-anything profile ../x18n -- node --experimental-strip-types $PWD/demo/x18n-search/search.ts . # -> fuzzyScore: a quarter of the run, called per key by `matched`: batch it rust-anything bridge ../x18n packages/core/src/fuzzy.ts --batch fuzzyScore:text ``` ```js const search = new FuzzyScoreBatch(keys) // once const order = search.rank(query, 0) // per keystroke: indexes, best first ``` A `FuzzyScoreIndex` struct in `port.rs` replaces the default loop with one that prepares the items once, and can rank by itself (`rank`): it keeps the keys lowercased with a character mask each, a table of each key's first position of every common character (a one-letter query is one column), and the last query's matches (typing `se` after `s` rescores only what `s` matched). On x18n's sidebar search over 50,000 keys, typed letter by letter, with identical results: | | Per query | vs TS | | --- | ---: | ---: | | TS: `map(fuzzyScore)`, filter, sort | 10 ms | 1x | | TS with the same narrowing as the index | 4.1-5.4 ms | 2x | | The same port, called per key | - | 0.2-0.4x | | `FuzzyScoreBatch`, default index (4 cores) | 5.1 ms | 1.7x | | `FuzzyScoreBatch` with `FuzzyScoreIndex` (napi, 4 cores) | 0.45-0.56 ms | **18-22x** | | The same with wasm (one thread) | 0.95 ms | **11.5x** | Against TS doing the same narrowing, Rust is still 7-12x faster (wasm 5x). Turn the returned indexes into keys with a plain loop: `Array.from(order, i => keys[i])` cost 20x more, 0.4 ms. Every language gets batches. Below, the Rust batch runs on 4 cores and the original on one thread, as the original code is written. Identical results and errors (benchmarks in each demo folder): | Language | Workload | Original (1 thread) | Per-call port vs original | Batch (4 cores) vs original | | --- | --- | ---: | ---: | ---: | | TS | x18n search, 50,000 keys | 10 ms | 0.2-0.4x | **20x** | | Python | `slugify`, 20,000 strings | 98 ms | - | **17x** | | Ruby | `slugify`, 20,000 strings | 110 ms | - | **12.7x** | | Ruby | `shellescape` (stdlib), 50,000 mixed values | 88 ms | - | **11.8x** | Go and Java are left out: they can run the original on 4 threads just as easily, and measured that way the Java original beats the Rust batch ([#110](https://github.com/erkamyaman/rust-anything/issues/110)). Batch crates allocate with mimalloc: with the system allocator the Go batch was slower than one thread. `bridge --allocator rusty_alloc` opts into a pure-Rust allocator instead. Demo: [`demo/x18n-search`](../demo/x18n-search/README.md). ## Switch a port on and off Every way to switch, in one place: | What | On | Off | | --- | --- | --- | | A TS/JS or Python unit, in place | `rust-anything enable `: one marked block in each original file rebinds the ported functions to the Rust module, so every caller gets Rust and no import changes. It refuses while a recorded case differs (`--force` skips that check); `go` runs it only after diff and gate pass | `rust-anything disable `: removes exactly the lines `enable` added, so the files are byte for byte what they were | | That unit, for one run | (on by default once enabled) | `RUST_ANYTHING_UNIT_=original` (`` is the crate name without `-rs`, upper case: `RUST_ANYTHING_UNIT_DEDUPE`), or `RUST_ANYTHING_MODE=old` for every unit | | A shadow module (any language) | Import it where the app imported the original; `RUST_ANYTHING_MODE=new` runs only Rust | `RUST_ANYTHING_MODE=old`; the default, `shadow`, returns the original's result and compares Rust | | A unit wired into a front door (`app wire`) | Wired units answer in Rust | `RUST_ANYTHING_UNIT_=original` sends that unit's commands to the original | | An installed package (`package`) | The platform's binary | `RUST_ANYTHING_MODE=old` runs the original it depends on | The `enable` block names the crate by a path relative to the source file, so it holds no path of your machine, and it falls back to the original when the module does not load (with `RUST_ANYTHING_MODE=new` that is an error instead). `record`, `diff`, `bench` and `fuzz` set the unit's switch to `original` for the original's side, so an enabled unit is still measured against the original. Other languages switch through the shadow module. ## One build cache Ports and bridges build into one cargo target folder: `CARGO_TARGET_DIR` when it is set, else `rust-anything/target` in your cache folder (`~/Library/Caches` on macOS, `$XDG_CACHE_HOME` or `~/.cache` on Linux, `%LOCALAPPDATA%` on Windows). napi-rs, PyO3, serde and the rest compile once for every crate instead of once per crate. `rust-anything clean` removes the folder (`--dry-run` prints its size; a folder named by `CARGO_TARGET_DIR` needs `--force`, since other projects may build there). Cargo names a crate's library after its package name alone, so two crates with one name would replace each other's library in a shared folder (see `docs/pitfalls.md`). Each package name belongs to one crate folder there (`owners.json`, written under a lock); another crate with the same name builds in its own `target/` as before, and gets the name back once the first folder is gone. Each crate's libraries are copied to its own `target/release`, where every loader reads them. Front doors (`rust/app`) keep their own `target/`, since every app's binary would have the same name. ## What `bridge` decides - Exports that cannot cross a bridge stay in the source language, with the reason, and the shadow module re-exports the original. For TS: functions that take or return functions, generators and iterators, RegExp, `instanceof` checks, generics (`--as-json T` bridges one the app only fills with data), and values whose types (followed through imports, re-exports and `extends`) hold functions. `--keep "name: reason"` keeps more, e.g. code that depends on `Intl` data. - TS types map to Rust types, with type aliases resolved through imports and parameter types inferred from default values; structured values cross as a generated binary wire (JSON only as a fallback for shapes the wire does not model). - JSON cannot express `undefined`, NaN, Infinity, -0 or lone surrogates: structured values carry markers (`{"$undefined": true}`, `{"$num": "NaN"}`, `{"$utf16": [...]}`) that the generated `index.cjs` translates, with helpers in the crate's `js.rs`. `record` runs TS sources as they are: a Node resolve hook follows bundler-style imports (`./errors` to `./errors.ts`), `--resolve-from` supplies npm packages when the repo has none installed, and TS that needs transforming (enums, parameter properties) is retried with `--experimental-transform-types`. ## What `analyze` looks at - Packages (`package.json`) and source files; skips `node_modules`, build output, fixtures, playgrounds, tool configs. Vue/Svelte/Astro `