# Moving the server core off Bun: scope (2026-10-28) Status: **research only; nothing is built.** Branch `server-rust-scope` from main 20d4dbe2. This doc answers what finishing the TS→Rust move on the server would mean before the owner decides whether it is a goal. **In flux:** the edit/net path (`server/src/net`, region edits, `client/src/world/region-manager.ts`) is being changed on branch `net-edit` ("edits as commands": the client predicts, holders replay, and both sides reconcile by seq/ack plus a state hash, 9b478c01). All counts here are from main. Where net-edit changes the picture, it is called out (§1.3, §5). Scratch, scripts and raw numbers: `logs/server-rust-scope/` (`bench/`, `common-split.txt`). --- ## 0. Summary - **What runs in TS on the server:** 38.4k lines in `server/src` (plus 28k lines of tests). The server also reaches about 29k lines of `common/src`: 26.7k of them are shared with the browser client, and 2.3k are server-only. Rust already owns the hot inner loops: physics step, worldgen, CA step and the surface-initiator build. That is 85k lines in 4 crates (744 Rust tests). - **What is still hot in TS:** - the main event loop: the stream scan, wire encode, the 30 Hz look tick, sessions and SQLite; - CSG edits (`applyCsgEditFull`); - the normals build (`buildNormalSVT`/`refreshNormalSVT`, a TS worker pool); - the data movement between Bun threads. - **The cost is not FFI and not GC.** - A bun:ffi call costs 9–135 ns, and a physics step makes about 10 of them. - The open "mark-compacts from embedder memory" item is **client-side** (Chromium's V8 plus WebGPU wrappers). No server change touches it. - The server heap is about 100k live objects; `--smol` has no effect. - **The measured cost of the Bun architecture is copies and one saturated thread.** - During a stream arrival the server main thread has **zero idle time**. Of every 20 s, 5.4 s go to structured-clone `postMessage`: 3.9 s for normals jobs carrying 27 region trees each, and 1.5 s for the physics relay. - Each physics-relevant region exists **three times**: in the main JS cache, in the physics Worker's JS `WorldState` and in the Rust store. That is why `REGION_CACHE_MB` has to be budgeted double, and why the worst-case envelope is about 10.5 GB. - Bun Workers cannot share a JS heap, so every hand-off is a copy. A 13 MiB clone round trip costs 14.7 ms, and "transfer" is not much cheaper in Bun 1.3.13 (11.4 ms). - **What Bun buys:** - zero runtime dependencies; - `Bun.serve` with drain-driven backpressure; - one TS codebase for the protocol, CSG, normals and pose codecs shared with the client. net-edit makes this load-bearing: the client and the server must produce byte-identical edit results, checked by hash; - 615 server tests and 867 common tests on one runner; - 48 fixture scenes (6k lines) written against the same CSG API; - hot reload; - the client bundler. The bundler is independent of the server runtime and stays whichever option is chosen. - **Recommendation: option D**, a native world core inside the Bun process. Rust owns the region store and the world-mutating hot paths (normals, edits, SI), and physics and CA read it in place across threads. Bun keeps sockets, sessions, entities, fixtures and tests. - Every phase removes a measured cost on its own (the 1:1 mirror, 27 % of main-thread time during an arrival). - Each phase leaves a playable server. - It does not move the protocol. - It is the first half of a full Rust server anyway, so the decision about option A can wait until D's numbers are in. - A spike confirmed the key enabler: a native pointer created on the main thread is valid in a Bun Worker, with one shared mapping of the `.so`. --- ## 1. Inventory ### 1.1 What runs where today Lines are non-test `.ts` lines on main 20d4dbe2 (test lines in brackets). | subsystem | TS lines (tests) | hot? | Rust already | boundary today, and what each crossing copies | |---|---|---|---|---| | **World manager / regions** (`world/manager.ts` 4317, `sculpt`, `structures`, `compute-budget`, `stream-knobs`, …) | ~6.3k (8.1k for all of `world/`) | **yes**: region cache, LRU, gen scheduling, edit apply, halo refresh, all on the main thread | `voxel-core` (SVT64 reader/writer, hashing) is used only by the crates | none: plain JS `Uint8Array`s in `ws.cache` (byte-bounded LRU, 2 GB default) | | **Worldgen host** (`worldgen-ffi`, `-worker`, `-worker-pool`, `generators`) | 0.94k | warm: 0.1 ms to 370 ms per region | **all** of generation (`worldgen-rs`, 23.7k) | bun:ffi in a Worker pool, one call per 256³ region. The worker copies the result tight and transfers it to main | | **Normals** (`normals-worker(-pool)`, `normals-cache`, `lod-normals-policy`) + `common/voxel-normals-svt.ts` 3048 | 0.7k + 3.0k | **yes**: every served region and every edit's 26-neighbour halo | **none** | a TS Worker pool. Each build job **structure-clones the region plus 26 neighbour trees (up to ~13 MB)** onto the worker, and the result is cloned back. This is 3.9 s of every 20 s of main-thread time during an arrival (`stream-speed.md` §5) | | **Surface initiators** (`surface-initiators-*`, `physics/surface-initiators-native`) | 1.0k | warm | **all** of the build (`physics-rs`) | a Worker pool calls bun:ffi. Each job clones 7 trees in, and the SoA is cloned back. 0.7 s of every 20 s | | **Persistence** (`store`, `structure-store`, `normals-cache`, `coarse-display-store`, `SI cache-store`, `entity-store`, `accounts`) | ~2.15k | warm: 1.35 s of every 20 s during an arrival | none | `bun:sqlite`, synchronous, on the main thread (10 files) | | **Entities + components** (`entity-manager` 2431, kinds, `impact-audio`, `effect-events`, `components/`) | 4.5k (2.3k) | warm: entity scope and AI in `serverTick` take 1.9 s of every 20 s | none | none (main thread) | | **Net / sessions / protocol** (`net/session.ts` 2906, `bulk-lane`, `region-wire`, `pose-sync`, `outgoing`, …) + `common/protocol.ts` 5772 + `pose-codec` 505 | 4.1k (3.7k) + 6.3k | **yes**: the main scan takes 5.2 s of every 20 s. The look tick takes p50 1.1 ms and p99 4.3–4.8 ms per tick (pile-huge, 2 sessions; `net-batch.md` §5.7) | none | `Bun.serve` WebSocket `sendBinary` plus the `drain` callback. Deflate runs on Bun's threadpool (`node:zlib`) | | **Physics host** (`host.ts` 1296, `rust-host` 970, `worker-host` 1185, `worker-rust-host` 828, `physics-worker` 342, …) | 6.3k (5.7k) | step **in Rust**. The host pump, writebacks and the snapshot replay run in TS | **the step** (`physics-rs`, 24.9k): detection, broadphase, islands, TGS, sleep, SI, deep contacts | a Bun Worker owns the native World. **DOWN:** `regionPut` structure-clones `nodeBytes`, the palette and the SI arrays (1.5 s of every 20 s on main), and the worker keeps its own JS `WorldState`. `phys_put_region` then does `to_vec()`, a 3rd copy. **UP:** per-pump step batches as transferred typed arrays. Inside the worker, about 10 bun:ffi calls per step, bodies batched through `phys_write_bodies`/`phys_read_bodies` | | **CA host** (`ca-worker-host` 1091, `ca-worker`, `ca-ffi`, harness/bench 1.3k) | 3.5k (6.9k) | off by default (quarantined) | **the step** (`ca-rs`, 32.9k) | a Worker plus bun:ffi. Region puts are cloned like physics. The mirror is bounded to a pinned-active footprint | | **Fixtures** (`fixtures/`, 48 scenes) | 6.0k (0.6k) | boot only. surface-gi spends **4.6 s of its 6.1 s boot in 435 TS CSG edits** (p50 4 ms, p99 116 ms) | none | the FixtureApi: CSG paint, spawn, celestial, env | | **Audio** (`audio/audibility`) | 0.27k | warm (per sound event) | none | main thread | | **Models** (`models/`) | 0.21k | boot | none | main thread, `decodeModelLibrary` | | **Auth / accounts** (`accounts.ts`) | 0.46k | cold | none | `bun:sqlite`. The token is an FNV stopgap (ROADMAP) | | **main.ts** (HTTP, static files, ticks, bench hooks, CA tick) | 2.3k | the tick scheduler | — | `Bun.serve` (static files, COOP/COEP headers, `/ws`) | | bench, scripts, test-support, logger, music manifest | 1.0k | no | — | — | Rust today: | crate | lines | tests | form | |---|---|---|---| | `physics-rs` | 24.9k | 293 | cdylib + rlib | | `ca-rs` | 32.9k | 308 | cdylib + rlib | | `worldgen-rs` | 23.7k | 96 | cdylib + rlib | | `voxel-core` | 3.6k | 47 | rlib | | **total** | **85.1k** | **744** | | Every crate is a library: there is no Rust binary, no async runtime and no SQLite or network dependency. ### 1.2 `common/` as the server uses it I resolved every symbol `server/src` and `client/src` import from `@voxel/common` to its defining file (`logs/server-rust-scope/syms.py`). Tests are excluded. | | files | lines | contents | |---|---|---|---| | shared by server **and** client | 39 | 26.7k | `protocol.ts` (5.8k, 63 message ids, 60 codec functions), `voxel-normals-svt` (3.0k), `svt64-edit` (1.9k), `svt64` (1.3k), `csg` (1.2k), `material` (1.2k), `svt64-patch` (0.8k), `region-build` (0.7k), `pose-codec` (0.5k), `tree-prune`, `celestial`, `core-look`, `value-codec`, `position`, voice/speech/song (~4k: the server derives Speak audio tokens and validates songs), model/palette decode, acoustics mip, the bitmap-font measure (~7k of font tables come along with it) | | server-only | 12 | 2.3k | `physics/` body pool, mass, classify, structure physics, SI core; the prefab catalog and builders; `svt64-solidity`; `world-gen` types | | client-only | 15 | 3.8k | inventory, `svt64-raycast`, voice cues/bodies, snap lattice, `wire-unwrap` | ### 1.3 What forces TS↔Rust parity if the server's logic moves These are the shared pieces the server *runs* and the client *also runs*, where the two must agree: | shared logic | client use | must agree how | precedent | |---|---|---|---| | **Protocol codecs** (`protocol.ts`, `pose-codec`, `value-codec`, `core-look`, `position`, `csg` encode/decode) | decodes everything, encodes C→S | byte-exact wire | none (TS only today) | | **`applyCsgEdit` / edit commands** (`svt64-edit`, `csg`, `svt64-patch`; on net-edit also `common/src/edit-command.ts` and `svtStateHash`) | today: undo and local tools. **On net-edit: every holder replays edits and compares a state hash with the server** | **bit-exact output bytes** (a hash mismatch forces a resync). net-edit already had to replace `Math.hypot` with `sqrt` for cross-engine determinism | physics TS→Rust (bit-identical oracle, `ts-rust-parity.md`); worldgen (byte-identical corpus) | | **Normals** (`buildNormalSVT`, `refreshNormalSVT`, `pruneNormalSVT`) | a CA delta refresh, the structure fallback, the LoD re-promote prune. On net-edit, holders also refresh after a replayed edit | bit-exact if the client's refresh must match the shipped normals. Otherwise "looks the same" | `test:corpus` normals parity exists (TS vs TS) | | `pruneTree` / `viewMinLevel` (`tree-prune`) | the upload-time prune | the server ships the level the client keeps. An ml1 tier re-pruned must be byte-identical (CLAUDE.md, LoD) | — | | `buildRegionTree5` (prefab material) | structure builds | byte-exact (structure hashing/interning) | worldgen corpus | | `celestial` model | the client clock and lighting | same orbit maths from the same config JSON | — | | material table, `structure-id-space`, voice/speech derivation, `bitmap-font` measure | rendering, chat UI | same tables | — | --- ## 2. Bun dependence | Bun API | where (non-test) | what it does here | maps to in Rust | |---|---|---|---| | `Bun.serve` (HTTP + WebSocket, `sendBinary`, `drain`, backpressure status) | `main.ts` | static client, COOP/COEP headers, `/ws`, bulk-lane refill on `drain` | `axum`/`hyper` + `tokio-tungstenite` (or `fastwebsockets`). Drain maps to a bounded per-socket write queue. **WebTransport** becomes possible (`wtransport`), §5.5 | | `bun:ffi` (`dlopen`, `ptr`, `toArrayBuffer`) | 9 files: physics, CA, worldgen, SI | native calls | direct calls; the boundary disappears | | `new Worker` + `postMessage` | 7 files: physics, CA, worldgen, normals and SI pools | thread isolation; every hand-off is a copy | `std::thread`/`rayon`/`micropool` over shared `Arc` data, no copies | | `bun:sqlite` | 10 files (6 stores + accounts + harnesses) | world, structures, normals cache, coarse display, SI cache, entities, accounts | `rusqlite` (same SQLite files, same schema) | | `bun:test` | 114 server and 65 common test files | ~2,200 tests behind `scripts/test-shards.ts` | `cargo test` for Rust-owned code. Bun keeps the TS (client/common) tests | | `Bun.build` | `client/build.ts` | the client bundle and its 3 worker bundles | **unchanged in every option**: client tooling, not the server runtime | | `node:zlib` deflate-raw (threadpool) | `net/region-wire.ts` | region payload compression, level 2 | `flate2`/`libdeflater` on a worker thread | | `Bun.file` / `Bun.write` / `node:fs` | `main.ts`, captures, prefabs, models | static files, capture POST, loading `.vplib`/`.modellib` | `tokio::fs` / `std::fs` | | `Bun.CryptoHasher` / `Bun.hash` | `world/structures.ts` | SHA-256 for structure interning | `sha2` (already a worldgen-rs dev-dependency) | | `bun:jsc` `heapStats`, `process.memoryUsage` | `worker-memtrace.ts` | the `VOXEL_MEMTRACE` per-thread trace | jemalloc/mimalloc stats; per-arena counters | | `Bun.nanoseconds`, `import.meta.dir` | timing, paths | — | `Instant`, `env!`/config | | `bun --watch` | `dev:server` | hot reload | `cargo watch` (rebuild and restart, seconds rather than instant) | | Bun as script runner | `scripts/` (61 files, 39k lines), `bench/`, the gate | harnesses, gates, fixtures-physics, the suite | stays Bun: tooling can drive a Rust server over the wire like any client | **Bun-specific behaviour the code depends on or works around:** - the shard runner retries the JSC panic (§3.6); - `console.log` drops lines into a slow pipe, so `scripts/stdout-flush.ts` exists; - `workerPoolSize: 0` in tests, because terminating Workers that are still loading modules is where Bun 1.3.13 crashes most. --- ## 3. Why move: the evidence Measurements are mine unless cited. They were taken on nazrin (8 vCPU) with no `/tmp/gi-gate*.lock` held (all four lock files were checked free with `flock -n`), load 1.9–3.5. Scripts and logs are in `logs/server-rust-scope/bench/`. ### 3.1 GC and embedder-memory mark-compacts (the open item) - The open item (`js-alloc-2026-10.md` §3.2 and §5 item 1; `perf-hygiene.md` §1) is in the **browser**. About 11 mark-compacts per route (mean 6.1 ms) are triggered by V8's *global* limit, which counts Blink-owned WebGPU encoders and views and read-back copies. - That is client JS on Chromium. **Moving the server to Rust changes nothing there.** - On the server, the 2026-07 balloon work (`voxel-nvidia-gpu-wedge` notes, merge 21aac4bf) found about 100k live JSC objects, `--smol` with no effect, and the residual being **allocator (mimalloc) retention from buffer churn**, not JS garbage. - No server GC pause has been reported as a problem in any doc. This is not a reason to move. ### 3.2 Worker `postMessage` copies (the real cost) Round trip main → worker → main, Bun 1.3.13 (`bench/pm-bench.ts`): | payload | structured clone | "transfer" | |---|---|---| | 64 KiB | 0.13 ms | 0.08 ms | | 1 MiB | 1.15 ms | 0.68 ms | | 6 MiB | 8.2 ms | 6.6 ms | | 13 MiB | 14.7 ms | 11.4 ms | | 27 × 500 KiB (normals-job shape) | 16.4 ms | — | - In Bun, transfer of a large buffer is only about 20–40 % cheaper than a clone (it is not the near-free ownership move a browser gives). - In production (`stream-speed.md` §5, surface-gi arrival, 20 s CPU profile) the main loop has **no idle time**: - normals pool posts take 3.9 s; - the physics relay takes 1.5 s; - SI takes 0.7 s. - That is **6.1 s of 20 (30 %) spent moving bytes between Bun threads**, with the main scan at 5.2 s. A bigger stream budget or a bigger gen pool changed nothing: "the loop, not the pools, is the limit." - `stream-speed.md` §7 item 3 already names the in-Bun fix: SAB-backed region bytes. It is unbuilt; it would touch every cache writer, the store and the relay. ### 3.3 FFI crossing overhead (not a cost) `bench/ffi-bench.ts`, `libphysics_rs.so` and libc: | call | ns/call | |---|---| | JS no-op function | 0.8 | | `phys_abi_version()`, no args | 8.9 | | libc `labs(i64)` (BigInt conversion) | 44.5 | | `memset(ptr(u8[64]))`, including `ptr()` | 136 | | the same, cached pointer | 98 | | `memset` 6 MiB, native | 84 µs | | JS `slice()` 6 MiB | 855 µs | - The physics step makes about 10 FFI calls per step, with bodies batched through `phys_write_bodies`/`phys_read_bodies`. So FFI costs **well under 2 µs per 16.7 ms step**. - The native world store takes a 3rd copy (`to_vec`) on every `phys_put_region`. That is a design choice, not an FFI cost: the bytes could be shared (§4, option D). ### 3.4 Single-thread contention: look tick, edits, scan - **Look tick** (30 Hz): p50 1.1 ms, p99 4.3–4.8 ms (pile-huge, 2 sessions, after net-batch; `net-batch.md` §5.7). Cheap on its own, but it shares a thread with: - the scan (5.2 s of 20); - SQLite (1.35 s); - gen completion (0.8 s); - entity scope and AI (1.9 s); - the clone traffic above. - Before the physics Worker, a viewer joining realistic-island-16 put the pump into 13–32 s of debt (`physics-worker.md` §1). That is solved by the Worker, at the price of the mirror. - **Edits:** `applyCsgEditFull` runs on the main thread, and then the 26-neighbour normals halo goes through the cloning pool. The fixture boot log times 435 edits: p50 4 ms, p90 13 ms, p99 116 ms, max 178 ms. In surface-gi that is 4.6 s of a 6.1 s boot. - net-edit measured about 205 KB of results per sphere edit before its command change (`net-entity.md`). The edit CPU is TS, and while it runs it blocks the look tick. ### 3.5 Server memory envelope - The 2026-07 bound (merge 21aac4bf): - `REGION_CACHE_MB` 2048; - the SI warm cache at 48 M cells ≈ 288 MB; - the coarse-display and normals caches. - The worst case with every class at its bound is **about 10.5 GB**. The deploy guidance is MemoryMax ≥ 12 G, or `REGION_CACHE_MB=1024`. - The **physics Worker mirrors the region cache about 1:1** (`STREAMING-AND-MEMORY.md` §2.1: "budget roughly DOUBLE"). The mirror sits in the Worker's JS `WorldState` plus the Rust copy. - The rest is mimalloc retention. Both are consequences of isolated heaps, not of TS. - Idle RSS (`bench/boot.txt`, 5 s after listening, 30–39 threads): | fixture | idle RSS | |---|---| | bare | 312 MB | | slab-only | 311 MB | | pile-huge | 327 MB | | realistic-island-16 | 319–324 MB | | surface-gi | 582–598 MB | The ~310 MB floor is about 8 Bun Workers, each a JSC VM with the common bundle loaded (normals 1.0 MB, physics 1.2 MB, SI 1.0 MB of bundled JS each). A Rust server's floor would be tens of MB. That matters only for small deploys. ### 3.6 Startup `bench/boot.sh`, time from exec to "Listening", 2 runs each: | fixture | to "Listening" | where the time goes | |---|---|---| | bare / slab-only | 0.31–0.39 s | Bun and module load | | pile-huge | 1.70–1.76 s | 500 spawns, 1.2 s | | realistic-island-16 | 2.42–2.49 s | — | | surface-gi | 6.07–6.19 s | **4.6 s is 435 TS CSG edits** | Runtime startup is not a cost. The fixture-build time is the TS edit path, the same thing §3.4 measured. ### 3.7 Crash and panic history - **No recorded Bun crash of a running game server.** Every `oh no: Bun has crashed` among the `logs/` files on nazrin (11 run logs) is a `bun test` shard: a JSC segfault, usually in shards that spawn and terminate Workers. - That class has cost real engineering: - `scripts/test-shards.ts` with panic-only per-file retries; - 32 shards, 4 parallel; - `workerPoolSize: 0` conventions; - `BUN_JSC_useFTLJIT=false` notes (known-issues). - It is a tax on the test loop, not on players. - Other Bun-isms worked around: - `console.log` drops lines into a slow pipe (`scripts/stdout-flush.ts`); - deploy ships `oven/bun:1.3.14` while dev runs 1.3.13. - The physics Worker has a graceful death-and-restart path. No production trigger is recorded. ### 3.8 What Bun buys (the case against moving) - **One language for shared logic.** 26.7k lines of `common/` run on both sides. The protocol (63 messages) is one file, and a wire change is one edit. - net-edit *depends* on this: client prediction and server results are compared by `svtStateHash`, so edit and normals code must be bit-identical on both sides. - With a Rust server, that guarantee comes from a parity corpus or from shipping the Rust code to the client as wasm. - **Iteration speed.** - `bun --watch` restarts in about 0.35 s. - TS changes need no build. - Agents edit TS server code and tests freely. - In Rust, each change costs a 15–40 s release build; physics, CA and worldgen already live with that. - **The test suite.** 615 server tests (28k lines) plus 867 common tests run on the same runner as the client tests. Many server tests drive the real `Bun.serve` session path with in-process fake clients. - **Fixtures in TS.** 48 scenes (6k lines) use `FixtureApi`: CSG paint, spawn, kinematic scripts and celestial config. `scripts/fixture-physics`, `physics-suite --raw` and the GI gate all boot them. Porting them means either Rust scenes or a scene format plus a script host. - **Zero runtime dependencies** and one container stage for the server. - **The bundler.** `Bun.build` serves the client in every option, so Bun remains a toolchain dependency regardless. --- ## 4. Goal options Effort is in **TS lines that move**, with a calibration from this repo's own ports, which agents ran: - `physics-rs` went from its first commit (2026-06-06) to TS retired (2026-06-14) in about 8 days. The TS oracle made it mechanical. - `worldgen-rs` was flipped canonical 2026-06-16, days after it started, against a byte-identical corpus. Ports with a bit-exact oracle are fast. Ports of timing- and concurrency-shaped code (sessions, streaming, backpressure) have no oracle, and that is where the risk is. | | end state | what moves | effort | risk | gained | lost | |---|---|---|---|---|---|---| | **A** | Full Rust server binary. Client stays TS. Shared logic goes to Rust + wasm, or stays in TS with parity | all 38k of `server/src` + 2.3k server-only common; Rust ports of the ~15k of shared common the server runs (protocol, CSG/edit, normals, prune, pose/value codecs, voice/speech tokens, celestial); 48 fixtures; re-expressing ~615 server tests | **very large**: ~55–60k TS lines to Rust, ~2–4 months of agent rounds at the past pace, longer for the unoracled parts | **high**: net/session/backpressure behaviour has no bit oracle (only the NET_PROBE / stream-speed / net-batch benches); protocol drift; fixture port; loses the TS shared-code guarantee that net-edit relies on | no copies or Workers; one memory model (~10.5 → ~6 GB worst case, the mirror gone); idle floor in tens of MB; no JSC panic tax on server tests; **WebTransport** servable (§5.5); real threads for scan/encode | TS iteration on server code; one-language protocol; the server tests on one runner; TS fixtures (or a script host to keep them) | | **B** | Rust core **process** owning the tick, world, physics, CA and networking. A thin Bun shell over IPC for fixtures, scripting and tooling, or no shell | as A minus fixtures, accounts and bench, which stay TS behind an IPC API | large: ~45–50k lines plus an IPC protocol | high, as A, plus a new process boundary (IPC serialisation is the copy problem again, at lower volume) | as A | as A, plus two processes to deploy and supervise | | **C** | Status quo plus opportunistic extraction under explicit criteria | case by case | small per step | low | keeps everything Bun buys | the copy/mirror tax stays until someone builds SAB regions in Bun, a large cross-cutting TS change (`stream-speed` §7.3) | | **D (recommended)** | **Native world core inside the Bun process**: one Rust library owns the region store (bytes, palettes, versions), normals, SI, CSG/edit apply and the encode-ready tiers. Physics and CA read it **in place** from their threads. Bun keeps `Bun.serve`, sessions, the protocol, entities, fixtures, accounts and tests | world manager internals (~6k), the normals pool + `voxel-normals-svt` (~3.7k), SI pool/cache (~1k), edit apply (`svt64-edit`/`csg`/`svt64-patch` server paths, ~4k), the worker-host/relay layers for physics and CA (~3–4k **deleted** rather than ported) | **medium**: ~12–15k TS lines replaced by ~10–14k Rust, much of it deletions. Oracles exist for most of it (`test:corpus` normals parity, `physics-suite --raw`, edit hashes) | **medium-low**: data-movement changes are verifiable bit-exact; the protocol and client are untouched; the one real decision is how the client gets the same edit/normals code (§6, D2) | removes the 1:1 mirror and the 27-tree clones (≈30 % of main-thread time in an arrival); edits/normals off the main thread; the fixture boot faster; the region budget no longer doubles | some TS-editable world code; adds a Rust↔TS handle API to maintain | **Why D over C:** - C's in-Bun fix (SAB regions) has to touch the same places D replaces: every cache writer, the store and the relay. - C's fix still leaves the Rust copy (`to_vec`), the TS normals in a cloning pool, and the worker `WorldState` mirror. - D does that work once, in the language the consumers (physics, CA, SI) already use. **Why D before A or B:** D is phases 1–3 of A (§5). If the owner later wants A, nothing is thrown away. If not, D is a stable end state. The spike behind D (`bench/share-main.ts`): - the main thread created a physics `World`; - a Bun Worker `dlopen`ed the same path and called `phys_world_body_count` on the main thread's pointer, which worked; - `/proc/self/maps` shows a single mapping. Rust statics and heap objects are shared across Bun threads, so a Rust-owned store with `Arc`/`RwLock` (or epoch-swapped immutable region versions) can be read by the physics and CA Workers without a byte crossing `postMessage`. --- ## 5. Phased plan (D, then an A/no-A decision point) Every phase merges on its own, keeps `bun server/src/main.ts` playable with every fixture, and changes no wire bytes. ### Phase 0: baselines and the handle API (small) - **Record the baselines** each later phase must move: - the server arrival profile (`bun --cpu-prof`, the surface-gi pose-0 arrival, as `stream-speed` §5); - `VOXEL_MEMTRACE=1` per-thread memory at the realistic-island-16 and earthlike envelopes; - fixture boot times (`bench/boot.sh`); - the look-tick p50/p99. - **Define the `world-rs` region handle ABI** on `voxel-core`: - put/get/drop by coord; - version stamps; - a borrowed read view: `toArrayBuffer` over native memory for the encode path, no copy. - **Pin the ABI** with the same loud version handshake as the other cdylibs. - **Size:** ~1k Rust, ~0.5k TS. ### Phase 1: one region store, read in place (first, because it is pure data movement and the biggest memory win) - `ws.cache` becomes a TS façade over the native store. - Physics and CA hosts read regions from the store by coord instead of `regionPut`. - **Deleted:** - the worker `WorldState` mirror; - `phys_put_region`'s `to_vec`; - the CA region relay; - most of `worker-host`/`worker-rust-host`'s region machinery (G#3 ordering becomes a version check). - **Gates:** - `physics-suite.ts --raw` bit-identical, per fixture; - `raw-dump-determinism`; - CA `test:ca` for the CA path; - the memtrace envelope, where the physics mirror class should drop to ~0; - the relay's 1.5 s of every 20 s in the arrival profile should go. - **Size:** ~3–5k Rust; ~3k TS removed. ### Phase 2: native normals and SI in place - Port `voxel-normals-svt` (3k) to Rust over the store. - Build and refresh on Rust threads (`micropool`), reading neighbours in place: no 27-tree clone. - The SI pool reads in place as well. - **Gates:** - `test:corpus` normals parity, re-pointed to TS-vs-Rust; - `NORMAL_SVT_BUILDER_VERSION` unchanged; - the arrival profile, where the 3.9 s + 0.7 s of posts should go. - **Client side:** depends on owner decision D2 (§6). - **Size:** ~4k Rust; ~1.5k TS removed (pools, worker entries). ### Phase 3: edits native (after net-edit merges) - `applyCsgEditFull`, the edit-command apply, `svtStateHash`, undo patches and the halo refresh run in Rust. - The main thread calls in, or posts to a Rust edit thread with ordered results. - **Gates:** - the edit hash agrees with the client's on net-edit's tests; - `svt64-edit` tests re-pointed; - the surface-gi fixture boot (4.6 s of edits) as a measured win. - **This phase is where TS↔Rust parity of shared code becomes binding** (D2). - **Size:** ~4k Rust; ~0.5k TS server glue removed. The common TS stays for the client unless D2 picks wasm. ### Phase 4: stream encode off the loop (the decision point) - Move the main scan's per-region work (prune to `serveTargetMl`, tier encode, deflate, the 256 MiB region-wire cache) into Rust. - TS keeps the session logic and hands bytes to `sendBinary`. - **After this phase, decide:** - stop at D; - or continue to A (Phase 5: sessions, net, entities, sqlite, accounts and fixtures to Rust; a Rust `Bun.serve` equivalent; Bun as tooling only). - **Size:** ~3k Rust. ### Phase 5 (A only, not recommended yet) - **Size:** ~40k TS lines. - **Order:** `bun:sqlite` stores → `rusqlite` (same files) → entities and kinds → sessions, protocol and net (WebSocket first, WebTransport after) → fixtures (a Rust `FixtureApi` with the scenes ported as data or Rust) → accounts. - **The server is playable throughout:** keep the TS server runnable against the shared native core until the Rust binary passes the same bench and gate scenarios, then delete it. ### 5.1 Tests, fixtures and the GPU gate across phases - **Tests:** - Through Phase 4 the TS test suite stays and keeps exercising the server end to end; native code under it just changes. - Rust-owned code gains `cargo test` coverage the way the 3 crates have (744 tests). - Parity tests (normals corpus, edit hashes) run in `bun test` against the cdylib, as `surface-initiators-native` tests do today. - **Fixtures:** unchanged through Phase 4. They call the same `FixtureApi`, which writes through the native store. The physics harness determinism rule (no wall clock, no pool Workers, synchronous build) must hold in the native store too: regions are built in the step that reaches them. - **GPU gate:** server changes do not touch the renderer, so the surface-GI GPU lane is not required per phase. The CPU arrival benchmarks and `physics-suite --raw` are the gates. - Run the SwiftShader nightly once after Phase 2. - Run the nightly again after Phase 4. - Shipped normals and tiers must be byte-identical, so the gate should be a no-op. ### 5.2 One protocol source of truth - **D never moves the protocol.** `common/src/protocol.ts` stays the single source, and Rust hands back only bytes that are already payloads (tiers, normals, edit results), framed by TS. - **Only A needs a second implementation.** Options for A, in order of preference: 1. a schema (63 messages) that generates both the TS and the Rust codecs; 2. TS stays authoritative, with a golden-bytes round-trip corpus in both languages (the worldgen precedent); 3. Rust codecs shipped to the client as wasm. This touches the net Worker's decode of every frame; Safari runs wasm fine, but it adds a load step. ### 5.3 Rule compliance - **Parity:** the region store, normals and edits serve terrain and entity structures through the same code; structures already use the same SVT64/normals builders. No kind-specific path is introduced. - **No mode shifts:** wire bytes and timing semantics are unchanged. - **No gravity-axis special-casing:** nothing here is spatial policy. - **Owner preference:** D deletes more TS than it adds Rust in Phases 1–2 (the relay, mirrors and pools). ### 5.4 Size per phase | phase | Rust added | TS removed | main win (to be measured against Phase 0) | |---|---|---|---| | 0 | ~1k | — | baselines | | 1 | 3–5k | ~3k | the physics mirror (≈ REGION_CACHE_MB of RSS), 1.5 s of every 20 s of main-thread time | | 2 | ~4k | ~1.5k | 3.9 + 0.7 s of every 20 s of main-thread time; the normals off the JS heap | | 3 | ~4k | ~0.5k (server) | edit latency off the main thread; fixture boot −4.6 s (surface-gi) | | 4 | ~3k | ~1.5k | the 5.2 s scan's encode/prune share | | 5 (A) | ~45k | ~40k | WebTransport, no Bun runtime | ### 5.5 Transport and Safari - Safari is unaffected server-side in D. - In A, the Rust server can serve **WebTransport** directly (`wtransport`). `net-entity.md` §9 lists it as "not Bun" (oven-sh/bun#13656): datagrams for poses and a stream per edit or region remove TCP head-of-line blocking under loss (§4–5 there: a 2.4–2.9× smoothness gain at 100 ms / 2 %, none on clean links). - Safari supports it only from **macOS/iOS 26.4**, and stable Caddy 2.11 cannot proxy it. Any WebTransport lane still needs the WebSocket path as a fallback (3–5 % of clients). - D does not block WebTransport: a Go or Rust sidecar is possible today (`net-entity` §9). WebTransport is a reason for A only if the owner wants it without a sidecar. --- ## 6. Owner decisions | # | decision | options and the numbers behind them | |---|---|---| | **D1** | **Goal.** Adopt "finish the server core in Rust" as a goal, and which end state | **D** (recommended: ~12–15k TS replaced, medium-low risk, removes the measured ~30 % main-thread copy tax and the 1:1 region mirror) · **A** (~55–60k lines, high risk, adds WebTransport and drops the Bun runtime; the GC item is client-side, so A does not fix it) · **C** (no goal; adopt §6 D5's criteria) · B is dominated by A (the same port plus an IPC boundary) | | **D2** | **How the client runs shared edit/normals code once the server's copy is Rust** (binding from Phase 2/3; net-edit makes edits hash-checked) | (a) **keep TS on the client** with a TS↔Rust bit-parity corpus (the physics and worldgen precedent; two implementations to maintain, and drift shows up as hash resyncs); (b) **compile the Rust crate to wasm for the client** (one implementation; physics-rs → wasm was 180 KB brotli in `net-entity`; Safari runs wasm; costs a wasm load and a JS↔wasm copy per edit on the client); (c) keep the edit apply in TS on the server too (D stops at Phase 2). Needs a measurement of the client edit/normals cost under wasm vs TS before choosing | | **D3** | **Start Phase 3 only after net-edit merges** | the edit path is being rewritten now (`edit-command.ts`, `svtStateHash`, `Math.hypot`→`sqrt`). Porting it mid-flux doubles the work | | **D4** | **Memory target** that Phase 1 must hit | today: the worst case ~10.5 GB with the physics mirror ≈ REGION_CACHE_MB (2 GB default); deploy MemoryMax ≥ 12 G. Proposed acceptance: the mirror class ~0 in memtrace, the worst case ≤ ~8.5 GB at defaults | | **D5** | **If C: criteria for what moves next** (proposed) | move a piece to Rust when **all** of these hold: (1) it is measured as ≥ 10 % of main-thread time in a standard profile (the arrival, the look tick, the edit burst) or ≥ 1 GB of the envelope; (2) a bit-exact oracle exists or can be built (corpus, `--raw`, a hash); (3) the move deletes the TS side, not mirrors it, unless the client needs it (then D2 applies). By these criteria, normals (19.5 % of the arrival) and the physics relay plus mirror qualify today; sessions and protocol do not | | **D6** | **Bun version** | dev runs 1.3.13 and deploy runs 1.3.14; the JSC test panic is version-specific. Independent of the above: pin one version, and re-test the panic on each bump | --- ## 7. Method notes and caveats - **Line counts:** `wc -l` on non-test `.ts` files, main 20d4dbe2. - **The common split** is symbol-level (named imports resolved to their defining file). It undercounts files reached only transitively inside `common`. - **The microbenchmarks** are single runs of medians over 30 round trips (pm) and 5 M calls (ffi), on an idle-ish 8-vCPU VM. They are good to about ±20 %. The `postMessage` "transfer" result is surprising enough to re-check on a newer Bun before relying on it in design. - **Boot times:** 2 runs each. The surface-gi edit timings come from the server's own log lines. - **Cited, not re-measured:** the arrival profile (`stream-speed.md` §5, taken under a held gate lock and load 8–19), the look-tick numbers (`net-batch.md`), the memory envelope (merge 21aac4bf notes) and the GC numbers (`js-alloc-2026-10.md`). Phase 0 re-baselines all of them on a quiet box. - **Nothing was built** beyond the throwaway benches in `logs/server-rust-scope/bench/`.