# The native world core (option D): Phase 0 (the region-handle API, shared code as wasm, baselines), Phase 1 (one region store, read in place), Phase 2 (normals and surface initiators on native threads, reading the store in place) and Phase 4 (the stream encode off the main thread) Status: the edit / normals core (option (b) of §3.9 plus the scoped refresh) is built: `docs/wasm-edit-core.md` — the TS edit, normals and patch code is deleted, the client runs voxel-core as wasm and the server natively. **Phase 4 built** on branch `rust-core-p4` (from main 4c4b1b4e); its results, the Phase 3 status and the A / no-A inputs are §8. **Phase 2 built** on branch `rust-core-p2` (from main 144feeed, Phase 1 merged); its results are §7. **Phase 1 built** on branch `rust-core-p1` (from main e0f4f5fd + `rust-core-p0`); its results are §6. **Phase 0 done** on branch `rust-core-p0` (from main 20d4dbe2). Items 1 (handle API and spike) and 2 (the shared-code-to-wasm study) were done on Bun 1.3.13; item 3 (the baselines, §5) and the re-runs of the Bun benches were taken on **Bun 1.3.14** once the gate was met. **Which code each number comes from.** Unless a row says otherwise, every number is from this branch's base, **main 20d4dbe2** (the branch changes no server or client runtime code). The rows marked *net-edit TS* ran the edit TS from `origin/net-edit` ad010330 (not merged), which scopes the flag walk and compacts against the live size; its output bytes matched the 20d4dbe2 corpus on every case here. - Background: `docs/server-rust-scope.md` (branch `server-rust-scope`). It covers the inventory, the copy tax and the D phases. - Scratch, corpora and raw results: `logs/rust-core-p0/`. - Bench scripts: `bench/rust-core/`. - Spike crates: `world-rs/` (the region store) and `voxel-wasm/` (the client module). - New voxel-core modules: `csg.rs`, `svt64_edit.rs`, `normals_svt.rs`. The edit/net path (`server/src/net`, region edits, `client/src/world/region-manager.ts`) is being changed on branch `net-edit`, and nothing here touches it. --- ## 0. Summary **Region handles (item 1).** - One process-wide Rust store holds every region as an immutable, `Arc`-counted version. A reader *pins* a version and reads it with no lock held. A writer swaps in a new version under a sharded lock. - The spike shows the main thread, a Bun Worker and Rust threads reading the same bytes in place: - 27 earthlike regions (151 MiB): structured clone to a Worker costs **136 ms**; posting their coords and pinning them in the Worker costs **3.4 ms**. - The centre region alone (4.5 MiB): 3.8 ms by clone, **0.03 ms** by pin. - Readers see whole versions while the main thread replaces them, in a Rust stress test and from a Bun Worker. - JS gets a zero-copy view (`toArrayBuffer`) for the encode path. Its median cost is 0.4–0.9 µs, but JSC counts each view as external memory, so views trigger GC (p99 850 µs). Views must stay short-lived. **Shared code as wasm (item 2).** - `applyCsgEditFull`, the CSG shapes, the brush decoder, `buildNormalSVT` and `refreshNormalSVT` are now in Rust (voxel-core). They are **bit-identical to TS** on 40 corpus cases, natively and as wasm. - On the client (headed Chromium on utsuho), one edit plus its normals refresh on a 4.7 MB surface region costs: | | sphere edits | stamp | |---|---|---| | TS | 26–31 ms | 95 ms | | wasm, regions copied in and out per edit | 17–20 ms | 67 ms | | wasm, regions resident in wasm memory | 15–17 ms | 64 ms | - Under JavaScriptCore (Bun, Safari's engine) the gap is wider: TS is 52–72 ms, wasm 13–18 ms. - The module is **30–35 KB brotli** (107 KB raw). Compile takes 5–10 ms and instantiate 0.2 ms. It needs no threads, so it does not need cross-origin isolation. - **The finding that matters more than the language:** about 11 ms of every edit, in TS and in Rust alike, is a whole-region flag refresh plus a pool copy. The brush walk itself is 1–2 ms. §3.3. **The algorithm already beat the language (net-edit TS, measured).** net-edit's scoped flag walk takes the same sphere edit + refresh to **7–10 ms in TS on V8** and **8–14 ms on JSC**: faster than this branch's wasm port of the *20d4dbe2* algorithm (15–17 ms). A like-for-like D2 comparison needs the Rust port to follow net-edit's algorithm first (§3.2, §3.9). **Baselines (item 3, Bun 1.3.14, §5):** - **Arrival** (surface-gi pose 0, headed Chromium on utsuho over vmlan, quiet nazrin, 3 runs): connect → settle in 7.7–8.9 s. The server main thread is busy **25–29 %** of it (2.24–2.27 s). `Worker.postMessage` takes **0.50–0.55 s** of that: normals 0.32–0.39, SI 0.09–0.11, physics relay 0.06–0.07. The scoping doc's "zero idle, 6.1 s of 20 in postMessage" (stream-speed §5: a loaded box, the DERP era, an older base) does **not** reproduce on a quiet box. - **Memory:** idle RSS 280–286 MB bare, 456–490 MB surface-gi; arrival peak 1.04–1.07 GB. A fast earthlike walk (50 m/s, 12 min) reached **5.6 GB RSS at a 1.77 GB region cache**; the physics Worker's JS mirror alone was 1.35 GB (0.76 × the cache), plus its Rust copy. - **The same walk found a main-thread stall:** `ensurePhysicsRegionReady` (physics `worker-host.ts`) generates regions **synchronously on the main thread** when the avatar outruns the gen pool: 44 s of a 90 s profiled walk, and the 30 Hz look tick ran **0.5–2.4 times a second**. Phase 1's store fixes it structurally (§5.3). - **Boot:** bare 0.69–0.85 s, surface-gi 6.45–6.53 s (4.9–5.0 s of it in 435 TS CSG edits: p50 6 ms, p99 119–125 ms). - **Look tick** (whole `lookTick`, pile-huge, 2 headless clients): p50 1.13–1.21 ms, p99 12.9–14.0 ms. **Phase 2 (§7):** normals and surface initiators are built on native threads from pins of the store's versions; the normals and SI Worker pools are deleted. Native normals are byte-identical to the TS clients run (a new `test:corpus` file), `physics-suite --raw` is unchanged. Arrival: main-thread busy 2064–2129 → 1612–1651 ms, `postMessage` 344–353 → 5 ms. Idle RSS bare 289–297 → 146–152 MB; the 12-minute walk 4011 → 3235 MB at the cache bound. The walks' look tick is 22 / 26 / 27 Hz (50 m/s 90 s / 5 m/s / 50 m/s 12 min): it is limited by long tasks (generation completions, a 1.1 s join, `_tickImpacts`), not by load. Fresh-world generation latency is six builds sharing one micropool (§7.8). **Phase 4 (§8):** the stream encode (prune to the wire level, the normals prune, the framing) runs in voxel-core on a native pool from pins, writing each message straight into a JS buffer; wire bytes are identical to main (1520 frozen digests; 3412 messages recorded on both trees). Arrival main-thread busy 1403–1434 → 893–949 ms (the prune's 450–468 ms is gone); walks and the look tick unchanged (already 29 Hz). The client keeps the TS `pruneTree` (faster than a wasm copy-in). Recommendation: stop at D (§8.10). **Bun "transfer" re-check:** - 1.3.13: a one-way transfer was cheap (13 MiB in ~2 ms vs a 12 ms clone); an **echo** (a transferred buffer transferred on) cost about a copy, which is what the scoping doc measured. - **1.3.14: the echo is fixed** too: 13 MiB round trip 0.8–1.1 ms by transfer vs 10–16 ms by clone. Transfer is now a real ownership move in both directions. - D is unchanged: the normals jobs clone trees the main thread must keep, and transfer cannot help those (§2.7). - **One Bun 1.3.14 crash**: a segfault during the surface-gi fixture boot with `--cpu-prof` and 9 Workers spawned (1 of 9 profiled boots; none in the 6 unprofiled boots or the other runs). `logs/rust-core-p0/baselines/crashes/`. --- ## 1. What was built | piece | where | lines | tests | |---|---|---|---| | Region store + C ABI (spike) | `world-rs/src/{store,ffi,lib}.rs` | 526 | 4 Rust tests (`world-rs/tests/store.rs`): pin lifetime, byte accounting, `PinCache`, concurrent readers vs a writer | | CSG shapes + brush wire decoder | `voxel-core/src/csg.rs` | 598 | corpus | | `applyCsgEditFull` | `voxel-core/src/svt64_edit.rs` | 973 | `voxel-core/tests/csg_edit_corpus.rs`: 34 cases bit-identical | | `buildNormalSVT` / `refreshNormalSVT` | `voxel-core/src/normals_svt.rs` | 1672 | `voxel-core/tests/normals_corpus.rs`: 2 builds + 15 refreshes bit-identical; 3 unit tests | | wasm module | `voxel-wasm/src/lib.rs`, `build.sh` | 185 | the browser/Bun bench checks every result against TS | | benches and corpora | `bench/rust-core/*.ts` | ~1.9k | — | - **voxel-core's `parallel` feature:** micropool became an optional, default-on feature. The wasm build turns it off. Without that, micropool pulls in wasm-bindgen/js-sys and the module grows to 621 KB with JS imports. The native crates are unchanged: they build with the default feature on. - **The corpus:** `bench/rust-core/make-corpus.ts` builds it. - Input: a real earthlike 3×3×3 block, seed 42691, around the spawn region (4, 0, −4). The centre region is 4.7 MB. - Edits at the surface of the centre column: sphere carve r 4/12/24, sphere fill, a border sphere, box, cylinder, ellipsoid and a rotated stamp. - `make-csg-corpus.ts` adds 25 cases: masks, first-surface, rotated boxes, multi-brush lists, edits crossing the faces, stamps at 0/45/90°, an unknown stamp key, REGION-tier palettes and RAW16. - `make-normals-extra-corpus.ts` adds 6 cases: palettes in the centre and in a neighbour, missing neighbours, edits at x 0 and x 255, a full-window refresh and a degenerate bbox. - **Not ported:** - The `text` brush, which needs the bitmap-font tables. It decodes, and the apply skips it: `has_unsupported_shapes` flags such lists, and those stay on TS. - `pruneNormalSVT`, `readNormalSVT`, and the test-only `buildNormalSVTReference`. - **Must follow net-edit:** net-edit replaces `Math.hypot` with `sqrt` in `_normalize3` (the first-surface normal), scopes the flag walk to the edit window and compacts against the live size. The Rust copy follows 20d4dbe2 and needs all three when net-edit merges (the last two are where the edit time is, §3.3). --- ## 2. Region-handle API (item 1) ### 2.1 Ownership - **One store per process**, owned by Rust: `world_rs::store::WorldStore`. - It holds each coord's *current* version as an `Arc`. A version carries: - the coord; - the caller's `version: u32` (the same TS region version that rides the wire); - the node bytes, and optionally the palette and the normals. - **A version is immutable once inserted.** An edit, a regeneration or a CA write inserts a new version. This is copy-on-write at region granularity, which is already what the TS edit path does (it returns a fresh `nodeBytes`). - **The handle is a pin** (`*const RegionVersion`, one `Arc` reference). - While a pin lives, the bytes do not change and their address is stable. - It stays valid after the store replaces or drops the coord. - The version is freed when the last pin goes. ### 2.2 Lifetime - **Explicit:** `wr_pin` / `wr_unpin`. The TS wrapper is `pinRegion(...).release()` in `bench/rust-core/world-ffi.ts`. Hot paths (encode, worker jobs) use this form. - **GC-owned:** `toArrayBuffer(ptr, 0, len, pin, wr_pin_finalize_addr())`. The ArrayBuffer owns the pin, and collection releases it. The spike verified this: - 64 views kept a dropped version alive; - `Bun.gc` released it (live versions went 28 → 27). - Use this only as a backstop: native memory is invisible to the GC's sizing until the view is collected. - `.ptr` on a bun:ffi symbol is not a usable function pointer (the spike got a denormal double). The deallocator address has to come from Rust (`wr_pin_finalize_addr`). ### 2.3 Workers - Bun maps the `.so` once per process. A Worker that `dlopen`s the same path gets the same statics, and a store pointer posted as a number works there. The scoping doc's spike showed this, and so does this one: every Worker figure below uses the main thread's store. - **Phase 1 needs one `.so`.** Physics and CA must read the same store from Rust code, so they cannot live in separate cdylibs that each link their own copy of `world-rs`. - `world-rs` links worldgen-rs as an rlib already, and `libworld_rs.so` exports every `wg_*` and `wr_*` symbol. - `wr_generate_into` builds a region straight into the store, with no JS crossing. Its output is byte-identical to the corpus. - Phase 1 links physics-rs and ca-rs the same way: one `libvoxel_native.so`. ### 2.4 Concurrency and locking - The store has 16 `RwLock` shards, keyed by a coord hash. - **Readers** take a read lock only for the lookup and the `Arc` clone (`version_lookup` 0.14–0.2 µs from JS). - **Writers** take the write lock only for the insert, a pointer swap. No reader ever blocks a writer for longer than that, and no writer invalidates a reader's bytes. - `PinCache` is the per-step consumer shape (physics, CA). It revalidates all its pins against the store's `generation` counter with one atomic load. - **Measured:** - The Rust stress test runs 4 readers against 1 writer replacing 32 regions 200 times. No reader saw a torn version. - From a Bun Worker, 2 M voxel reads through the store cost **143 ns/voxel idle** and **181 ns/voxel** while the main thread replaced the region about 500 times. Every read went through the lookup, and the results were identical. - The physics read pattern would use `PinCache` and skip the per-voxel lookup. ### 2.5 Versioning - Each insert carries the caller's region version. `wr_version(coord)` is the cheap check. - The store-wide `generation` bumps on every put or drop. - The physics worker's G#3 ordering (hash-tracked `regionPut`s) becomes "is my pin's version the current one". There is no message ordering to maintain. ### 2.6 JS reads without copying (the stream-encode path) - Pin, then `wr_pin_desc` (pointers, lengths and version in one crossing), then `toArrayBuffer` over the node bytes. This is a zero-copy view; aliasing was verified. - Reading it costs the same as a JS-heap array: a full checksum of 4.5 MiB takes 1.43 ms over the view, 1.42 ms over a heap copy, and 1.23 ms in Rust. - `node:zlib` deflate and `sendBinary` accept the view directly. - **Cost of a view:** median 0.4–0.9 µs, independent of size. But JSC reports the length as external memory, so creating views drives GC: - for 4 MiB views the mean is 83 µs and the p99 850 µs; - in a loop of 1 MiB views, about 22 µs/MiB. - **Rule:** one view per pin, released right after the encode. Never keep views of the whole cache. - **JS must treat views as read-only.** Nothing enforces this. A write would mutate an immutable version that other threads read. Phase 1 should hand JS writable bytes only through `wr_put`. ### 2.7 Spike numbers `bench/rust-core/world-bench.ts` on nazrin. Raw: `logs/rust-core-p0/world-bench-1.3.13.json` (load ~5) and `world-bench-1.3.14.json` (quiet, load < 2). | what | Bun 1.3.13 | Bun 1.3.14 | |---|---|---| | `wr_put` of 27 regions (151 MiB, copied from JS) | 45 ms, 3.3 GiB/s | 28 ms, 5.2 GiB/s | | pin + desc + view + release | p50 0.9 µs (mean 28 µs: GC from the external-memory accounting, §2.6) | p50 0.8 µs, p99 855 µs | | version lookup from JS | 0.14 µs | 0.15 µs | | Worker hand-off, 27 trees, **structured clone** (the normals-job shape) | p50 136 ms, p90 185 ms | p50 121 ms, p90 168 ms | | Worker hand-off, 27 trees, copy-then-**transfer** | p50 3.4 ms, plus the copy (2 ms per 4.5 MiB slice) | p50 1.4 ms, plus the copy | | Worker hand-off, **27 coords, pinned in the Worker** | p50 3.4 ms | p50 2.4 ms | | the same plus a full read of all 151 MiB in the Worker | clone 207 ms; pin + JS read 65 ms; pin + Rust read 54 ms | clone 173 ms; pin + JS 52 ms; pin + Rust 44 ms | | centre region (4.5 MiB): clone vs pin | 3.8 ms vs 0.03 ms | 2.1 ms vs 0.03 ms | | Worker voxel reads through the store, idle / under ~1k puts | 143 / 181 ns | 103 / 141 ns | | GC-owned pins released by `Bun.gc` | yes | yes | | `wr_generate_into` (earthlike centre, Rust → store) | 1.28 s (generation; nothing crosses JS) | — | The clone and pin results must agree, and every checksum matched across clone, pin with JS read, and pin with Rust read. **Bun's "transfer" re-checked** (`bench/rust-core/pm-recheck.ts`, `logs/rust-core-p0/pm-recheck-1.3.1{3,4}.txt`). Round trip with the buffer echoed back, as in the scoping bench, against a one-way post that gets a small ack: | 13 MiB | Bun | echo, clone | echo, transfer | one-way, clone | one-way, transfer | |---|---|---|---|---|---| | `new Uint8Array(n)` | 1.3.13 | 24.8 ms | 13.5 ms | 11.9 ms | **1.9 ms** | | | 1.3.14 | 15.7 ms | **0.84 ms** | 11.5 ms | **1.8 ms** | | `new Uint8Array(new ArrayBuffer(n))` | 1.3.13 | 12.3 ms | 6.3 ms | 6.3 ms | **2.0 ms** | | | 1.3.14 | 10.1 ms | **1.1 ms** | 5.4 ms | **1.9 ms** | - **1.3.13:** the first hop was cheap; the echo (re-transferring a buffer that arrived by transfer) cost about a copy. That is the "barely cheaper" the scoping doc measured. - **1.3.14:** the echo is cheap too. Transfer is now an ownership move both ways; only clones copy. - **Effect on D:** none. The server's large hand-offs are clones of trees the main thread keeps (normals: 27 trees per job; the physics relay), and transfer cannot help those. The pools' results (worker → main) already transfer. --- ## 3. Shared code to wasm (item 2, owner decision D2) ### 3.1 Which code The 26.7k shared lines of `common/`, by candidacy (`logs/server-rust-scope/common-split.txt`): | shared code | lines (TS) | client hot? | Rust twin | wasm candidate? | |---|---|---|---|---| | `svt64-edit` + `csg` (applyCsgEdit, shapes, brush codec) | 1942 + 1231 | **yes on net-edit**: every holder replays every edit, hash-checked | **yes, this branch** (`svt64_edit.rs`, `csg.rs`), bit-identical | **yes**: bulk byte work, one call per edit | | `voxel-normals-svt` (build/refresh) | 3048 | yes: CA-delta refresh, structure fallback; on net-edit the post-edit refresh | **yes, this branch** (`normals_svt.rs`), bit-identical; prune not ported | **yes**: same shape | | `svt64-patch` (`applyVoxelDelta`) | 823 | yes (CA deltas) | yes (`voxel-core/svt64_patch.rs`, byte-twin) | yes, with the above | | `svt64` read/write | 1316 | yes (everywhere) | yes (`svt64_read/write.rs`) | only as part of the above; the renderer's own reads stay JS/WGSL | | `region-build` (`buildRegionTree5`) | 719 | structure builds | yes (worldgen-rs `region_build.rs`, byte-identical) | possible; not hot on the client | | `tree-prune` (`pruneTree`, `viewMinLevel`) | 369 | yes, at upload (per region) | none | plausible later (byte work); small | | `protocol` (63 messages), `pose-codec`, `value-codec`, `core-look`, `position` | 5772 + 505 + 339 + 189 + 189 | every frame, in the net Worker | none | **no**: the output is JS objects, and a wasm decoder still needs JS glue to build them per field; per-message work is microseconds. Only option A needs a second implementation (scoping §5.2: schema-generated codecs are preferred there). Not measured. | | `celestial` | 369 | the client clock and lighting | none | no: tiny maths on a config; parity is trivial | | material table, voice/speech, songs, model decode, fonts | ~7k | UI and audio | partial (`material.rs`) | no | ### 3.2 Speed **Method:** - `bench/rust-core/wasm-bench-core.ts` runs the same cases in three modes: - **TS:** today's client path. `applyCsgEditFull` plus `refreshNormalSVT` on JS ArrayBuffers. The halo is collected as region-manager's `_assembleDeltaNormalsHalo` does it: only the neighbours whose face the refresh window reaches. - **wasm copy:** per edit, the centre region, the previous normals, the needed neighbours and the brush bytes are copied into linear memory, and both results are copied out with `slice()`. - **wasm resident:** the client keeps its regions in wasm memory. Only compute is timed, and the results are viewed in place, which is what a `writeBuffer` upload reads. - Every wasm result is compared byte-for-byte with the TS result, and all matched. - Medians are of 15 runs (Bun) and 25 runs (Chromium), after 3 warm-up runs. **Headed Chromium 149 (V8) on utsuho** (4 vCPU; `logs/rust-core-p0/wasm-bench-chromium-2.json`; run 1 within ±1 ms): | edit (4.7 MB earthlike region) | halo neighbours | TS edit + refresh | wasm copy: in / edit / refresh / out | wasm resident | Rust native (nazrin) | |---|---|---|---|---|---| | sphere carve r4 | 0 | 23.2 + 3.4 = **26.5** | 0.8 / 12.7 / 1.8 / 1.8 = **17.1** | **14.7** | 14.1 + 1.2 = 15.3 | | sphere carve r12 | 0 | 22.4 + 3.9 = **26.3** | 0.8 / 13.2 / 2.2 / 1.8 = **18.1** | **15.4** | 12.9 + 1.6 = 14.5 | | sphere carve r24 | 0 | 23.6 + 7.7 = **31.3** | 0.9 / 13.4 / 3.7 / 2.0 = **20.0** | **17.4** | 12.6 + 2.6 = 15.2 | | sphere fill r12 | 0 | 23.8 + 4.5 = **28.3** | 19.4 | 15.5 | 12.5 + 1.5 = 14.0 | | sphere at the −X face, r12 | 1 | 23.2 + 4.4 = **27.6** | 2.0 / 13.4 / 2.2 / 2.2 = **19.9** | **14.8** | 12.6 + 1.4 = 14.0 | | box / cylinder / ellipsoid | 0 | 26.4 / 27.2 / 27.1 | 19.1 / 18.0 / 18.1 | 14.8 / 14.7 / 15.4 | 12.6–13.3 | | **stamp** (rotated 45°) | 0 | 78.0 + 17.5 = **95.4** | 0.8 / 54.0 / 10.0 / 2.0 = **67.0** | **64.3** | 55.1 + 7.6 = 62.7 | | first call after load (sphere r4) | | **62–68** (JIT warm-up) | **27–30** | | | **JavaScriptCore (Bun, the engine Safari uses)** on nazrin (`logs/rust-core-p0/wasm-bench-bun.json` on 1.3.13, `wasm-bench-bun-1.3.14.json` on 1.3.14): | edit | TS 1.3.13 | TS 1.3.14 | wasm copy (1.3.13 / 1.3.14) | wasm resident (1.3.13 / 1.3.14) | |---|---|---|---|---| | sphere carve r4 / r12 / r24 | 53.2 / 54.9 / 72.0 | 52.3 / 52.2 / 55.6 | 16.6 / 15.2 / 17.8 · 18.3 / 15.5 / 18.2 | 13.0 / 14.2 / 15.1 · 13.2 / 13.6 / 14.4 | | other primitives | 52–65 | 51–52 | 14.7–18.2 · 14.5–16.8 | 12.9–16.6 · 12.6–13.1 | | stamp | 127.3 | 112.6 | 66.0 · 62.6 | 63.5 · 62.0 | | first call | 88 | 87 | 31 · 31 | | **net-edit's TS edit** (`origin/net-edit` ad010330: the flag walk scoped to the edit window, compaction against the live size), same corpus and harness; its output was byte-identical to the 20d4dbe2 corpus on every case, so the wasm columns (20d4dbe2's algorithm) still verify: | edit | V8 (Chromium, utsuho): net-edit TS | V8: wasm copy / resident | JSC (Bun 1.3.14): net-edit TS | JSC: wasm copy / resident | |---|---|---|---|---| | sphere carve r4 | 4.7 + 3.0 = **7.7** | 16.1 / 13.8 | 6.4 + 3.3 = **9.7** | 15.6 / 13.4 | | sphere carve r12 | 5.2 + 3.5 = **8.7** | 16.6 / 14.2 | 7.7 + 3.9 = **11.6** | 15.6 / 13.7 | | sphere carve r24 | 5.7 + 4.5 = **10.2** | 17.3 / 15.1 | 7.6 + 5.9 = **13.5** | 18.4 / 15.1 | | other primitives | 6.9–9.1 | 15.5–16.6 / 13.3–14.0 | 8.3–9.6 | 15.1–17.6 / 13.2–13.7 | | stamp | 55.5 + 16.4 = **72.0** | 61.6 / 59.4 | 63.0 + 14.0 = **77.0** | 66.0 / 61.1 | | first call | 35 | 28 | 38 | 29 | (`logs/rust-core-p0/wasm-bench-chromium-netedit-ts.json`, `wasm-bench-bun-1.3.14-netedit-ts.json`.) **With net-edit's algorithm TS is 1.7–2× faster than this branch's wasm**, because the wasm still does 20d4dbe2's whole-tree flag walk. The refresh alone (the same algorithm on both sides) is wasm 1.7–3.1 ms vs TS 2.6–4.5 ms on V8. Projected wasm with net-edit's algorithm: about 2–3 ms edit (the brush walk) + 2 ms refresh + copies, i.e. **~4–7 ms copy / ~3–5 ms resident** (an estimate from the native breakdown in §3.3, not measured). **Reading the tables:** - **wasm runs at native speed** (within 0–15 %). The work is memory-bound. - **V8:** wasm is 1.5–1.8× faster than TS for primitive edits and 1.4–1.5× for the stamp. - **JSC:** TS is about 2× slower than under V8 (the edit allocates a 9.4 MB pool plus a 4.7 MB output per call), so wasm is 3–4× faster. Safari itself was not measured; no Safari is available here. - **Copying regions in and out** of wasm memory costs 2–5 ms per edit on a 4.7 MB region (in 0.8 ms, out about 2 ms, more with halo neighbours). - Each face neighbour adds about 0.8–1.2 ms of copy-in (`sphere_border`: +1.2 ms for one). - A corner edit reaching 7 neighbours would add about 6–8 ms in copy mode. That is an estimate, not measured. - **The copy-out replaces a copy the client already makes.** `_sharedSliceNodes` copies every assigned region into a SAB. The wasm-copy path can copy straight into that SAB, so its net extra cost is the copy-in. - **On 20d4dbe2's algorithm neither option fits a 16.7 ms frame** for one edit on a region this dense; with net-edit's algorithm TS already does (7–14 ms). §3.3 is where the time went. - **SIMD128 buys nothing:** ±1 ms, noise. `-C target-feature=+simd128` auto-vectorises little here. A SIMD build would be a separate deliverable for no gain. ### 3.3 Where the edit time goes (both languages) - In the CSG port's breakdown (native), the edit on the 4.7 MB region splits as: - **~11–12 ms fixed**: the input copy into a 2× pool plus `refreshSubtreeFlags` over the **whole** tree; - **1–2 ms**: the brush walk itself. - TS pays the same fixed work, and pays it slower. - A flag refresh scoped to the touched paths would produce the same bytes, provided the input's flags are already correct. So would an edit that does not copy the whole pool when it only appends. - **net-edit has built this in TS** (scoped flag walk, compaction against the live size; ad010330, not merged). Measured on this corpus: the TS edit drops from 22–24 ms to **4.3–5.7 ms** on V8 and from 48–49 ms to **5.8–7.7 ms** on JSC (§3.2), with byte-identical output. - The same change in the Rust port should take its edit from ~12.6 ms to about 2 ms (the brush walk); **estimate, not measured**. Porting it is the next step before any D2 speed comparison is fair. - It is a larger win than the language change, and independent of D2. - The stamp's ~43 ms of real work is per-voxel `read_voxel` descents into the source prefab: the same algorithm in both languages, and a candidate for a source-leaf cache. ### 3.4 Size | artifact | raw | gzip -9 | brotli -q 11 | |---|---|---|---| | `voxel_wasm.wasm` (edit + csg + normals; fat LTO, `opt-level=3`) | 107 KB | 42.8 KB | **34.6 KB** | | the same after `wasm-opt -O3 --strip-debug` | 85 KB | 36.6 KB | **29.8 KB** | | the TS it replaces (`csg` + `svt64-edit` + `voxel-normals-svt` and their imports, `Bun.build --minify`) | 617 KB | 101 KB | 82 KB | | today's `client/dist/bundle.js`, for scale (not minified; inline sourcemaps) | 13.4 MB | 3.18 MB | 2.17 MB | | physics-rs as wasm (`net-entity.md` §7, for the shared-module question) | 918 KB | 257 KB | 180 KB | Much of the TS subset's minified size is probably shared modules (material tables, `svt64`) that the client keeps anyway; it was not itemised. So wasm does **not** shrink the bundle measurably. It adds about 30–35 KB br. ### 3.5 Lifecycle | | Chromium 149 (utsuho) | JSC (Bun) | |---|---|---| | `WebAssembly.compile` (107 KB) | 6.8–10.5 ms | 4.2–6.8 ms | | `compileStreaming` from the response | 3.7 ms | — | | `instantiate` | 0.2 ms | 0.2–0.3 ms | | first edit after instantiate (sphere r4, edit + refresh) | 27–30 ms | 31 ms | | first TS edit (JIT warm-up included) | 62–68 ms | 88 ms | | linear memory, resident mode with 27 regions | 195 MiB | 195 MiB | - **Resident mode** moves the client's CPU region copies into wasm memory. - Linear memory **never shrinks**. - wasm32 caps it at 4 GiB, and mobile Safari is known to fail large `Memory.grow`s well below that (not measured here). - The net Worker decodes region bytes into a SAB today. A non-shared wasm memory cannot alias that SAB, so every arrival would be copied in: about 0.2 ms/MB at the copy-in rate above. - A *shared* memory would remove the copy, but needs the threads build (§3.6). - **Copy mode** keeps JS ownership. Its peak is about two regions plus ~12 MB of normals scratch plus a 2× edit pool, roughly 30–40 MB for this region (estimate). ### 3.6 Safari and cross-origin isolation - **The module needs:** mutable-globals, sign-ext, nontrapping-fptoint, bulk-memory, reference-types and multivalue. These are rustc 1.95's defaults for `wasm32-unknown-unknown`, as detected by `wasm-opt --detect-features`. - Safari has supported all of them since 15.x. That is from the feature tables; **not verified on a real Safari**. - If 16.4 must be proven rather than inferred, build with `-C target-cpu=mvp` plus `+bulk-memory` and test on a device. - **SIMD128** (Safari 16.4+) is supported but not needed (§3.2). - **The module uses no threads,** so it does not depend on cross-origin isolation. - **The site is cross-origin isolated today.** - `CROSS_ORIGIN_HEADERS` in `server/src/main.ts` sends COOP `same-origin`, COEP `require-corp` and CORP `same-origin` on every static response. - The Chromium bench page with the same headers reported `crossOriginIsolated: true`. - The client already falls back when a proxy strips the headers (`client/src/sab.ts`). - **wasm threads** (shared memory, atomics) would need: - isolation, which the site has, and a single-threaded fallback build for when it is missing; - a **nightly** toolchain with `-Z build-std` for `+atomics`. The devshell's stable rustc 1.95 cannot build it. - **What isolation breaks is already broken today:** - cross-origin iframes, images or scripts without CORP/CORS; - OAuth-style popups that rely on `window.opener`. - Nothing new would break. - **Recommendation for any wasm option:** single-threaded. To get the work off the main thread, run the module in a Worker. ### 3.7 Development cost | loop | today (TS) | with Rust in the client loop | |---|---|---| | change edit/normals code → runnable client | `watch:client` rebuild, 0.4–0.6 s | `cargo build --target wasm32` after a voxel-core change: **4.8 s** (fat LTO; 2.3 s no-op), plus the bundle | | hot reload | the bundle watcher | needs a `cargo watch` (or Bun `--watch` on the `.wasm`) step that the client build picks up | | tests | `bun test` on TS (`svt64-edit.test.ts`, normals corpus) | `cargo test --release` in voxel-core: **7 s** incremental, including both corpus parity tests (40 cases). The TS tests stay as long as TS keeps a copy | | fixtures (48 scenes) | `FixtureApi` → TS CSG | unchanged: the server side (Phase 3) can call the same Rust through the native `.so` | | toolchain | Bun | adds `lld` (`wasm-ld`), `binaryen` (`wasm-opt`) and `brotli`: now in the devshell; the Containerfile's build stage would need `lld` too. `voxel-wasm/build.sh` uses `wasm-ld` from PATH (`WASM_LD` overrides) | | agent edits | TS anywhere | edit/normals changes become Rust changes, with the bit-parity corpus as the gate (the physics/worldgen precedent) | ### 3.8 Interactions - **net-edit (byte-identical client/server edits).** - One crate on both sides gives identity by construction: the native `.so` on the server, the wasm on the client. The corpus shows native, wasm and TS agreeing on all 40 cases. - Keeping TS on the client and Rust on the server makes the corpus a *permanent* gate. Every edit-path change must land twice, and drift shows up in production as `svtStateHash` resyncs. - net-edit's `Math.hypot` → `sqrt` change has to be mirrored in `csg.rs` / `svt64_edit.rs` either way. - **net-entity step d (client local-sim physics as wasm, 180 KB br).** - One module holding physics-rs plus the edit/normals core would share voxel-core: SVT reading, palettes and the material table. - More importantly, it would share **one linear memory**. The ml0 regions the local sim collides against would be the same bytes the edit prediction mutates. - That only pays off in **resident** mode. In copy mode the two would each copy the regions they need. - The `parallel` feature switch added here is what physics-rs also needs on wasm: serial micropool, the route net-entity names. - A combined module is about 180 + 30 KB br. Separate modules would load voxel-core twice; it is small. - **Server option A.** If the server ever goes fully Rust, the protocol needs a second implementation regardless. Scoping §5.2 prefers a schema; wasm codecs are a poor fit (§3.1). ### 3.9 Options for the owner (not decided here) | option | what moves | client edit cost (V8 / JSC, sphere r12 on a 4.7 MB region) | size | parity | effort and risk | |---|---|---|---|---|---| | **(a) all shared code to wasm** | (b) plus the protocol and codecs (~7k TS lines), celestial and prune | as (b) for edits. The protocol decode would gain nothing and likely lose (JS objects are built per field through glue; not measured) | (b) + a codec module, est. 50–100 KB br | one implementation of everything | largest: about 9k more TS lines ported, and the net Worker's decode of every frame changes. Only worth it if the server goes to option A | | **(b) edit/normals core to wasm** (this branch's crate) | `applyCsgEditFull`, `refreshNormalSVT`/`buildNormalSVT`, `applyVoxelDelta`, later `pruneTree` | on 20d4dbe2's algorithm (measured): copy **18.1 / 15.5 ms**, resident **15.4 / 13.6 ms**. With net-edit's algorithm ported (estimate): **~4–7 / ~4–7 ms** copy, ~3–5 resident | +30–35 KB br; compile under 10 ms | **by construction** (the same crate as the server's Phase 2/3 native code) | built and bit-identical here. Adds a ~5 s Rust build to the client edit loop, the wasm toolchain in the devshell and the Containerfile, and a JS shim (~200 lines) in region-manager (net-edit's area). The TS copies can be deleted from the client once the server is also Rust (Phase 3) | | **(c) keep TS on the client, with a parity corpus** | nothing on the client. The server runs Rust (Phases 2/3) | 20d4dbe2 TS: **26.3 / 52.2 ms**; with net-edit's TS (measured): **8.7 / 11.6 ms** | 0 | the bit-parity corpus (40 cases today) becomes a permanent CI gate, and every change lands twice | lowest now; highest drift risk. A mismatch is a hash resync for the player | | **(c′) = (c) + the scoped flag refresh (§3.3)** | the algorithm fix in TS and Rust | **measured: 8.7 / 11.6 ms** (net-edit's TS; V8 / JSC, edit + refresh) | 0 | as (c) | **already built in TS on net-edit**; the Rust port (server Phase 3) must follow it | - **What the net-edit numbers change:** the speed argument for (b) shrinks from ~1.7× (V8) / ~3.5× (JSC) to an estimated ~1.5–2.5× on top of net-edit's TS, i.e. a few ms per edit. The remaining arguments for (b) are parity by construction, JSC/Safari's slower TS, and the shared linear memory with net-entity's local sim. - **Combinations:** - (b) and (c′) combine. - Resident vs copy mode is a separate, later choice inside (b). - Resident mode wins 2–5 ms per edit and enables net-entity's shared memory. - Copy mode keeps the client's SAB region model untouched. --- ## 4. Phase 1 plan: one region store, read in place **Goal:** remove the physics region mirror and the relay clones. No wire change; every fixture stays playable. ### 4.1 Steps 1. **`libvoxel_native.so`.** `world-rs` becomes the single cdylib. It links physics-rs, ca-rs and worldgen-rs as rlibs and re-exports their C ABIs; the three crates keep their `rlib` targets for tests. - The TS loaders (`rust-host`, `ca-ffi`, `worldgen-ffi`) point at one path, and each keeps its own ABI handshake. - The stale-`.so` warning moves to the combined build. 2. **Physics reads the store.** physics-rs's `RegionStore` becomes a `PinCache` over `WorldStore`: same `get`/`read_voxel` surface, `Arc` pins instead of owned `Vec`s. - Surface initiators stay a per-region side table keyed by (coord, version), still pushed by the SI pool until Phase 2. - `phys_put_region` / `phys_drop_region` are deleted; the worker no longer needs region messages. 3. **CA reads the store** the same way. CA's overlay and scratch stay CA-owned (`ca-rs/src/region_store.rs` keeps only its overlay). 4. **`ws.cache` becomes a façade over the store** (`world/manager.ts` and every cache call site): - **Writes:** `wr_put` (TS edits; one copy, until Phase 3) or `wr_generate_into` (worldgen in the gen pool's Workers writes straight into the store, since the Workers share the `.so`). - **Reads:** pins. The LRU byte bound moves into the store (`bytes()`); TS keeps the LRU *policy* (pins, CA pins, viewer distance) and calls `wr_drop`. 5. **The stream encode reads views** (§2.6): pin → view → deflate → release. The region-wire cache keeps holding encoded tiers only. 6. **Fixtures:** the harness determinism rule (synchronous build, no pool Workers) is unchanged. `makeFixtureWorld` writes through the same façade. ### 4.2 Deletions (target ≈ 3k TS lines, plus a Rust copy) - `server/src/physics/physics-worker.ts`: the worker's `WorldState` (`makeWorldState`, `regionPut`, its region bookkeeping). Most of its 342 lines. - `server/src/physics/worker-host.ts` (1185): the `regionPut` relay, the empty-region posts and the region queueing. - `server/src/physics/worker-rust-host.ts` (828): `_mirrorRegion`, the per-coord material-hash tracking and the G#3 ordering, which becomes a version check. - `server/src/physics/rust-host.ts` (970): the `phys_put_region` mirroring paths (§§ at lines 346–455). - `server/src/ca/ca-worker-host.ts` (1091) and `ca-worker.ts` (478): the region relay. - `physics-rs/src/ffi.rs`: `phys_put_region`'s `to_vec` (the 3rd copy) and `phys_drop_region`. `physics-rs/src/region_store.rs` keeps the read/walk code over pins. - Docs: the CLAUDE.md "budget roughly DOUBLE" note on `REGION_CACHE_MB`, and `STREAMING-AND-MEMORY.md` §2.1. ### 4.3 Gates - `physics-suite.ts --raw` bit-identical per fixture, and `raw-dump-determinism`. - `test:ca` for the CA path. - The default `bun run test`, and the voxel-core, world-rs and physics-rs cargo tests. - **Memtrace:** the physics-mirror class at about 0. The worst-case envelope target comes from owner decision D4 (proposed ≤ ~8.5 GB at defaults). - **The arrival profile:** the physics relay's 1.5 s of every 20 s gone, measured against the Phase 0 baseline (§5). ### 4.4 Size About 3–5k Rust: the façade ABI, physics/CA store adapters, LRU accounting and tests. About 3k TS removed. ### 4.5 Risks - **Fixture determinism:** the store must not let a Worker observe a region before the step that builds it. Versions plus pins make this explicit. - **The physics Worker's death-and-restart path:** pins held by a dead Worker leak until process exit. Mitigation: the Worker releases its `PinCache` on terminate, and a store-side per-consumer pin registry is the fallback. - **JS writes into views** (§2.6). --- ## 5. Phase 0 baselines (item 3) **Code:** main 20d4dbe2 (this branch's base; the server and client are unmodified). **Bun 1.3.14.** **Gate**, checked before each timed batch: `bun --version` 1.3.14; nothing listening on 3960–3979; all four `/tmp/gi-gate*.lock` free; nazrin load < 2 at the start of every timed run (one earthlike memory run overlapped the realistic-island-16 run, which is therefore used for memory only). Raw data: `logs/rust-core-p0/baselines/` (`*.analysis*.json` are the summaries). **Tooling** (`bench/rust-core/baseline/`, no server code changes): - `probe-preload.ts`, loaded with `bun --preload`: times every main-thread `Worker.postMessage` call (the synchronous structured clone), attributed to the Worker's script, and every `lookTick` run. - `arrival.mjs`: the server in a 10 G scope with the probe, `--cpu-prof` (main thread, 1 ms samples, wall-clock stamped) and `VOXEL_MEMTRACE=1`; headed Chromium on utsuho over vmlan (800×600, GI on, sun held), the camera sent to the pose, settle = regions and nodes unchanged 15 s. - `analyze.py`: the profile cut to a window (connect → settle), an exclusive category breakdown, the probe sums, look-tick percentiles and the memtrace peak. - `boot.sh`, `looktick.sh` (two headless `entclient.ts` clients, copied from net-entity), `memwalk.sh` (a headless client walking an earthlike world). ### 5.1 Arrival: the server main thread (surface-gi, pose 0, cold) Three runs, connect → settle (7.7–8.9 s; settle 5–6 s after the pose). | | run 1 | run 2 | run 3 | |---|---|---|---| | window (s) | 8.91 | 8.65 | 7.68 | | main thread busy (ms, share) | 2239 (25 %) | 2267 (26 %) | 2238 (29 %) | | prune (`pruneTree`, `pruneNormalSVT`) | 508 | 495 | 522 | | **`postMessage`** (profile) | **424** | **436** | **398** | | gen completion (`_finishGenerated`, queue) | 300 | 359 | 352 | | deflate (`node:zlib`) | 274 | 252 | 272 | | main scan, the rest (visit, encode, queue) | 241 | 193 | 194 | | SQLite | 199 | 223 | 211 | | look tick | 64 | 61 | 87 | | serverTick, the rest (entities, gen ball, CA pins) | 75 | 68 | 65 | | WS message handling | 19 | 18 | 20 | | other | 135 | 162 | 117 | `Worker.postMessage` from the probe (the call's wall time), per Worker: | | run 1 | run 2 | run 3 | |---|---|---|---| | normals pool (283 jobs) | 386 ms | 393 ms | 323 ms | | surface-initiators pool (376–391) | 92 ms | 99 ms | 107 ms | | physics relay (~4 620 posts) | 57 ms | 61 ms | 71 ms | | **total** | **535 ms** | **553 ms** | **501 ms** | - Over the 20 s after connect the main thread is busy 2.46–2.52 s (12–13 %): the arrival is over in under 9 s. - **Against the scoping doc:** stream-speed §5 (cited there) saw zero idle and 6.1 s of every 20 s in `postMessage`. That profile was taken on a loaded box (load 8–19) over DERP on an older base. On a quiet nazrin over vmlan, `postMessage` is **0.50–0.55 s per arrival, about 22–24 % of the main thread's busy time**; the normals pool is ~70 % of it. The Phase 1 (relay) and Phase 2 (normals, SI) targets are these rows. - The look tick during the arrival: p50 0.16 ms, p99 0.46–1.19 ms, max 15–33 ms. ### 5.2 Memory, per thread and total | scene | main RSS | main heap / ext / ab | region cache | Worker JS (largest report per Worker) | |---|---|---|---|---| | bare, idle (11 s after listening; 3 boots) | **280–289 MB** | 9 / 3 / 0 MB | 0 | normals 6, SI 7, physics 8, worldgen 0 MB heap | | surface-gi, idle (3 boots) | **456–490 MB** | 41 / 33 / 20 MB | 180 regions, 18 MB | physics 48, normals ≤ 29, SI ≤ 12 MB heap | | surface-gi, arrival peak (3 runs) | **1042–1074 MB** | 171–194 / 155–178 / 138–161 MB | 5129 regions, 57 MB | physics 83–86, normals 32–36 ×4, SI 32–38 ×4 MB heap | | realistic-island-16, arrival peak (1 run, memory only) | 852 MB | 137 / 123 / 103 MB | 5169 regions, 48 MB | physics 113, normals 43 ×4, SI 43 ×4 MB heap | | **earthlike walk, 50 m/s, 12 min** (worst observed) | **5611 MB** | 2001 / 1978 / 1958 MB | **926 regions, 1770 MB** | **physics 1346 MB**, SI 143 ×4, worldgen 54 ×6 MB heap | | earthlike walk, 4 min | 2817 MB | 852 / 842 / 826 MB | 302 regions, 707 MB | physics 513 MB | - Threads: 35 bare, 29 surface-gi (idle), 43 during the walk. - **The physics mirror, measured:** the physics Worker's JS heap tracks the region cache at **0.73–0.76 ×** (513 / 707 MB, 1346 / 1770 MB). The Rust copy (`phys_put_region`'s `to_vec`) is in the RSS but not broken out by memtrace; RSS minus main heap minus the reported Worker heaps leaves ~1.5 GB native at the walk's peak. - At 1.77 GB of cache the process held 5.6 GB, **about 3.2 × the cache**. The default bound is 2048 MB, so the defaults' worst case extrapolates to roughly 6.5 GB before the normals/SI/coarse caches fill (the scoping doc's 10.5 GB had every class at its bound). The walk did not reach the bound: generation (~1.3 s per earthlike surface region) limits how fast a single player can fill it. - The walker received no regions (it sends no `SetLodView` and moved faster than the scan); the server-side cache, gen ball and physics mirror are what the run measures. ### 5.3 Finding: synchronous generation on the main thread - A 90 s profiled walk (`walk-prof`): **44.5 s of the main thread was `_generate` → `wg_build_region`**, reached from `physics/worker-host.ts` `_onUp` → `_applyBatch` → `ensurePhysicsRegionReady`. When the avatar's body reaches a region the physics mirror lacks, the host generates it synchronously, on the main thread. - Meanwhile the 30 Hz look tick ran **214 times in 96 s** (~2 Hz; 341 times in the 12-minute walk). Every session's realtime state stalls with it. - Fast travel (creative flight) reaches this; walking speed may not. It was not seen in the arrivals or pile-huge. - **Phase 1 removes the cause:** with one store and generation writing into it from the pool (`wr_generate_into`), the physics host asks for a region instead of building it; a missing region reads as air until the pool delivers (the CA/physics rule today), or the host waits on the pool without blocking the loop. Owner decision if neither is acceptable. ### 5.4 Boot times `boot.sh` (exec → "Listening", including `direnv exec`'s ~0.21 s): | fixture | run 1 | run 2 | run 3 | |---|---|---|---| | bare | 0.85 s | 0.72 s | 0.69 s | | surface-gi | 6.53 s | 6.45 s | 6.48 s | - surface-gi: fixture start → listening 5.95–6.07 s, of which the 435 TS CSG edits (with their halo refresh) take **4.92–4.98 s**: p50 6 ms, p90 13–14 ms, p99 119–125 ms, max 164–185 ms. This is the Phase 3 win. ### 5.5 Look tick (pile-huge, 2 sessions) Whole `lookTick` (physics pump, contact events, looks, the outbox flush, `tickPositions`), two headless clients at spawn and (0, 100, −200), 75 s, loopback, the first 5 s after joining skipped: | run | ticks | p50 | p90 | p99 | max | |---|---|---|---|---|---| | 1 | 2092 | 1.21 ms | 5.27 ms | 13.99 ms | 26.8 ms | | 2 | 2095 | 1.13 ms | 4.96 ms | 12.94 ms | 23.5 ms | - `net-batch.md` §5.7's 1.1 / 4.3–4.8 ms timed only the entity-state part; these are the whole callback. - Main-thread `postMessage` over the 80 s: 279–314 ms (physics 123–135, SI 81–100, normals 75–79). ### 5.6 Re-runs on Bun 1.3.14 All in §2.7 and §3.2 beside the 1.3.13 numbers: transfer now cheap both ways; the store bench a little faster across the board (put 5.2 GiB/s; 27-tree clone 121 ms vs 2.4 ms pinned); the JSC edit bench unchanged within noise (TS 51–56 ms, wasm 14.5–18.3 ms copy, 12.6–14.4 ms resident; stamp 113 / 63 / 62 ms). ### 5.7 Crash - One `panic: Segmentation fault` in Bun 1.3.14 during a surface-gi fixture boot under `--cpu-prof` + the probe preload, with 9 Workers spawned, 441 ms after start (`baselines/crashes/sg-arrival-2.srv.log`, with the bun.report link). 1 of 9 profiled boots; none in 6 unprofiled boots, 2 look-tick runs or 3 walks. The first recorded Bun crash of a game server in this repo, though under the profiler. --- ## 6. Phase 1 (built): one region store, read in place Branch `rust-core-p1`: main e0f4f5fd (net-edit's step c merged) plus `rust-core-p0`. Every Phase 1 number below was taken on **Bun 1.3.14** against **main e0f4f5fd re-run in the same session** (a detached worktree at `logs/rust-core-p1/base-e0f4`, the Phase 0 scripts copied in untracked), with the same scripts, conditions and run counts as §5, alternating main and branch run by run. Phase 0's own numbers (base 20d4dbe2) are not used for comparison: net-edit changed the edit and serve paths in between. Gate per timed run (`bench/rust-core/p1/run-baselines.sh`): `bun --version` 1.3.14, no `/tmp/gi-gate*.lock` held, nazrin load < 2. Raw data: `logs/rust-core-p1/bl/`. ### 6.1 What was built | piece | where | lines | |---|---|---| | The store, in voxel-core so physics-rs and ca-rs read the same type: Arc-counted immutable versions with ids (`id`, and `nodes_id` shared by a normals-only version), a surface-initiator side table stamped with the `nodes_id` it was built from, `generation`, live-byte accounting, `PinCache`, raw-handle retain/release | `voxel-core/src/world_store.rs` | 619 | | One native library: `world-rs` is the cdylib `libvoxel_native.so` linking physics-rs, ca-rs and worldgen-rs (now rlibs); the `wr_*` ABI v2 (put, detached generation + insert, pins, descriptors, SI put/drop/state, stats) | `world-rs/src/{lib,ffi}.rs` | 400 | | Physics reads the store: `RegionStore` is a per-step pin set over the shared store (`prepare` pins every live body's swept footprint and reports each region's status; a read outside the set pins into an append-only overflow, so one step sees one version per region); SoAs come from the store's side table; `phys_set_store`, `phys_prepare_regions`, `phys_build_store_si`, `phys_set_held` (physics ABI 21) | `physics-rs/src/{region_store,ffi}.rs` | ±330 | | Hold in place: a held body is a zero-velocity kinematic for the step, its whole state restored bit for bit after it | `physics-rs/src/held.rs` | 71 | | CA reads the store: a region holds the pinned version it was told about and keeps only its overlay; `ca_region_put` takes a pin (CA ABI 4) | `ca-rs/src/{region_store,step,ffi}.rs` | ±150 | | TS: the one loader path and staleness check, the store binding, the cache façade | `server/src/native-lib.ts`, `world/world-ffi.ts`, `world/region-cache.ts` | 68 + 364 + 307 | **`ws.cache` is a façade over the store** (`world/region-cache.ts`, `world/manager.ts`): - **Writes:** `wr_put` copies JS bytes once (TS edits and CA write-backs, SQLite loads, the fixture generators). Native generation never crosses JS: the generator-pool Worker builds a **detached** version (`wr_generate`) and posts its pin; the main thread lands it with `wr_insert` when it lands the region in the cache (or drops the pin if the result is stale), so the cache stays the store's only writer and the race with a concurrent edit is decided where it always was (`_onGenComplete`). The synchronous path (`_generate`) does the same inline. - **Reads:** every TS reader gets a façade per version. Its byte fields are GC-owned views (`toArrayBuffer` with the Rust-provided deallocator, one pin per view), materialised on first read and cached with the version, so object identity per version (the material-hash memo, the edit snapshots) is unchanged. The stream encode, generation persistence, the visual-empty test and the material hash read **short-lived pinned views** instead (`withResultBytes`, `withRegionBytes`), memoised on the façade, so a region that is only streamed never materialises a GC-owned view. The wire cache keys its inputs on version ids instead of array identity. - **Accounting and eviction:** the byte bound reads the store's current bytes; TS keeps the LRU policy (recency, CA and physics-occupancy pins) and evicts with `wr_drop`. A version a reader still pins (a step in flight, a GC-owned view, a CA region) lives until its last pin goes. - `closeWorld` drops the world's versions but keeps the store handle (a few hundred bytes), so a late façade or host finds an empty store, never a dangling pointer; physics worlds hold their own reference. **Physics** (`rust-host.ts`, `worker-rust-host.ts`, `worker-host.ts`): - The direct host publishes surface-initiator SoAs to the store's side table exactly where it used to mirror them (the change hook's warm peek; the pre-step pass's cold build for a pinned region without one), so the SoA a step reads is the one it read before: **`physics-suite --raw` is bit-identical** (§6.2). - The Worker gets the store pointer in `init`; no region bytes or SoAs cross the channel. A pinned region without a SoA is built natively from the store on the Worker's thread (`phys_build_store_si`, the same sparse builder and halo the TS cache uses). The main side publishes warm SoAs it already has and answers missing-region requests. The G#3 ordering (hash-tracked `regionPut`s) is gone: an SoA applies only to the bytes it was built from. - Materials: the Worker registers the whole id-stable material table up front (it never sees SoA material ids); the direct host registers as before. **Hold in place (owner decision).** Before each step the Worker host pins every live body's swept footprint. A body with a region not in the store is held — dynamic, kinematic or avatar shadow alike, awake or asleep — and the region is requested from the main thread at physics-urgent priority (retried every second). For the step the native world makes the held body a zero-velocity kinematic (immovable, never integrated, never woken, waking nothing), and restores its pose, velocities, awake flag and sleep timer bit for bit afterwards; its kinematic readback is discarded. A held body writes nothing back, so: - its entity keeps the pose it had; the client interpolator (no extrapolation) shows it at rest; - when it resumes, the first writeback carries the previous step as `prevHeldUntilMs`, which records the hold as a rest (`EntityStore.setPose`), so the client receives `heldUntilMs` and starts the motion from the rest — step b's sleep/wake path, not a jump; - an avatar shadow's entity pose is report-driven anyway: holding the shadow only stops it pushing bodies; the player sees nothing. The main side never generates for physics any more. `ensurePhysicsRegionReady` loads a persisted region (a SQLite read) or queues a physics-urgent generation, and the footprint lookahead uses the same path. A physics-urgent item now goes to the pool even while the pool's full lane is saturated (the pool runs its queue by priority); before this a held body waited behind every queued client full. Hold statistics ride the batches (`holds`) and are logged as `[hold]` lines. **CA:** `CaWorkerHost` posts a pin of the version it was notified of (a number), `ca_region_put` takes it over, and the CA reads that version's bytes in place, keeping only its overlay. The pin, not a lookup at processing time, keeps the event semantics exact: the CA seeds the version it was told about even if a newer one landed meanwhile. This is an event pin, not a `PinCache`: CA's put is also its seed-and-wake event. **Deleted** (TS non-test: +1755 / −1255 lines over the branch; Rust: +1558 / −832, most of the Rust addition being the store and its tests): - `phys_put_region` / `phys_drop_region` and their `to_vec` copy of every region (the third copy); the old owned `RegionStore`. - The physics Worker's `WorldState`, `regionPut` / `regionDrop`, its SI cache (`physics-worker.ts` −73 lines). - `worker-host.ts`'s region relay: `pushedRegions`, `_pushRegionState`, the replay of regions to a restarted Worker, the synchronous `getOrGenerate` + sync SI build in `ensurePhysicsRegionReady`, the answered-empty oracle (−166 / +102). - `worker-rust-host.ts`'s `knownRegions`, `siReadyRegions`, `emptyRegions`, `regionMaterialHash` (the G#3 ordering), `noteRegionPut/Known/Unknown`, the `_afterMirror*` hooks, the eviction wake-and-hold and the bytes-pending oracle (−328 / +164, mostly the hold gate). - `rust-host.ts`'s `_mirrorRegion` / `_pendingSi` / `_flushPendingSurfaceInit` (−191 / +161). - The CA byte relay (`ca-worker-host.ts`, `ca-worker.ts`). - Three copies of the loader path and staleness check. The Phase 0 target of ≈3k TS lines deleted was not reached: the relays were smaller than estimated, and the façade, binding and loader add ≈740 lines. ### 6.2 Gates - **`physics-suite --raw`:** bit-identical to main e0f4f5fd on every fixture (823 `RAW` lines, zero diff). `raw-dump-determinism` passes (in the default loop). - **`bun run check`:** passes. **`bun run test`:** `TOTAL: 2093 pass, 0 fail across 38 shards`, no Bun panic (final code; also on two earlier states). - **`bun run test:ca`:** `TOTAL: 73 pass, 1 fail across 4 shards`, plus `ca-suite` `13-earthlike-coast: reload=FAIL` — **identical on main e0f4f5fd** (same session, same box: the same `late join: every join phase is served the worker's authoritative water` timeout and the same `ca-suite` failure). Pre-existing, not introduced here. - Rust: `voxel-core`, `physics-rs` (290), `ca-rs` (286 + the r50 gate) and `world-rs` cargo tests pass. New tests: SI stamping and staleness, `drop_if`, store-backed prepare / SI readiness / hold-exactness through the FFI, the native store SI build. ### 6.3 Arrival (surface-gi pose 0, headed Chromium on utsuho, 3 runs each) | | main e0f4f5fd | branch | |---|---|---| | window connect → settle | 9.0–9.8 s | 9.8 s | | main thread busy | 1952–2116 ms (22 %) | 2075–2152 ms (21–22 %) | | **physics relay `postMessage`** (probe) | **66–70 ms, 4639–4662 posts** | **5.3–6.4 ms, 181–182 posts** (commands only) | | all `postMessage` (probe) | 423–427 ms | 328–344 ms | | `postMessage` called from `worker-host.ts` (profile) | 56–65 ms | 4–7 ms | | gen completion (profile) | 279–317 ms | 376–417 ms | | prune / deflate / SQLite (profile) | 617 / 125 / 188 ms (run 1) | 606 / 119 / 196 ms (run 1) | | peak RSS | 983–1024 MB | 859–902 MB | | physics Worker heap (largest report) | 80–84 MB | 19–26 MB | | look tick p50 / p99 | 0.16 / 0.62–1.35 ms | 0.15–0.17 / 0.67–0.82 ms | | settle | 6.2–7.0 s | 7.0 s | - The physics relay is gone; what remains on that channel is commands (enrol, body writes, keepalive). - Gen completion grew ~90 ms: the surface-gi fixture's generator is TS, so its bytes are copied into the store (`wr_put`) and persisted from a pinned view. Real worlds generate natively into a detached version and copy nothing. - The arrival is not shorter: on a quiet box the relay was 3 % of the main thread's busy time; the normals (≈225 ms) and SI (≈100–125 ms) posts are Phase 2's. ### 6.4 Memory | scene | main e0f4f5fd | branch | |---|---|---| | bare, idle (11 s after listening; 3 boots) | 281–283 MB | 289–294 MB | | surface-gi, idle (3 boots) | 436–498 MB | 429–446 MB | | surface-gi arrival peak (3 runs) | 983–1024 MB | 859–902 MB | | pile-huge, 2 clients (2 runs) | 704–709 MB, physics heap 100–105 MB | 618–622 MB, physics heap 35–36 MB | | **earthlike walk, 50 m/s, 12 min** | **5249 MB** at a 1738 MB / 960-region cache (3.0× the cache); physics Worker heap 1020 MB; main ext / ab 1923 / 1905 MB | **3463 MB** at a 2047 MB / 666-region cache — the 2048 MB bound (1.7× the cache); physics Worker heap 14 MB; store: SI side table 567 entries / 114 MB, live versions 2166 MB (119 MB pinned stale); main ext / ab 2186 / 2165 MB (the façade views) | - **The physics mirror class is ≈0**: the physics Worker's heap stays at 13–15 MB in every walk (main: 687 MB at 5 m/s, 1020 MB at 50 m/s), and its native copy is gone. (Phase 0, base 20d4dbe2: 5611 MB at a 1770 MB cache, physics heap 1346 MB.) - The branch's walk filled the cache to its bound and evicted; main's did not (its loop was stalled in synchronous generation, §6.7). At the bound the process held 1.7× the cache instead of 3.0×. - The JS-visible `arrayBuffers` are now the GC-owned views of store versions (same bytes, one copy); `live` counts versions still pinned after eviction until their views are collected. ### 6.5 Boot | fixture | main e0f4f5fd (3 runs) | branch (3 runs) | |---|---|---| | bare | 0.74–0.90 s | 0.72–0.96 s | | surface-gi | 5.44–5.47 s | 5.50–5.61 s | Within noise; surface-gi's +~0.1 s is the fixture's TS-generated regions copied into the store at boot. ### 6.6 Look tick (pile-huge, 2 headless clients, 75 s, 2 runs each) | | ticks | p50 | p90 | p99 | max | physics `postMessage` | |---|---|---|---|---|---|---| | main run 1 | 2090 | 1.23 ms | 5.57 ms | 13.56 ms | 22.5 ms | 147 ms, 10 323 posts | | main run 2 | 2095 | 1.21 ms | 5.02 ms | 13.18 ms | 18.6 ms | 132 ms, 10 244 posts | | branch run 1 | 2098 | 1.16 ms | 4.79 ms | 14.18 ms | 22.8 ms | 78 ms, 5 078 posts | | branch run 2 | 2094 | 1.10 ms | 5.22 ms | 13.72 ms | 22.1 ms | 76 ms, 5 079 posts | Unchanged within noise: pile-huge's terrain is a few regions. The physics channel carries half the posts (no region relay). ### 6.7 The fast-travel stall (Phase 0 finding 1) A fresh earthlike world (deleted after), one headless client walking along +X from spawn (`memwalk.sh`), server at defaults. "Main-thread time in generation" counts CPU-profile samples whose stack holds `_generate`, `wg_build_region` or `wr_generate` (`bench/rust-core/p1/walkstats.py`). | walk | | main e0f4f5fd | branch | |---|---|---|---| | 50 m/s, 90 s, profiled | main thread in generation | **83.3 s of 90.5** | **0.0 s** | | | look tick runs (rate) | 28 (0.31 Hz) | 2013 (22.2 Hz) | | | peak RSS | 1841 MB | 1360 MB | | 5 m/s, 180 s | look tick runs (rate) | 36 (0.20 Hz) | 4634 (25.7 Hz) | | | peak RSS | 3324 MB | 1759 MB | | | physics Worker heap | 687 MB | 15 MB | - **The stall is gone.** On main, `ensurePhysicsRegionReady` generated every region the walker's avatar reached synchronously: the main thread spent 92 % of the walk in `wg_build_region` and the look tick ran once every 3–5 s — at walking speed too (0.20 Hz), which Phase 0 had not measured. - The branch's look tick is 22–26 Hz, not 30: with the loop free, the main thread now does the work main never got to — the streaming scan (18 s of 90), generation completions (11 s: persistence and the L3 silhouette), the SI pool's `postMessage` clones (12 s) and the avatar's body writes (9 s). The SI and normals posts are Phase 2's target. ### 6.8 Hold-in-place statistics | run | held | how long | |---|---|---| | surface-gi arrivals (3) | no body, ever | — | | pile-huge, 2 clients (a 40 s run with the release log) | all 502 bodies at the first steps after the clients join | p50 217 ms, max 233 ms (13–14 steps): until the fixture's footprint regions were generated; then never again (main's Worker held dynamic bodies over unknown terrain the same way) | | fresh earthlike, 50 m/s walk, 90 s | the avatar shadow, continuously | the whole walk (4721 body-steps ≈ 79 s) | | fresh earthlike, 5 m/s walk, 180 s | the avatar shadow, continuously | the whole walk (10 188 body-steps ≈ 170 s) | | fresh earthlike, player standing at spawn, 90 s | the avatar shadow | once, 36.1 s: until the pool had generated its spawn footprint (2163 body-steps) | - In a **fresh** world the pool generates the region the avatar's footprint enters next in 2–18 s under the load of the proactive ball, and the walker enters a new region every 3.2 s even at 5 m/s, so the shadow never catches up. The hold is invisible to the walker (the player's pose is report-driven); it only means the shadow pushes no bodies there — and in a fresh world there are none. On main the same walk froze the server instead. - A body that needs terrain the world already has (persisted or cached) is never held for more than the request round-trip. - Interaction with step b: a held body writes nothing back, so its last writeback stands and the release goes through the rest path (`prevHeldUntilMs` → `rest` → `heldUntilMs`): the client sees a body at rest, then the motion from that pose. ### 6.9 Owner decisions (none landed) - **Memory cap.** Phase 0 proposed a worst case ≤ ~8.5 GB at defaults. Measured at defaults on the 12-minute 50 m/s walk: **3.46 GB RSS with the region cache AT its 2 GB bound** (store current 2.05 GB + 0.12 GB pinned stale, SI side table 0.11 GB, physics Worker 14 MB). Not every derived cache was at its bound (the SI warm cache, 288 MB; the wire cache, 256 MB; the store's SI table grows with the cached surface regions). Estimate with every class at its bound: ≈4–4.5 GB (store 2.05 + store SI ≈0.3 + SI warm 0.29 + wire 0.26 + the rest of the process ≈1.2–1.6 GB); not measured. That is about half of Phase 0's proposed ~8.5 GB cap; the cap and `REGION_CACHE_MB` are the owner's. - **Eviction policy:** unchanged (TS LRU over the store's bytes, CA and physics-occupancy pins). One new effect: an evicted version a reader still pins stays alive until the pin goes, counted in the process-wide `liveBytes` (memtrace `store … live=`), not in the cache's bytes. - **Visible:** nothing in the surface-gi arrivals. The avatar shadow in a fresh world is held while the player outruns generation (above): bodies there are not pushed by the player until the terrain lands. A body frozen mid-fall at the edge of generated terrain resumes from the pose it froze at once the region lands. - **Physics now reads render-only regions.** Before, a region the streamer loaded render-only was air to physics until a body asked for it; it is now the same bytes physics reads (the old `T2b` control test, which asserted the fall-through, now asserts the landing). - **Neighbour SoA staleness (Worker):** main's Worker invalidated the six neighbours' SoAs when a region's bytes changed; the store keys an SoA only to its own region's bytes, as the direct host always did. A neighbour's SoA can keep a boundary cell classified against the old neighbour until that neighbour itself changes; the narrowphase re-derives each visited cell's exposed mask from live reads, so only which cells are visited is affected. Not measured. ### 6.10 Leftovers - Normals and SI jobs still clone trees to their pools (≈325 ms of the arrival's main thread); the façade views those readers touch are GC-owned. Phase 2: the pools pin from the store. - `ws.cache` readers outside the encode path still materialise GC-owned views (edits, CA, audio mip, normals sources). - A dead physics or CA Worker leaks the pins it held (the physics `PinCache` and CA region pins) until process exit; a respawned Worker re-pins. - `physicsPullsOnDemand` / render-only loads now only skip SoA work (physics sees the bytes regardless); the knob could go. - `injectRegion` / `evictRegion` are test seams now (the Worker no longer uses them). - `test:ca`'s `late join` and `ca-suite`'s `13-earthlike-coast reload` fail on main e0f4f5fd too. --- ## 7. Phase 2 (built): normals and surface initiators read the store in place Branch `rust-core-p2` from main 144feeed (Phase 1 merged). Every number below was taken on **Bun 1.3.14** against **main 144feeed re-run in the same session** (a detached worktree at `logs/rust-core-p2/base-144f`), with the Phase 0/1 scripts, conditions and run counts, alternating main and branch run by run (`bench/rust-core/p2/run-baselines.sh`; same gate: Bun 1.3.14, no `/tmp/gi-gate*.lock` held, load < 2). Raw data: `logs/rust-core-p2/bl/`. ### 7.1 What was built | piece | where | lines | |---|---|---| | The native job pool: a FIFO run by Rust threads; a job takes over the pins of the versions it reads (normals: the region and its 26 neighbours; SI: the region and its 6 axis neighbours) and yields an immutable `Arc` result; `wj_*` ABI | `world-rs/src/jobs.rs` | 445 | | The store's normals side table: entries stamped with the `nodes_id` of the version they were built from; a result built from a version replaced meanwhile is refused; dropped with the region | `voxel-core/src/world_store.rs` | +113 | | SI from pinned versions, shared by the job pool and the physics Worker's store build | `physics-rs/src/surface_init.rs` (`build_surface_init_versions`) | +34 | | TS: the runner (submit, a 1 ms poll while jobs are in flight, results as views of native memory) and `KeyedJobQueue` (per-key dedup, refresh follow-ups, the class upgrade, the compute budget) | `server/src/world/native-jobs.ts` | 263 | | TS: the normals and SI pools on it | `normals-pool.ts`, `surface-initiators-pool.ts` | 147 + 100 | | TS: pins of a result (`pinResult`: the store's current version, or a detached copy of bytes replaced since), the normals hot cache, the bindings | `region-cache.ts`, `manager.ts`, `world-ffi.ts` | +29, ±325, +170 | | Native-vs-TS normals parity corpus | `server/src/world/normals-native-corpus.test.ts` (`test:corpus`) | 571 | **Deleted:** the normals and SI Worker pools and their Workers (`normals-worker-pool.ts`, `normals-worker.ts`, `surface-initiators-worker-pool.ts`, `surface-initiators-worker.ts`: 797 lines) and with them every tree clone to a pool, their crash-respawn paths, and the SI cache's `maxWarmCells` / `siWarmCells` seam (it existed for the physics Worker's mirror world, gone since Phase 1). Over the branch: TS non-test +915 / −958, TS tests +664 / −85, Rust +723 / −33. **Threads: native, not Bun Workers.** The pool runs on Rust threads (`std::thread`, a mutex-and-condvar FIFO; no new crate). Bun Workers calling the shared `.so` would have kept a Worker pool (its JS heaps, its crash and respawn paths, a message per job) only to call one native function; Rust threads read the store directly and the main thread only submits and collects. Completion is collected by polling (`wj_poll`, one FFI call per 1 ms timer while any job is in flight) rather than a thread-safe `JSCallback`, which bun:ffi documents as experimental. The thread count is `2 × workerPoolSize` (8 at the default 4): as many threads as the two Worker pools had Workers. The compute budget (cores − 2) still caps how many jobs run at once, so CPU use is unchanged. A thread that fails to spawn (EAGAIN on a loaded box) is skipped, not fatal. A panic in a job aborts the process (`panic = "abort"`), as for physics; the old pools' retry-after-crash path has no equivalent. **Normals.** - The server's builds and refreshes are the Rust port (§1). The TS normals code is unchanged since 20d4dbe2, the port's base, so nothing needed porting; net-edit's `Math.hypot` change was in the CSG stamp probe, not in normals. - `svtStateHash` hashes the material only (`docs/net-edit.md` §1.6), so no runtime check would catch a server/client normals divergence. `normals-native-corpus.test.ts` is that gate. Every native result goes through the production path: a store, pins, the pool, the result view. - Fresh builds of a generated 3×3×3 block (terrain and crystal-caverns, seed 42691). The outer ring's halos are partly missing. - Edits applied with `applyRegionCsg`, then each edited region refreshed over its box and each loaded neighbour over its `haloNeighbourBoxes` layer, exactly as a peer replays a command. The edits: sphere carve r4, r12 and r24, a fill, a stained-glass paint (REGION palette), a box across a face, a sphere on an edge, a `die` stamp and a multi-brush list. - Each refresh runs twice, with the previous normals as the native entry and as plain bytes. - A Rarium bridge across a face (centre and neighbour palettes). - A region whose palette overflows into RAW16 leaves. - Degenerate, full-window and one-voxel boxes, and an empty prev. - Every case is byte-identical. - Each result is attached to the store's side table (no copy) when it was built from the region's current version. The LRU entry memoises it, so the serve path reads normals without a SQLite read. SQLite stays the persistent layer (restarts, evicted regions). Plain bytes (the buried-gate stub) replace the side-table entry. An edit's new version drops it. - A refresh's previous normals go to the job as the native entry when they are one; bytes read back from SQLite are copied in once. - **Not ported:** `pruneNormalSVT` (it did not fall out of this work; the stream prune and encode are Phase 4). The TS edit algorithm is untouched. **Surface initiators.** `requestSurfaceInitiatorsBuild` pins the region and its axis neighbours and queues the native build. The completion check that the inputs are still current compares **version ids** instead of SHA-256-hashing six neighbours on the main thread. A neighbour evicted and reloaded with the same bytes now discards the result, which costs a rebuild and never changes physics: a surviving result is the synchronous build's output. The results still populate the warm TS cache and the SQLite store as before. ### 7.2 Gates - **Normals parity:** `test:corpus` `TOTAL: 83 pass, 0 fail`, including the existing normals corpora and the new native-vs-TS file. - **`physics-suite --raw`:** bit-identical to main 144feeed, 812 `RAW` lines, zero diff. - **`bun run check`:** passes. **`bun run test`:** `TOTAL: 2093 pass, 0 fail across 38 shards`, no Bun panic. - **`test:ca`:** `TOTAL: 73 pass, 1 fail across 4 shards`. The failure is the pre-existing `late join: every join phase is served the worker's authoritative water`; `ca-suite` `13-earthlike-coast: reload=FAIL` as on main. Unchanged from main. - Rust: `world-rs` (`tests/jobs.rs`: pins read after the region is replaced, results equal to the direct builders, stale results refused, a threaded pool) and the store's normals-table test pass. ### 7.3 Arrival (surface-gi pose 0, headed Chromium on utsuho, 3 runs each) | | main 144feeed | branch | |---|---|---| | window connect → settle | 9.77–9.79 s | 8.86–9.69 s | | settle (after the pose) | 7.0 s ×3 | 6.1–7.0 s | | regions / nodes at settle | 142 / 3 854 840 | 142 / 3 854 840 | | main thread busy | 2064–2129 ms (21–22 %) | **1612–1651 ms (17–18 %)** | | all `postMessage` (probe) | 344–353 ms: normals 224–234, SI 113–116, physics 5–6 | **4.5–5.8 ms** (physics commands only) | | prune / gen completion / main scan (profile, run 1) | 619 / 178 / 265 ms | 591 / 177 / 195 ms | | SQLite / deflate (run 1) | 205 / 115 ms | 158 / 121 ms | | new: job inputs (pins) / job results (poll, views, cache put) / store views (run 1) | — / — / 85 ms | 83 / 51 / 65 ms | | look tick p50 / p99 | 0.15–0.18 / 0.68–0.78 ms | 0.15–0.16 / 0.47–0.80 ms | | peak RSS | 805–904 MB | 771–789 MB | | store normals side table at the peak | — | 289 entries, 119 MB | - The normals and SI `postMessage` clones are gone: −340 ms of main thread per arrival. The busy time fell by ~470 ms (−22 %): the clones, plus less SQLite (normals served from the side table) and a lighter main scan. - What the main thread still does on an arrival (branch, run 1, 1651 ms): prune (`pruneTree`, `pruneNormalSVT`) 591 ms (36 %), the main scan 195, generation completions 177, SQLite 158, deflate 121, pinning job inputs 83, store views and pins 65, job results 51, `serverTick` 49, the look tick 42, material SHA-256 41 (`bench/rust-core/p2/mainthread.py`). ### 7.4 Memory | scene | main 144feeed | branch | |---|---|---| | bare, idle (3 boots) | 289–297 MB | **146–152 MB** | | surface-gi, idle (3 boots) | 438–463 MB | **333–335 MB** | | surface-gi arrival peak (3 runs) | 805–904 MB | 771–789 MB (incl. 119 MB of side-table normals) | | pile-huge, 2 clients (2 runs) | 649–667 MB | 503–527 MB | | 5 m/s walk, 180 s | 1896 MB (SI Worker heap 148 MB) | 1762 MB | | **earthlike walk, 50 m/s, 12 min** | **4011 MB** at a 2039 MB / 680-region cache; SI Workers' heap ≤ 96 MB each | **3235 MB** at a 2043 MB / 698-region cache (the bound); store SI 583 / 113 MB, live 2221 MB | - Eight Bun Workers (4 normals, 4 SI) and their JS heaps are gone; the native pool's eight threads hold ~12 MB of normals scratch each once used. The thread count is unchanged (35 bare, 29 surface-gi). - The 12-minute walk: −776 MB at the same cache bound (1.58 × the cache, was 1.97 ×). The walker sends no `SetLodView`, so no normals were built in the walks (side table 0). - **The side table's own cost:** 119 MB for 289 regions in the surface-gi arrival (its thin fixture regions carry more normals than material); on natural terrain about **7 % of the material** (earthlike surface regions: 0.64–1.01 MB of normals for 11.9–14.5 MB of material). It is not counted in `REGION_CACHE_MB` (as the SI table is not); at the 2 GB bound that is ≈140 MB if every resident region had normals. Owner decision (§7.9). ### 7.5 Boot | fixture | main 144feeed (3 runs) | branch (3 runs) | |---|---|---| | bare | 0.75–0.95 s | 0.66–0.84 s | | surface-gi | 5.40–5.63 s | 5.16–5.20 s | Nothing spawns the eight pool Workers (and their module loads) any more. ### 7.6 Look tick (pile-huge, 2 headless clients, 75 s, 2 runs each) | | ticks | p50 | p90 | p99 | max | `postMessage` | |---|---|---|---|---|---|---| | main run 1 | 2093 | 1.13 ms | 4.94 ms | 13.70 ms | 22.1 ms | 261 ms (SI 112, physics 75, normals 73) | | main run 2 | 2096 | 1.12 ms | 4.98 ms | 14.32 ms | 27.3 ms | 251 ms | | branch run 1 | 2100 | 1.17 ms | 4.69 ms | 14.68 ms | 24.6 ms | 75 ms (physics) | | branch run 2 | 2093 | 1.13 ms | 4.70 ms | 13.43 ms | 22.7 ms | 75 ms (physics) | Unchanged within noise: the look tick's own work did not change. ### 7.7 Walks: the look-tick rate, and where the main thread goes Fresh earthlike world (deleted after), one headless walker along +X (`memwalk.sh`), server at defaults. | walk | | main 144feeed | branch | |---|---|---|---| | 50 m/s, 90 s, profiled | look tick runs (rate) | 1984 (21.9 Hz) | 2014 (22.3 Hz) | | | SI `postMessage` | 1612 ms | 0 | | | peak RSS | 1365 MB | 1224 MB | | 5 m/s, 180 s | look tick (rate) | 4645 (25.7 Hz) | 4740 (26.3 Hz) | | | SI `postMessage` | 4601 ms | 0 | | 50 m/s, 12 min | look tick (rate) | 19 181 (26.6 Hz) | 19 584 (27.2 Hz) | | | SI `postMessage` | 10 686 ms | 0 | **The rate is not limited by main-thread load, but by stalls.** The look-tick interval is on time at the median (34 ms in both trees; p90 52 ms) and the tick itself is short (p50 0.08 ms). The rate is lost to rare long tasks: interval p99 251–273 ms, max 1.1 s. Bun's `--cpu-prof` records no idle samples and samples sparsely on a loaded box (median 3 ms apart in the walk vs 1.1 ms in the arrival), so §6.7's "18 s of 90 in the scan" (which counted every gap between samples as busy) overstated the load: the walk's main thread runs about 5–22 s of 90 depending on how a gap is read. The tasks of ≥ 50 ms (`bench/rust-core/p2/longtasks.py`), 50 m/s profiled walk: | long task (≥ 50 ms), heading frame | main: n, total | branch: n, total, max | inside it | |---|---|---|---| | generation completion (`_onGenComplete`) | 31, 2350 ms | 25, 2179 ms, 181 ms | SQLite `put` of the region 839 ms, material SHA-256 282, the store's `regionHash` 250, logging 180, `wr_stats` 87 | | the join (`handleMessage`) | 3, 1322 ms | 3, 1271 ms, **1094 ms** | building prefab structures in TS at connect (`_buildL0Leaf`, `voxelAt` of `primitives`/`die`) 1020 ms, `accounts.updatePosition`'s `cloneObject` 144 | | the look tick itself | 9, 765 ms | 9, 815 ms, 145 ms | `_tickImpacts` (a `Map` build) 403 ms, `drainContactEvents` / `tickLooks` `slice` 256 | | `serverTick` / `caTick` | 7, 685 ms | 10, 697 ms | `regionCoordKey` 258, `caTick` 262, the scan | | compute-budget release pumps (gen and SI completions) | 13, 955 ms | 2, 171 ms | — | | **new: job completions (`_poll`)** | — | 4, 392 ms, 160 ms | `toArrayBuffer` of SI results 292 ms (JSC's external-memory GC; the view itself costs ≤ 0.01 ms, a copy 0.15–0.4 ms), `wj_poll` 85 | | SI completions on the Worker channel (besides their release pumps) | 1, 104 ms | — | — | So the remaining 30 Hz gap is: generation completions (persistence, two full-region hashes, logging), one 1.1 s join stall building prefabs in TS, `_tickImpacts`, and now ~0.4 s of job completions whose cost is GC triggered by native views. None of it is the normals or SI clone any more. ### 7.8 Finding: fresh-world generation latency is concurrency, not cost In the walks every region builds in 3–16 s inside its pool Worker (`gen #` lines: surface regions p50 3.2–4.0 s, p90 16.2–16.7 s, both trees). An experiment on a quiet box (`WorldgenWorkerPool`, 6 Workers, earthlike surface regions of the walk's row): | | per-region build time | wall for six | |---|---|---| | one at a time | 1376–1862 ms | 9.9 s (sum) | | six at once | 3145–9702 ms | 9.7 s | Six concurrent builds take as long as six sequential ones: worldgen-rs fans every region's 64 L2 subtrees out on micropool's **one process-wide pool** (`voxel_core::parallel`, ≤ 8 threads), so the six gen Workers add no throughput and multiply each region's latency by up to ~6×, including the physics-urgent region a held body waits for (§6.8). Cheap levers (not applied): a gen pool of 1–2 Workers, or a priority lane on the shared pool. ### 7.9 Owner decisions (none landed) - **Job threads:** 8 (`2 × workerPoolSize`, the Workers the two pools had); the compute budget (6 on nazrin) still caps running jobs. Fewer threads only lengthen the queue under the budget; more do nothing. - **Normals side-table memory:** outside `REGION_CACHE_MB`, like the SI table: ≈7 % of the cache on natural terrain (≈140 MB at the 2 GB bound), 119 MB in the surface-gi arrival. Counting it in the bound would evict regions instead. - **Generation concurrency** (§7.8): gen pool size vs latency; not part of this phase. ### 7.10 Leftovers - `pruneNormalSVT` and the stream prune/encode stay TS (Phase 4); prune is 36 % of the arrival's main thread. - Entity structures' normals are still built in TS on the main thread (`StructureManager`, ~30 ms each). - The SI side table is still fed through the TS warm cache (`wr_put_si` copies); the job result could be attached in place, as normals are. - `physicsPullsOnDemand` and the `injectRegion` / `evictRegion` test seams (§6.10) are untouched: this phase does not make them dead. - `cacheMaxBytes`'s doc still describes the physics Worker's mirror world. - The GC cost of native views (`toArrayBuffer`, JSC external memory) is the new main-thread item (≈0.3 s per fast-walk minute and a half). --- ## 8. Phase 4 (built): the stream encode off the main thread Branch `rust-core-p4` from main 4c4b1b4e (the wasm edit core merged). Every number below was taken on **Bun 1.3.14** against **main 4c4b1b4e re-run in the same session** (a detached worktree at `logs/rust-core-p4/base-4c4b`), with the Phase 2 / tick-long-tasks scripts, conditions and run counts, alternating main and branch run by run (`bench/rust-core/p4/run-baselines.sh`; the same gate: no `/tmp/gi-gate*.lock` held, load < 2 at each start). Raw data: `logs/rust-core-p4/bl/` (wire proof: `logs/rust-core-p4/wire/`). ### 8.1 What was built | piece | where | lines | |---|---|---| | `pruneTree`'s twin: `prune_tree_into` (BFS, children contiguous, writes into the caller's slice) and `pruned_slots` (the output size, walking only the kept nodes; the normals SVT has the same layout and cut rule, so it sizes the normals prune too) | `voxel-core/src/tree_prune.rs` | 119 | | The streamed tier: the material pruned to `ml`, the normals pruned against the face neighbours (`prune_normal_svt`) or stripped above `LOD_NORMALS_MAX_ML`, the `RegionData` framed | `voxel-core/src/stream_tier.rs` | 123 | | The C ABI: `ws_tier_len` (the tier's size and section lengths), `ws_encode_tier` (on the calling thread), one `f64` argument table naming the region and face neighbours by pin (or raw bytes) | `world-rs/src/stream.rs` | 147 | | The tier job on the native pool (writes into the caller's buffer, no result), and `wj_pool_release_wait` (a release that returns once no job is running) | `world-rs/src/jobs.rs` | +68 | | TS: pin the region and its resident face neighbours, size the tier, allocate the message in the JS heap, encode it on the calling thread or submit it | `server/src/net/stream-encode.ts` | 239 | | The world's stream pool: 2 Rust threads (`WorldState.streamJobs`; 0 with `workerPoolSize: 0`) | `server/src/world/manager.ts` | +39 / −53 (with the face-neighbour helpers) | | Goldens of main's TS stream encode (1520 digests) | `server/src/world/stream-tier-corpus.{test.ts,golden.json}` (`test:corpus`) | 251 | **The flow.** `_queueRegionData` asks the wire cache (`region-wire.ts`) for the tier. On a miss, `encodeStreamTier` pins the region's store version and its resident face neighbours (the snapshot the synchronous encode read), calls `ws_tier_len`, and allocates the message (`new Uint8Array(len)`). The native code writes the message straight into that buffer, so there is no copy out of native memory and no native view (§2.6's GC cost). - A tier under 4 KiB (`COMPRESS_MIN_BYTES`: sent uncompressed) is encoded on the calling thread. It reaches the lane as bytes, synchronously, as on main. So does every tier of a world without stream threads (tests, fixtures). - A larger tier is a job on the stream pool. The pool takes over the pins. The cache and the lane hold the message's Promise; deflate chains on it. On main, a tier of this size was already a Promise on the lane (deflate), so ordering and the lane's backlog accounting are unchanged: the exact raw size is known at enqueue, as before. - The stream pool is its own: two threads that never queue behind a normals build (the shared pool runs ≤ 6 budgeted jobs of 100s of ms). An encode is 1–15 ms of CPU. The compute budget does not count it, as it did not count the main thread's encode. **Deflate stays on Bun's threadpool.** Bun links its zlib statically (no exported symbols; `process.versions.zlib` is a fork commit), so a native deflate would be another library's bytes and change the wire. The client would inflate them, but the gate is byte identity. Deflate already runs off the main thread; its main-thread side (the `node:zlib` wrapper, 80–104 ms per arrival) is the same on both trees (§8.3). **Deleted:** session.ts's `pruneForStream` (the strip tests now call a native twin in `stream-encode.ts`), `withFaceNeighbourMaterials` and the test-only `peekFaceNeighbourMaterials` (`pinFaceNeighbours` replaces both). Over the branch, without the bench commits: TS non-test +348 / −130, TS tests +279 / −21 (plus the 1522-line golden), Rust +564 / −7 (with tests). Less TS than the scoping doc's ~1.5k: the TS normals prune was already gone (the wasm edit core), and the client keeps `pruneTree` (§8.7). **The region-wire cache stays in JS** (item 2, §8.6): it holds compressed bytes that Bun's zlib produces in the JS heap; moving them native would add a copy per tier and a native view per send, whose length JSC counts as external memory just as it counts the ArrayBuffers now. ### 8.2 Gates - **Wire bytes identical to main**, proved two ways: - `test:corpus`'s `stream-tier-corpus.test.ts`: the native encode matches 1520 frozen digests of main's TS (terrain, crystal-caverns and earthlike 3×3×3 blocks; wire levels 0–3; with and without face neighbours; `LOD_NORMALS_MAX_ML` 1 and 3; a REGION-palette edit, the buried stub, no normals). 210 of the digests change with the face neighbours, so the normals prune's border reads are covered. - A wire recorder (`bench/rust-core/p4/wirehash.ts`): a headless client reports a `LodView` (full-detail radius 1, so most tiers are pruned) and hashes every region message as transmitted (BulkParts reassembled, a `Deflated` message hashed compressed). Same scenario on both trees: surface-gi 1587 / 1587 messages, island-4 1590 / 1590, earthlike stand 225 shared (237 on the branch, generation timing), earthlike walk 10. **3412 shared messages, 1865 of them pruned tiers, 0 mismatched.** - **`physics-suite --raw`:** bit-identical to main, 812 `RAW` lines, zero diff. - **`test:corpus`:** `TOTAL: 94 pass, 0 fail across 1 shard`. - **`bun run check`**, **`bun run lint`:** pass. **`bun run test`:** `TOTAL: 2079 pass, 0 fail across 38 shards`, no Bun panic. - **`test:ca`:** `TOTAL: 73 pass, 1 fail across 4 shards`: the pre-existing `late join: every join phase is served the worker's authoritative water`; `ca-suite` `13-earthlike-coast: reload=FAIL`. As on main. - Rust: `world-rs/tests/stream.rs` (a job and the sync encode agree; a job reads the pins it was given after the region is replaced; a waiting release returns with no job writing) and the existing `world-rs` / `voxel-core` tests pass. ### 8.3 Arrival (surface-gi pose 0, headed Chromium on utsuho, 3 runs each) | | main 4c4b1b4e | branch | |---|---|---| | settle (after the pose) | 7.0 s ×3 | 7.0 s ×3 | | regions / nodes at settle | 142 / 3 854 840 | 142 / 3 854 840 | | main thread busy (connect → settle, 9.5–9.8 s) | 1403–1434 ms (15 %) | **893–949 ms (9–10 %)** | | look tick p50 / p99 | 0.15 / 0.59–0.75 ms | 0.15 / 0.63–0.96 ms | | peak RSS | 665–677 MB | 663–667 MB | The settle time sits on the probe's 1 s sampling floor on both trees, so time to arrival does not resolve here; the arrival was not main-thread-bound on main either (15 % busy). Where the main thread goes (`bench/rust-core/p4/mainthread.py`, ms, min–max of 3 runs, ranked by the branch): | category | main | branch | |---|---|---| | SQLite (`bun:sqlite`: generated-region and normals reads/puts) | 138–175 | 157–162 | | main scan (the rest of `_mainScanPass`) | 208–225 | 153–164 | | deflate (`node:zlib`'s main-thread side) | 78–104 | 80–104 | | generation completions | 91–129 | 87–92 | | job inputs (pins: normals sources, SI dispatch) | 65–81 | 68–81 | | look tick | 52–60 | 53–66 | | `serverTick` (rest: entities, gen ball, CA pins) | 55–59 | 47–60 | | **stream encode (new: pins, size, small tiers, submit, completion)** | — | **47–48** | | native job results (poll, views, cache put) | 54–68 | 38–50 | | physics host | 27–43 | 33–40 | | material hash (SHA-256) | 19–25 | 21–31 | | store views / pins | 21–35 | 15–23 | | ws message handling | 22–33 | 15–24 | | **prune (`pruneTree` TS, `pruneNormalSVT` native via FFI)** | **450–468** | **1–2** | - The prune (306 ms of TS `pruneTree` and 114 ms of the native normals prune in the exploratory run) and the TS framing (`encodeRegionData` 33 ms, in the main scan) leave the main thread: −510 ms per arrival (−36 %). What replaces them is 47–48 ms: pinning, sizing, the sub-4 KiB tiers and the completions. - The branch's main thread does no per-region byte work for the stream except deflate's wrapper. ### 8.4 Walks (fresh earthlike world, one headless walker along +X, unprofiled) | walk | | main 4c4b1b4e | branch | |---|---|---|---| | 50 m/s, 90 s (2 runs each) | look-tick rate | 29.01 / 29.09 Hz | 28.94 / 29.05 Hz | | | interval p50 / p99 / max | 33 / 47 / 67 ms; 33 / 47 / 63 ms | 33 / 49 / 63 ms; 33 / 48 / 75 ms | | | intervals ≥ 100 ms | 0 / 0 | 0 / 0 | | | peak RSS | 777 / 802 MB | 784 / 818 MB | | 5 m/s, 180 s (2 runs each) | look-tick rate | 29.07 / 29.15 Hz | 29.10 / 29.08 Hz | | | interval p50 / p99 / max | 33 / 47 / 103 ms; 33 / 45 / 129 ms | 33 / 47 / 104 ms; 33 / 47 / 106 ms | | | intervals ≥ 100 ms | 1 / 1 | 2 / 1 | | | peak RSS | 1279 / 1212 MB | 1224 / 1241 MB | Unchanged. The walker sends no `SetLodView`, so it is served the L3 rung and then full detail: no pruned tier with normals, and an earthlike region compresses ~5×, so the encode was never a walk cost (the profiled 50 m/s walk: prune 6 ms on main, the stream encode 2 ms on the branch). The walks' look tick was already at 29 Hz with no 100 ms stall after tick-long-tasks. ### 8.5 Look tick (pile-huge, 2 headless clients, 75 s, 2 runs each) | | ticks | p50 | p99 | max | |---|---|---|---|---| | main run 1 | 2092 | 1.24 ms | 15.21 ms | 24.7 ms | | main run 2 | 2092 | 1.24 ms | 13.20 ms | 24.9 ms | | branch run 1 | 2089 | 1.16 ms | 13.35 ms | 25.7 ms | | branch run 2 | 2096 | 1.11 ms | 13.34 ms | 21.7 ms | Unchanged within noise (nothing here touches the look tick). ### 8.6 The region-wire cache: memory and copies **What the cache holds.** It holds the compressed tiers, one per region, wire level and version, bounded at 256 MiB. The wire recorder's sizes show how small that is next to the region cache: | scenario (one client) | tiers | raw MB | in the wire cache (compressed) | |---|---|---|---| | surface-gi arrival | 865 | 104.3 | **2.8 MB** | | realistic-island-4 | 867 | 92.5 | 2.0 MB | | earthlike stand, 240 s | 237 | 97.1 | 15.1 MB | The cache is the same on both trees: JS ArrayBuffers that Bun's zlib wrote. JSC counts their bytes as external memory, as it would count native views of the same bytes. Moving the bytes into native memory would add a copy (JS → native) per tier, plus a view per send (`toArrayBuffer`, §2.6: ≈ 1 µs median but GC-triggering). It would remove nothing. **Not moved.** **Bytes copied on the main thread per served tier:** | | main | branch | |---|---|---| | message framing (`encodeRegionData`'s `set` of nodes, normals, palette) | the whole raw tier (104 MB in the surface-gi arrival above) | 0: the native encode writes the message into its JS buffer on a pool thread (tiers < 4 KiB: on the main thread, < 4 KiB each) | | `pruneTree`'s tight copy out of its scratch | the pruned material (35.5 MB in that arrival) | 0 | | deflate output (`compressForWire`: tag byte + `set`) | the compressed tier (2.8 MB) | the same | ### 8.7 The client's `pruneTree`: TS vs the wasm core (measured, not changed) The client prunes every region at upload (`region-manager.ts`). A wasm prune must first copy the region into linear memory (copy mode, as the edit core runs). That copy costs more than the TS prune, which visits only the kept nodes. 18 generated regions (earthlike and terrain, 3.4 MB mean), the median of 15 runs each, per region (`logs/rust-core-p4/client-prune-bench.txt`; the wasm module was a bench-only build of `tree_prune.rs`): | | ml1 | ml2 | ml3 | |---|---|---|---| | TS, V8 (node 22) | **1.45 ms** | **0.035 ms** | **0.004 ms** | | wasm, V8 (copy in, prune, copy out) | 1.81 ms | 0.36 ms | 0.32 ms | | TS, JSC (Bun 1.3.14) | **1.35 ms** | **0.11 ms** | **0.01 ms** | | wasm, JSC | 1.76 ms | 0.39 ms | 0.34 ms | Outputs are byte-identical. **The client keeps the TS `pruneTree`.** So does the server's L3 silhouette writer (`putCoarseDisplayFromFull`, root and L2 only). `common/src/tree-prune.ts` therefore stays, and `stream-tier-corpus` pins it against the native twin. ### 8.8 Phase 2 leftovers - **Done:** `cacheMaxBytes`'s doc describes the store bound (it still described the physics Worker's mirror world). - **Entity-structure normals:** no longer TS. The wasm edit core made `buildNormalSVT` native on the server. Measured: `die` (70 KB) 4.4 ms; the primitives 0.1–0.2 ms, synchronously at intern time (`bench/rust-core/p4/structure-normals.ts`). `StructureRegister` needs the result at once, and 4 ms per new structure does not justify a job. Left as is. - **SI table fed via `wr_put_si` copies:** not done. The fix is a `wj_put_si` that attaches the job's `Arc` when built from the current `nodes_id` (as `wj_put_normals` does), plus a view → entry map so the physics host's `storePutSi` can find it. It touches the physics feed, and nothing in this phase's measurements points at it. - **`physicsPullsOnDemand`:** not a test seam. It is the production gate that keeps eager SI builds for the direct `PHYS_ENGINE=rust` engine, which only `peek`s warm SI. Kept. - **`injectRegion` / `evictRegion`:** unused by production; used by 4 test files (17 sites). Deleting them means moving them to `test-support/` and exporting `lruSet` for it, or rewriting those tests on the generator. Listed, not done. - **A dead physics / CA Worker leaks its pins:** the leak is the Worker's whole native world (the physics `World` with its `PinCache`, the CA engine), not only the pins. The fix: the Worker posts its native handles after init, and the host destroys them on the Worker's `close` event after `_onFailure` (never before: the thread may still be inside a step). Not done (no Phase 4 code touches the Workers). ### 8.9 Phase 3 status (write-up only) The wasm edit core made the edit itself native (`csgEditPinned`: the input is read in place, the result lands as a store version without a copy). What remains of scoping's Phase 3 on the main thread, measured on a quiet box with `bench/rust-core/p4/edit-cost.ts`. Setup: a real earthlike world on a SQLite file, the spawn column's surface region (1.63 MB), 30 sphere edits r8 (carve/fill), 2 runs. | part of one `applyTerrainEdit` | p50 | p90 | |---|---|---| | **the whole call** | **12.4–12.8 ms** | 36 ms | | SQLite put of the region (`ws.store.put`) | 8.3–8.5 ms | 31–32 ms | | material SHA-256 (`materialHash`, the normals-cache key) | 0.9 ms | 1.0–1.1 ms | | `svtStateHash` (TS, the command's hash) | 0.84–0.88 ms | 1.2–1.3 ms | | the rest: the native edit, `lruSet`, SI / normals dispatch, wake scan (by difference) | ≈ 2.4 ms | — | What Phase 3 would still move, with an estimate for each: - **The SQLite put: ~8 ms per edited region, p90 31 ms** — two thirds of an edit. It does not need Rust: a writer off the main thread (as tick-long-tasks moved generated-region persistence to the worldgen Worker) removes it. The bytes are already a store version, so a Worker can pin them. This is the one Phase 3 item worth doing. - **`svtStateHash`: ~0.9 ms** per region. It is linear in the region's bytes (≈ 0.55 ms/MB here, so ≈ 2.5 ms on a 4.7 MB region). A native port must stay bit-identical to the clients' (TS today; the wasm core could carry it). Small. - **Material hash: ~0.9 ms.** Could be dropped if the normals cache keyed on the store's `nodes_id` while resident. Small. - **An edit thread with ordered results:** it would buy the remaining ≈ 2.4 ms per edit at the price of an asynchronous ack path (commands are applied in arrival order and acked with the post-edit hash). Not worth it at these numbers. ### 8.10 The A / no-A inputs **What remains on the server main thread.** - **Arrival** (the heaviest case measured; surface-gi, branch, 3 runs): 893–949 ms busy of a 9.5–9.8 s window, 9–10 %. Ranked: 1. SQLite 157–162 ms; 2. the main scan's session logic 153–164; 3. deflate's `node:zlib` wrapper 80–104; 4. generation completions 87–92; 5. job inputs (pins) 68–81; 6. the look tick 53–66; 7. `serverTick` 47–60; 8. the stream encode's TS 47–48; 9. job results 38–50; 10. the physics host 33–40; 11. material hash 21–31; 12. the rest < 25 each. - **Walks:** 29 Hz at 50 m/s and at 5 m/s, interval p99 47–49 ms, no 100 ms stall at 50 m/s. Profiled (Bun's sampler overstates, §7.7), the 50 m/s walk's 2.4–2.7 s of 90 s is `serverTick` 0.7 s, the look tick 0.4 s, the main scan 0.3 s, the physics host 0.2 s, `ws` messages 0.2 s, job results 0.1 s, SQLite 0.1 s. The stream encode is 2 ms. - **Edits:** 12.6 ms each, two thirds of it the SQLite put (§8.9). **What A would still buy over D.** - WebTransport (scoping §5.5: smoothness under loss, none on clean links). Safari only from 26.4, and stable Caddy cannot proxy it. - No Bun runtime: no JSC GC pauses and no `node:zlib` / `bun:sqlite` wrapper costs. On the arrival that is at most the ~0.9 s above, and most of it is session logic that A would rewrite rather than remove. - A free choice of deflate. The client accepts any deflate-raw; only this branch's byte-identity gate forbids it. **Within D, without A**, the next levers by size: - the SQLite put off the main thread (~8 ms per edit; ~160 ms per arrival for the reads and puts it can take); - deflate's per-call wrapper (~0.15 ms × ~580 tiers per arrival); - the generation completions (≈ 90 ms). **Recommendation: stop at D (no A).** After Phase 4 the server main thread is 9–10 % busy through the heaviest arrival measured. The look tick holds 29 Hz in both walks with no 100 ms stall. What is left is spread over a dozen items of ≤ 160 ms each, and the largest (SQLite) moves off the main thread within D. A is ~45k lines (scoping §5.4) for WebTransport and the absence of a runtime that is no longer the bottleneck. It is the owner's decision. ### 8.11 Owner decisions (none landed) - **Stream pool threads: 2** (`STREAM_ENCODE_THREADS`). An arrival's tiers ≥ 4 KiB are 1–15 ms of CPU each. The pool sits outside the compute budget, as the main thread's encode did. At a full 6-token budget that is up to 2 extra busy threads on 8 cores, during an arrival only. - **A or no A** (§8.10). ### 8.12 Leftovers - The Phase 2 items of §8.8 not done: the SI table attach-in-place, the `injectRegion` / `evictRegion` seams, the dead-Worker native world. - The SQLite put of edits and of generation completions (§8.9, §8.10): the largest main-thread items left, and D work. - One Bun 1.3.14 crash in a profiled walk: `SystemError: Failed to get memory usage` from `process.memoryUsage()` in the memtrace timer (as in tick-long-tasks). Re-run. `logs/rust-core-p4/bl/br-walk-prof.crash1.srv.log`. --- ## 9. Reproduce ```sh bun bench/rust-core/make-corpus.ts ../logs/rust-core-p0/corpus bun bench/rust-core/make-csg-corpus.ts ../logs/rust-core-p0/corpus ../logs/rust-core-p0/corpus-csg bun bench/rust-core/make-normals-extra-corpus.ts # → ../logs/rust-core-p0/corpus-normals-extra (cd voxel-core && cargo test --release) # corpus parity (RUST_CORE_CORPUS overrides) (cd world-rs && cargo test --release && cargo build --release) bun bench/rust-core/world-bench.ts ../logs/rust-core-p0/corpus bun bench/rust-core/pm-recheck.ts WASM_LD=/bin/wasm-ld voxel-wasm/build.sh # voxel_wasm.wasm + voxel_wasm_simd.wasm bun bench/rust-core/wasm-bench-bun.ts ../logs/rust-core-p0/corpus 15 PORT=3985 bun bench/rust-core/wasm-bench-serve.ts ../logs/rust-core-p0/corpus out.json # then on utsuho (under logs/utsuho.lock): with-gpu-display chromium --ozone-platform=x11 --no-sandbox \ # --unsafely-treat-insecure-origin-as-secure=http://nazrin:3985 http://nazrin:3985/?runs=25 bun bench/rust-core/wasm-bench-table.ts out.json # Phase 1 (§6): one library, then the same baselines on main e0f4f5fd and this branch bun run build:world-rs && (cd world-rs && cargo test --release) bun scripts/physics-suite.ts --raw > raw.txt # diff against main's (non-log lines) bench/rust-core/p1/run-baselines.sh boot|looktick|walkprof|walkslow|walklong|arrival both python3 bench/rust-core/p1/walkstats.py ../logs/rust-core-p1/bl p1-walk-prof # Phase 4 (§8): goldens, the wire proof, then the baselines on main 4c4b1b4e and this branch GOLDEN_RECORD=1 bun test server/src/world/stream-tier-corpus.test.ts # on main's TS only bench/rust-core/p4/run-baselines.sh wire|arrival|walkfast|walkslow|looktick|walkprof both bun bench/rust-core/p4/wirehash.ts --compare ../logs/rust-core-p4/wire/main-sg.json ../logs/rust-core-p4/wire/br-sg.json python3 bench/rust-core/p4/mainthread.py ../logs/rust-core-p4/bl br-sg-arrival-1 arrival python3 bench/tick-long-tasks/tickstats.py ../logs/rust-core-p4/bl br-walk-fast-1 bun bench/rust-core/p4/edit-cost.ts 30; bun bench/rust-core/p4/structure-normals.ts # Phase 2 (§7): the same baselines on main 144feeed and this branch bun run test:corpus # incl. normals-native-corpus.test.ts bench/rust-core/p2/run-baselines.sh boot|looktick|arrival|walkprof|walkslow|walklong both python3 bench/rust-core/p2/mainthread.py ../logs/rust-core-p2/bl p2-sg-arrival-1 arrival python3 bench/rust-core/p2/longtasks.py ../logs/rust-core-p2/bl p2-walk-prof 50 # baselines (§5); arrivals under logs/utsuho.lock: bun bench/rust-core/baseline/arrival.mjs sg-arrival-1 --fixture surface-gi --pose -384,112,-320,0.8,0.25 --max 120 --hold 5 python3 bench/rust-core/baseline/analyze.py ../logs/rust-core-p0/baselines sg-arrival-1 arrival bench/rust-core/baseline/boot.sh bare-1; bench/rust-core/baseline/boot.sh surface-gi-1 FIXTURE=surface-gi bench/rust-core/baseline/looktick.sh lt-pile-1 pile-huge 75 [PROF=1] bench/rust-core/baseline/memwalk.sh walk-long 720 800 ```