# Long main-thread tasks and the 30 Hz look tick; a generation priority lane Branch `tick-long-tasks` from main 42a462fd (option D Phase 2 merged). The targets were the long tasks (≥ 50 ms) that `docs/rust-core.md` §7.7 measured in the 50 m/s walk, and a priority lane for world generation (§7.8). Every number below was taken on **Bun 1.3.14**, main 42a462fd re-run in the same session (a detached worktree, `logs/tick-long-tasks/base-42a4`), with Phase 2's scripts, conditions and run counts, alternating main and branch run by run (`bench/tick-long-tasks/run-baselines.sh`; gate: Bun 1.3.14, no `/tmp/gi-gate*.lock` held, load < 2). Raw data: `logs/tick-long-tasks/bl/` (first chain) and `bl2/` (after the last commit; the tables use `bl2` unless a column says otherwise). ## 1. What changed | target | Phase 2 (profiled 50 m/s walk) | cause | change | |---|---|---|---| | generation completion | 25 tasks, 2179 ms | SQLite put 839 ms; two full-region SHA-256s 532 ms; logging 180 ms | the worldgen Worker writes the row and computes the material hash; the store's per-row hash is gone; the logger keeps its file open | | the join | 1094 ms, once per connect | `getPrefabSpec` built every code prefab's SVT in TS to read its AABB | `getPrefabAabb`: AABBs without building | | `_tickImpacts` in the look tick | 403 ms | not its work (below) | none | | job completions (`_poll`) | 392 ms | not its work (below) | none (fewer native views overall) | | generation priority | an urgent region waits behind FIFO client requests | — | a queued region a held body needs moves to the queue head | ### 1.1 Generation completions **Why two hashes.** The two full-region SHA-256s were different hashes: 1. `regionHash` (coord + nodes + palette) in `RegionStore.put`, written to the `hash` column of every row. Nothing read it back except `verify()` (one test) and `worldHash()` (`bench/run.ts`'s "was the bench world edited" check). 2. `materialHash(nodeBytes)`, the key of the SI, normals and coarse-display caches. On a completion the physics host's region-changed hook (`SurfaceInitiatorsCache.peek`) computed it to look up a SQLite SI row that a freshly generated region cannot have, and it materialised a GC-owned view of the whole region to do so. The coarse-display put then hashed again (its memo is keyed on a short-lived view). **Now:** - The worldgen Worker, after `generatePinned`, reads the pinned version through short-lived views, computes `materialHash` and writes the row with `RegionStore.putVirgin` (INSERT OR IGNORE) on its own connection, then posts the pin, the hash and `persisted: true`. The main thread seeds the façade's memo (`seedMaterialHash`), so the coarse-display put, the SI build request and the SI cache read the hash for free. - Empty results stay with the main thread (a physics-only empty is not persisted), as do in-memory worlds (`dbPath` `:memory:`). - `SurfaceInitiatorsCacheStore.get` takes the hash as a function, computed only when a stored row exists; the SI cache reads it through the façade memo (no GC-owned view). - `RegionStore.put` no longer hashes (rows written from now on store `''`). `regionHash` and `verify` are deleted; `worldHash` hashes the stored rows' bytes when called (a bench's saved hash mismatches once and the bench world regenerates). - The per-region `log.debug` line is gone; `Logger` keeps each channel's fd open (`appendFileSync` was open + write + close per line). **Why INSERT OR IGNORE is safe, and durability.** Generation is deterministic and only ever produces virgin bytes; region rows are never deleted. So a row already present for the coord is the same virgin bytes or newer ones (an edit or a CA write-back, both still written by the main thread with INSERT OR REPLACE), and keeping it is right in either order. Main used the same rule from the other side (a completion whose key is in `generatedKeys` is dropped). | | before | after | |---|---|---| | who writes a generated region's row | main thread, in the completion | the worldgen Worker, before it posts the completion | | when | after the region was landed in the store, before it was served | before the main thread learns of it | | transaction | autocommit, WAL, `synchronous = NORMAL` | the same | | on an existing row | (not reached: completion dropped) | kept (INSERT OR IGNORE) | | edits, CA write-backs, empties | main thread | main thread, unchanged | Durability is unchanged (same journal and sync settings), and a region's row is committed no later than before relative to serving it. The only new interaction is lock contention: the entity and structure stores' connections to the same file had no `busy_timeout` and threw `SQLITE_BUSY` once (an entity delete on disconnect, `bl/br-stand-pool1`); both now wait up to 5 s, as the region store's connection already did. A main-thread entity write can wait for one region commit (~30 ms); none of the walks below shows it. ### 1.2 The join `session.ts` advertised the catalog by calling `getPrefabSpec` for every key, which built the die and the primitives with `buildRegionTree5` in TS (1.0 s of the 1.1 s stall), only to read `localAabbMin/Max`. `getPrefabAabb` returns a library entry's stored bounds or a code builder's declared ones (the builder returns its sampler; building is the expensive part). A code prefab's material is now built when one is first spawned or previewed: once per key per process, 0.1–0.2 s each on the main thread (die ≈ 0.19 s), instead of all seven at every connect. ### 1.3 `_tickImpacts`, `_poll` and "GC from native views" `_tickImpacts` does no work in the walk (no contact events); the profiles show the main thread *stopped* in trivial frames: `new Map` (28 samples over 129 ms), `slice` in `tickLooks`, `cloneObject` of a 4-field object in `accounts.updatePosition`, `toArrayBuffer` in `siViews`, `_promoteFollowUp`, `unpin`, `wr_pin_desc`. Findings: - **JSC GC is not it.** An unprofiled walk with `BUN_JSC_logGC=1` (`logs/tick-long-tasks/diag/br5-gclog.srv.log`): 7 692 eden and 3 full collections in 90 s, no single pause above 30 ms. - **Native views do count as GC pressure**: a `toArrayBuffer` view of 12 MB, with or without a finalizer, adds 12.6 MB to JSC's extra memory (a scratch test). The branch removed the main region-sized views of the walk (the SI peek's façade materialisation, the persist and hash views): the probe's `ab=` at the walk's 60-region mark fell from 353 MB to 27–56 MB. - **The stalls are the profiler's.** They appear only in `--cpu-prof` runs: every unprofiled walk on the branch has 0–2 look-tick intervals ≥ 100 ms (below), against 48–289 on main. Bun's sampler suspends the main thread to take each sample; on a box saturated by generation (8 native gen threads + job threads on 8 vCPUs) a suspended main thread can wait a scheduler slice or more. So Phase 2's "~0.4 s of GC from native views" was this artefact landing on allocation sites; the profiled long-task list overstates what a player sees. ## 2. Look tick: before / after ### 2.1 Walks (fresh earthlike world, one headless walker along +X) | walk | | main 42a462fd | branch | |---|---|---|---| | 50 m/s, 90 s, **profiled** (Phase 2's run; `bl` / `bl2`) | rate | 22.43 / 22.29 Hz | 24.88 / 27.72 Hz | | | interval p50 / p99 / max | 34 / 240 / 1142 ms; 34 / 239 / 1118 ms | 34 / 178 / 546 ms; 33 / 99 / 329 ms | | 50 m/s, 90 s, unprofiled (2 sessions × 2 runs) | rate | 26.06–26.36 Hz | **28.80–29.03 Hz** | | | interval p50 / p99 / max | 34 / 133–143 / 1097–1114 ms | 33 / **48–52 / 70–96 ms** | | | intervals ≥ 100 ms | 48–55 | **0** | | 5 m/s, 180 s (`bl` / `bl2`) | rate | 26.52 / 26.60 Hz | **29.05 / 29.14 Hz** | | | interval p50 / p99 / max | 34 / 131 / 1102 ms; 34 / 128 / 1139 ms | 33 / 48 / 125 ms; 33 / 47 / 127 ms | | | intervals ≥ 100 ms | 113 / 113 | 1 / 2 | | 50 m/s, 12 min (`bl`) | rate | 27.19 Hz | **28.82 Hz** | | | interval p50 / p99 / max | 34 / 121 / 1092 ms | 33 / **50 / 144 ms** | | | intervals ≥ 100 ms | 289 | 2 | | | peak RSS | 3234 MB | 3246 MB | | standing at spawn, 90 s | rate | 25.68 / 25.42 Hz | 28.69 / 28.18 Hz | | | interval p99 / max | 207 / 1083 ms; 215 / 1127 ms | 63 / 101 ms; 67 / 108 ms | The look tick's own duration is unchanged (p50 0.07–0.08 ms in both). The interval median is 33 ms on the branch (34 on main): the 30 Hz timer now fires on time. ### 2.2 Long tasks ≥ 50 ms (profiled 50 m/s walk, `longtasks.py`; `bl2`, `bl` in brackets) | heading frame | main: n, total | branch: n, total | inside it on the branch | |---|---|---|---| | **all** | 44, 5.3 s [44, 5.0 s] | **18, 1.5 s** [28, 3.0 s] | | | join (`handleMessage`, at connect) | 1082 ms [1121] | none (14 ms) | — | | other `handleMessage` | 5, 597 ms [11, 1031] | 1, 78 ms [1, 255] | stalled in `cloneObject` (§1.3) | | generation completion | 18, 1600 ms [13, 1273] | **4, 341 ms** [2, 223] | no SQLite, hash or log; stalled in `_notifyRegionChanged`, `pinDesc`, `unpin` | | the look tick | 8, 761 ms [6, 479] | 5, 536 ms [5, 452] | stalled in `new Map` (`_tickImpacts`), `slice` (`tickLooks`) | | `serverTick` / `caTick` | 9, 944 ms [7, 589] | 5, 371 ms [10, 954] | stalled in `setProactiveQueue`, `isGenerated` | | job completions (`_poll`) | 0 [3, 274 ms] | 2, 106 ms [4, 524] | stalled in `toArrayBuffer`, `_promoteFollowUp` | What is left in the profiled list is §1.3's artefact: unprofiled, the same walk has no interval of 100 ms. ### 2.3 Join stall Longest main-thread task while the walker connects: main 1121 / 1082 ms; branch 14 ms (`bl2`; `bl`'s 255 ms task was a later PlayerPos message stopped in `cloneObject`, §1.3). ### 2.4 Pile-huge look tick (2 headless clients, 75 s, 2 runs each) | | ticks | p50 | p90 | p99 | max | physics `postMessage` | |---|---|---|---|---|---|---| | main run 1 | 2096 | 1.14 ms | 5.02 ms | 13.18 ms | 22.5 ms | 67 ms | | main run 2 | 2096 | 1.14 ms | 4.90 ms | 13.70 ms | 36.8 ms | 67 ms | | branch run 1 | 2094 | 1.29 ms | 4.88 ms | 14.20 ms | 24.7 ms | 67 ms | | branch run 2 | 2094 | 1.27 ms | 5.03 ms | 13.46 ms | 23.5 ms | 72 ms | p90 and up are unchanged; the median is 0.13–0.15 ms higher on the branch in both runs. Nothing on the branch touches the look tick's code; Phase 2 saw 1.12–1.17 ms across its four runs. Not explained (§6). ### 2.5 Surface-gi arrival (headed Chromium on utsuho, pose 0) | | main | branch | |---|---|---| | settle | 7.0 s ×4 | 7.0 s ×3 | | regions / nodes at settle | 142 / 3 854 840 | 142 / 3 854 840 | | main thread busy | 1632, 1650, 1674, 1671 ms | **1520, 1534, 1543 ms** | | of which gen completion | 166–189 ms | 94–123 ms | Branch run 2 failed to connect the browser on utsuho (`Unable to connect`); a fourth pair was run instead. ## 3. Generation: the priority lane ### 3.1 What landed `queueGeneratePhysicsUrgent` (a region a held body needs) lifted the pool priority of a region already requested, but a region still in the manager's FIFO client queue stayed behind every streamer request queued before it. It now moves to the queue head at physics-urgent priority, and the pump's saturated-lane bypass keys on that priority. "A region in a player's immediate footprint" is covered by the same path: the player's avatar shadow is a body, held while its footprint has no terrain (no kind rule). ### 3.2 What the lane cannot do at 6 Workers All six gen Workers fan their regions out on micropool's one process-wide pool, so an urgent region that starts beside others shares the CPU with them. A gate that started nothing else while an urgent job waited or ran (tried, not landed) did not help: the region still shares with the jobs already running, urgent latency 4.5 / 5.2 s against 3.5 / 4.4 s without it. Running "first and alone" needs fewer concurrent regions, i.e. a smaller pool — an owner decision (§5). ### 3.3 Latency and throughput (`bench/tick-long-tasks/gen-latency.ts`, quiet box, 2 runs each) Earthlike seed 42691. *Row*: 12 regions along the walk's row (spawn ry and ry−1), urgent region requested 1.5 s in. *Block*: the 5×5×5 block around spawn (124 regions: sky, surface, underground), urgent region 3 s in. | | main, 6 Workers | branch, 6 | branch, `WORLDGEN_POOL_SIZE=2` | branch, `=1` | |---|---|---|---|---| | row: throughput | 0.76, 0.76 /s | 0.76, 0.76 /s | 0.75, 0.75 /s | 0.71, 0.71 /s | | row: region latency p50 / max | 12.1–13.7 / 17.1 s | 12.6–13.0 / 17.1 s | 10.3 / 17.3 s | 10.9 / 18.4 s | | row: first region | 4.1 s | — | 2.5–2.9 s | 1.1 s | | row: urgent region | 4.2, 4.2 s | 4.4, 3.8 s | 3.7, 2.5 s | **2.4, 2.4 s** | | block: throughput | 0.83, 0.91 /s | 0.93, 0.92 /s | 0.90, 0.90 /s | 0.84, 0.84 /s | | block: urgent region | 4.7, 4.7 s | 3.5, 4.4 s | 2.4, 2.3 s | **1.9, 1.8 s** | | one region alone | — | — | — | 0.6–1.9 s | Bytes are untouched: generation code did not change (`test:corpus` passes, 83/83), and the Worker reads the pinned version it built. ### 3.4 Hold-in-place (fresh earthlike, the avatar shadow) | run | main | branch (6 Workers) | `WORLDGEN_POOL_SIZE=2` | `=1` | |---|---|---|---|---| | standing at spawn, 90 s: hold until the footprint lands | 24.8 s, 27.4 s | 19.8 s, 12.3 s | 6.85 s, 7.0 s | 7.0 s, 6.75 s | | 50 m/s and 5 m/s walks | held the whole walk | held the whole walk | — | — | The spawn (1024, 233, −1024) sits on a region corner: the shadow's footprint needs eight regions, 0.6–1.1 s each alone, so ~7 s is the floor at any pool size. The walker still outruns generation at both speeds (a new region every 3.2 s at 5 m/s against 1–2 s per region alone and a ball of proactive work). ## 4. Gates - `physics-suite --raw`: 812 `RAW` lines, identical to main 42a462fd. - `test:corpus`: `TOTAL: 83 pass, 0 fail across 1 shard`. - `bun run check` passes; `bun run lint`: 16 warnings, as main. - `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 pre-existing `late join: every join phase is served the worker's authoritative water`; `ca-suite` `13-earthlike-coast: liveSync=PASS reload=FAIL` as on main. - Surface-GI gate: not run here (the orchestrator runs it). ## 5. Owner decisions (none landed) - **Gen Worker count** (`WORLDGEN_POOL_SIZE`, default cores − 2 = 6). From §3.3–3.4: | Workers | urgent region | standing-spawn hold | throughput (block) | |---|---|---|---| | 6 (now) | 3.5–4.4 s | 12–20 s | 0.92 /s | | 2 | 2.3–2.4 s | 6.9–7.0 s | 0.90 /s (−2 %) | | 1 | 1.8–1.9 s | 6.8–7.0 s | 0.84 /s (−9 %) | Recommendation: 2 — most of the latency win for ~2 % throughput. 1 is the only size where an urgent region truly runs alone. Either size also leaves the compute budget's surplus tokens idle for gen (the boot warns `COMPUTE_BUDGET 6 > worldgen pool capacity`; that warning would need rewording). The surface-gi harness and the route benches already run 1–2. ## 6. Leftovers - The profiled long-task list is dominated by the sampler's stalls (§1.3); a run-to-run look-tick comparison should use unprofiled walks. - Pile-huge look-tick median +0.13 ms on the branch (§2.4), unexplained. - A code prefab's material is built in TS on its first spawn or preview (0.1–0.2 s once per key per process); moving `buildRegionTree5` for the catalog to native or a Worker would remove it. - SI job results still reach the TS warm cache as GC-owned native views (`siViews`; ~0.25 MB per region); attaching them to the store's side table in place (as normals are) is Phase 2's leftover. - Main-thread entity / structure writes can now wait for a Worker's region commit (≤ ~30 ms); not visible in any run here. - micropool's pool is shared by worldgen and the physics Worker's parallel passes and sized to all 8 vCPUs, so generation saturates the box (the compute budget's reserved cores are not reserved from it). A `VOXEL_PAR_THREADS=6` diagnostic walk was inconclusive; not landed. - One Bun crash recorded: a diagnostic walk's server died with `SystemError: Failed to get memory usage` from `process.memoryUsage()` in the memtrace timer (`logs/tick-long-tasks/diag/br1-walk-prof.srv.log`); not reproduced in ~25 later runs. ## 7. Reproduce ```sh bench/tick-long-tasks/run-baselines.sh walkprof|walkfast|walkslow|walklong|looktick|stand|standpool|arrival both python3 bench/tick-long-tasks/tickstats.py ../logs/tick-long-tasks/bl2 br-walk-fast-1 python3 bench/rust-core/p2/longtasks.py ../logs/tick-long-tasks/bl2 br-walk-prof 50 python3 bench/rust-core/p2/mainthread.py ../logs/tick-long-tasks/bl2 br-sg-arrival-1 arrival bun bench/tick-long-tasks/gen-latency.ts 12 1500 # row bun bench/tick-long-tasks/gen-latency.ts 0 3000 # 5×5×5 block BUN_JSC_logGC=1 bench/rust-core/baseline/memwalk.sh