# Every SQLite write off the server main thread Branch `write-offload` from main 0f4869b5 (option D Phase 4 merged), the follow-up after `docs/rust-core.md` §8. The owner's request: "move writes off the main thread in general". Every number below was taken on **Bun 1.3.14** against main 0f4869b5 re-run in the same session (a detached worktree, `logs/write-offload/base-0f48`), alternating main and branch run by run (`bench/write-offload/run-baselines.sh`; gate: no `/tmp/gi-gate*.lock` held, load < 2 at each start). Raw data: `logs/write-offload/bl/` (first chain), `bl2/` (look tick, entity scene and soak re-run after the last code commit, 2472f704; those tables use `bl2`), `crash/`, `inv/` (inventory). The surface-GI gate was not run here (the orchestrator runs it). ## 1. Inventory: the writes on the main thread (main 0f4869b5) Measured with `bench/write-offload/sqlite-probe.ts`, a preload that times every `bun:sqlite` call on the main thread (ms are the calls' wall time). | scenario | what writes | calls | total | per call (avg / max) | |---|---|---|---|---| | one edit every 2 s (sphere r 12), fresh earthlike, 120 s | region row puts | 84 | **5.0 s** | 59 / 180 ms | | | SI cache puts | 180 | 0.67 s | 3.7 / 48 ms | | | normals cache puts | 86 | 0.51 s | 5.9 / 45 ms | | | all writes | 733 | **6.4 s (5 % of the window)** | | | `applyTerrainEdit` alone, quiet box (edit-cost, 60 edits r 8) | the region put inside it | 60 | | p50 13 ms of the call, p90 36 ms | | edit soak (brush drags 30/s + 32³ box stamps every 5 s), 90 s | region row puts | ~5 000 | **71 s in the 90 s burst** | 72 / 564 ms | | dice spawns, 4/s, earthlike file world, 75 s | entity `INSERT` | 241 | 2.6 s | 10.8 / 69 ms | | | entity flush (one transaction per spawn) | 241 | 2.2 s | 9.0 / 57 ms | | pile-huge fixture, 2 clients, 75 s (in memory) | entity flushes (scrape-loop audio emitters flush every dirty pose) | 2 066 txns, 570 k component rows | **2.9 s** | 1.4 / 17 ms | | surface-gi fixture arrival (profiled, in memory) | region rows of generations, normals | | **154–160 ms** of 902–910 ms busy | | | 50 m/s and 5 m/s walks | SI cache puts (regions come from the worldgen Workers) | ~90 | 0.24–0.35 s | 2–2.4 / 40–94 ms | | any | accounts (30 s flush + on leave), world meta (clock save) | few | < 5 ms | | Why a put costs 59–72 ms on a file world when edit-cost's quiet put is 8 ms: earthlike rows are 1.6–4.7 MB, the WAL's auto-checkpoint (every ~4 MB) runs inside the put and fsyncs (`synchronous=NORMAL`), and the main thread waits for the write lock while a worldgen Worker commits its virgin rows. Under the soak the main thread spent 71 of 90 s in SQLite and the look tick fell to 0.2 Hz. **Reads, not moved** (they answer the caller now): in the edit scenarios the main thread also issues 1.2 M region-row `SELECT`s per 3 min (5.8 s; 10 k/s, nearly all for coords that have no row: `tryGet` reads the store on every cache miss before it knows whether the coord was ever generated; 56 of them ≥ 20 ms, the real loads of multi-MB rows). §8 lists the fix. ## 2. Design: one writer Worker per world `server/src/db/db-writer.ts` (main side), `db-writer-worker.ts` (the Worker). - **One Worker per world, one connection per database file** (world.db, the normals / SI / coarse-display caches, accounts.db). Every store kind on a file shares the connection, so a batch is **one transaction per file**. The main thread keeps its own connections and only reads. - **Ops.** A store in writer mode turns each write into `[storeId, op, ...args]` and appends it to the current batch. Each store's write statements are one class (`RegionWrites`, `NormalsWrites`, `SiWrites`, `CoarseWrites`, `StructureWrites`, `EntityRowWriter`, `AccountWrites`) that the store runs in place without a writer and the Worker runs with one. - **Batches.** The batch is posted once per event-loop turn (`setImmediate`), and only when the previous one has committed: a busy Worker meets fewer, larger batches (group commit), and a whole-row write of a row already in the buffer replaces the earlier one (region rows, cache rows, an entity's row: a brush drag writes its region once per batch; the soak coalesced ~1 400 writes). - **No copies of region bytes.** A region write carries a pin of the store version (`putPinned`: edits, generation completions, CA flushes); the Worker reads the version in place and the pin is released at the commit. Native normals and SI results travel as references to their native entries (`cloneNormals`, `cloneSi`; the SI blob is packed in the Worker). What is still structured-cloned: entity rows and components, structure material (a new structure or an entity edit, ~70 KB), coarse silhouettes (KBs), meta, accounts. Measured: 10 ms of `postMessage` per arrival, 0.3–0.6 s per 75 s in pile-huge (entity flushes; 0.9 ms per batch). - **Fixture worlds** (the deployed server runs one) were `:memory:`, which a Worker cannot reach: they now live in `data/fixture-worlds//` (world + accounts), deleted at shutdown and, after a crash, at the next fixture boot. `:memory:` worlds (tests, harnesses) have no writer and write in place, as before. - **Ids.** `entities` and `structures` are AUTOINCREMENT tables whose new id the caller needs at once: the stores allocate it as AUTOINCREMENT does (past `sqlite_sequence` and every row, `nextAutoincrementId`) and insert it explicitly, so no write answers the main thread. Same ids and the same `sqlite_sequence` as main (§4). - **The worldgen Workers** still write their own virgin rows on their own connections (`putVirgin`, INSERT OR IGNORE: order-independent against the writer's edits, `docs/tick-long-tasks.md` §1.1). ### 2.1 Read-your-writes Each store keeps an overlay of its pending writes, stamped with the batch they are in, and a read consults it before the file: | store | the overlay holds | a read of a pending key returns | |---|---|---| | regions | the pinned version (or bytes), or a tombstone | a copy of the pending bytes / nothing | | meta, CA sub-ticks | the value / the blob or a tombstone | it | | normals, SI caches | the bytes or SoA with its material hash, or a tombstone; a conditional delete (`deleteBuried`) as "unknown" | a hit only on the same hash; "unknown" reads as a miss (always correct for a cache) | | coarse display | per level the payload, and whether a delete-all came first | the payload / nothing | | entities, structures, accounts | none: their in-memory maps are the read path (the files are read at load only; `StructureStore.get` drains first) | — | An entry leaves the overlay when the batch holding the key's **last** write commits; the main connection's next read starts a new WAL read transaction and sees that commit. So no read can return bytes older than the last write issued: before the commit it gets the overlay, after it the file. ### 2.2 Ordering - One FIFO per world, one batch in flight, ops applied in issue order on one connection per file: two writes of a row land in issue order (coalescing only drops a write superseded inside its own batch, i.e. inside the same transaction). - A batch commits the cache files first and world.db / accounts.db last, so a crash between the commits keeps the batch's cache deletes (a miss, rebuilt on demand) and can keep cache puts derived from world.db writes that were lost. Since round 5 those puts carry the batch's write generation and the next open drops them (§18; before, the coarse silhouette, read unchecked, could describe a lost edit). - Cross-table invariants on world.db hold at every commit: the entity ↔ structure rows, structure dedupe by hash (the UNIQUE index sees the same statement order the main thread issued), regions + CA sub-ticks (`transaction` keeps a CA flush in one batch). Main committed each statement on its own, so the file now only ever holds turn boundaries. ### 2.3 Durability: acks after the commit (superseded: terrain §10, entities §16) **Today (main).** `synchronous=NORMAL` in WAL mode: a write is committed to the WAL (the OS page cache) when the statement returns, and an edit command is sent (its ack and the peers' copies) right after `applyTerrainEdit`, whose put has returned. So an acked edit survives a process crash (kill -9); a power cut can roll back what was committed since the last checkpoint (the WAL is fsynced only at checkpoints: up to ~4 MB of frames, one to three region rows). A spawn's entity row is committed before its `EntitySpawn` goes out; an entity edit's structure row before its ack. **Branch: the same guarantee.** The sends of a player's mutation wait for the commit of the writes it issued (`net/durable-sends.ts`): the terrain command's ack, peers' copies and results (`whenDurable`, FIFO behind the command), and an entity edit's, spawn's or delete's messages (held for the mutation's sockets, then sent in order). The server's state changes at once; only the messages wait. Same pragmas, so the power-cut exposure is the same. Measured in §5: no acked edit, no seen entity lost on either tree. What the branch can lose on kill -9 that main had written: unacked writes in the queue (at most one batch in flight plus the buffer: generated rows, regenerated deterministically; cache rows, rebuilt; entity poses, which main also only wrote at the next spawn / edit flush; accounts, flushed every 30 s on both). **The cost of holding the acks** is the commit wait: 97 ms mean (max 155 ms) for a lone r 12 edit on earthlike, 191–231 ms (max 770 ms) under the soak. See owner decision D1. **Since round 2 (§10) terrain edit commands no longer wait** (the owner's decision), **and since round 3 (§16) spawns, deletes and entity edits do not either** (the owner's D4): nothing waits for a commit, `net/durable-sends.ts` and `whenDurable` are deleted. ### 2.4 Back-pressure, slow disk, shutdown - Uncommitted bytes (pinned versions included) are bounded by `DB_WRITER_MAX_MB` (default 512). Past it the main thread waits on the Worker (`Atomics.wait` on a shared commit counter) until half is free — what every write did before. Never reached in these runs: peak 11 MB in the soak, 1.5 MB in the spawn scene, 17 MB in a fixture join. - A slow disk therefore shows up as late acks (the commit wait), then, past the bound, as main-thread waits; the look tick keeps running until then. - A failed batch is retried op by op; an op that fails is logged and dropped, as a throwing write was. A Worker that dies is respawned and handed every uncommitted batch again (the ops replay the same rows). - `closeWorld` drains the writer (flush + wait for the last commit) before the stores close; SIGTERM's shutdown queues the accounts' last flush, then closes the world. Measured: 1–2 ms at the end of edit-cost. ## 3. What was built, what was deleted | piece | where | |---|---| | The writer (main side: batches, coalescing, overlays' commit hook, drain, bound, respawn; Worker: connections, one transaction per file, cache files first) | `server/src/db/db-writer.ts`, `db-writer-worker.ts` (+ test) | | Write sides + writer mode + overlays | `world/store.ts`, `normals-cache.ts`, `surface-initiators-cache-store.ts`, `coarse-display-store.ts`, `structure-store.ts`, `entities/entity-store.ts`, `accounts.ts` | | Region rows by pin (edits, generation completions, CA flushes) | `world/manager.ts` | | Acks after the commit (entity mutations only since §10; deleted in §16) | (was `net/durable-sends.ts`) | | Fixture worlds on a throwaway file | `main.ts` | | The SI build's "already cached?" check reads the hash, not the blob (1.3 s per 90 s soak) | `SurfaceInitiatorsCacheStore.has` | Deleted: every synchronous write path on the main thread (the stores' write statements now live once, in their write-side classes, run in place only without a writer), the `lastInsertRowid` round trips, the fixture `:memory:` world. ### 3.1 Phase 4 leftovers (`docs/rust-core.md` §8.8) - **SI table attached in place.** `wj_put_si` attaches a job's native SI entry to the store's side table, shared, when it was built from the coord's current node bytes (`attach_si_built`); `storePutSi` finds the entry behind the views (`siEntryOf`). A SoA loaded from the SQLite cache, or one for a version since replaced by equal bytes, is still copied once. World ABI 5. - **A dead physics / CA Worker's native world is freed.** Both Workers post their native world in `ready`; on a restart the host frees it on the dead Worker's `close` (after the thread is gone, never mid-step). The worker-death test checks the free. - **`injectRegion` / `evictRegion` deleted.** Tests land a region through production paths (`test-support/regions.ts` `landRegion`: persist the row, evict a resident version as the LRU does, read it back with `tryGet`) and evict with `evictResidentRegion`, the LRU's own eviction body (`lruEvictOne` calls it). The old `evictRegion` also dropped `generatedKeys`, which the LRU never does. ## 4. Gates - `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: 2084 pass, 0 fail across 38 shards`, no Bun panic (main 2079 + the writer's 5). - `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`; `13-earthlike-coast reload=FAIL`. As on main. - **Stored bytes identical** (`bench/write-offload/stored-bytes.ts`: a fresh earthlike world, the spawn block generated, 40 sphere / box edits, 6 dice spawned, a pose flush, an entity edit, two despawns (one reclaiming the edited structure), a meta write, an account flush; then `closeWorld`), with and without the native job pool: the same rows and SHA-256 per table on both trees for regions, palettes, meta, ca_subticks, entities, components, structures, sqlite_sequence, accounts, normals, coarse_display (timestamps excluded). ## 5. Before / after ### 5.1 Edits | | main 0f4869b5 | branch | |---|---|---| | `applyTerrainEdit` p50 / p90 / max (edit-cost, 60 × r 8, quiet box, 2 runs) | 13.3 / 36.3 / 53.6 ms; 13.0 / 36.2 / 44.9 ms | **4.2 / 4.5 / 20.1 ms; 4.3 / 4.7 / 19.3 ms** | | lone edit every 2 s (r 12, earthlike, 120 s, 2 runs): ack p50 / p95 / max | 122 / 154 / 212; 121 / 164 / 180 ms | 138 / 185 / 195; 135 / 179 / 192 ms | | — the commit wait inside the branch's ack (mean / max) | — | 97 / 144; 97 / 155 ms | | — look-tick interval p99 / max, ≥ 100 ms intervals | 141 / 225 ms, 59; 139 / 201 ms, 61 | **65 / 113 ms, 1; 62 / 146 ms, 1** | | — main-thread SQLite writes | 6.4 s; 6.4 s | 0.2 ms | Click → visible for the **editor** is its local prediction (`docs/net-edit.md` §3: the next frame), which no server change touches. For a **peer** the edit shows when the command arrives, ≈ the editor's ack: +15 ms p50 on the branch (owner decision D1). ### 5.2 Edit soak (brush drags 30/s + box stamps every 5 s, 90 s; `bl2`) Beyond what the server can apply on either tree; the burst is the point. | | main | branch | |---|---|---| | edits acked in the burst | 957 / 1 997; 930 / 1 997 | **1 859 / 1 866; 1 854 / 1 868** | | ack p50 / p95 | 27.8 / 50.8 s; 25.9 / 48.6 s | **0.28 / 0.58 s; 0.34 / 0.63 s** | | look tick | 0.23 Hz (one 30.6 s interval); 0.24 Hz (41.6 s) | 15.8 Hz, p99 240 ms, max 378; 13.6 Hz, p99 260, max 375 | | main-thread SQLite writes in the burst | 71.4 s; 71.4 s | 0 | | writer: peak uncommitted / max buffered ops / coalesced | — | 10.5 MB / 27 / 1 389; 10.5 MB / 33 / 1 439 | | writer: busy (Worker) / commit wait mean / max | — | 50 s / 191 / 562 ms; 46 s / 211 / 769 ms | | peak RSS | 2 150; 2 178 MB | 2 142; 2 058 MB | The branch's main thread is now saturated by the edits' own work (CSG, normals and SI dispatch, hashes) — no main thread can carry 30 r 8 edits/s on 1.6–4.7 MB regions; main could not carry one region put per edit. ### 5.3 Entity-heavy scene (dice spawned at 4/s into a fresh earthlike world, 240 bodies, 75 s; `bl2`) | | main | branch | |---|---|---| | look-tick rate, interval p99 | 27.1 Hz, 85 ms; 27.1 Hz, 85 ms | **28.4 Hz, 54 ms; 27.9 Hz, 55 ms** | | intervals ≥ 100 ms | 11; 10 | **2; 1** | | max interval (both: the first spawn's prefab build) | 1 012; 1 313 ms | 705; 1 305 ms | | main-thread SQLite writes | 3.35 s; 3.33 s | 0 | | spawn messages held for the commit: mean / max wait | — | 5.8 / 82 ms; 6.1 / 57 ms | | peak RSS | 2 016; 2 081 MB | 1 949; 2 060 MB | ### 5.4 Look tick, pile-huge (2 headless clients, 75 s; `bl2`) | | ticks | p50 | p99 | max | peak RSS | |---|---|---|---|---|---| | main run 1 | 2 095 | 1.28 ms | 14.5 ms | 34.8 ms | 499 MB | | main run 2 | 2 088 | 1.27 ms | 14.2 ms | 24.9 ms | 470 MB | | branch run 1 | 2 088 | 1.18 ms | **8.6 ms** | 14.0 ms | 449 MB | | branch run 2 | 2 096 | 0.99 ms | **8.4 ms** | 28.1 ms | 463 MB | Main spent 2.9 s per run in its in-memory entity flushes; the branch spends 0.3–0.6 s cloning them to the Worker. (The first chain, before the entity rows coalesced, had branch maxima of 38 / 35 ms with p99 8.9 / 13.7: `bl/`.) ### 5.5 Walks (fresh earthlike world, one headless walker along +X, unprofiled) | walk | | main | branch | |---|---|---|---| | 50 m/s, 90 s | rate | 29.11 / 29.01 Hz | 28.99 / 29.13 Hz | | | interval p50 / p99 / max | 33 / 47 / 64; 33 / 48 / 119 ms | 33 / 46 / 88; 33 / 46 / 68 ms | | | ≥ 100 ms | 0 / 1 | 0 / 0 | | | peak RSS | 789 / 805 MB | 828 / 791 MB | | | main-thread SQLite writes | 238 / 265 ms | 0.2 ms | | 5 m/s, 180 s | rate | 29.06 / 29.09 Hz | 29.05 / 28.94 Hz | | | interval p50 / p99 / max | 33 / 47 / 114; 33 / 46 / 91 ms | 33 / 47 / 144; 33 / 48 / 99 ms | | | ≥ 100 ms | 1 / 0 | 1 / 0 | | | peak RSS | 1 230 / 1 257 MB | 1 306 / 1 220 MB | | | main-thread SQLite writes | 350 / 342 ms | 0.2 ms | Unchanged: the walks' writes were already off the main thread except the SI cache puts (2–4 ms of 90–180 s). ### 5.6 Arrival (surface-gi pose 0, headed Chromium on utsuho, 2 runs each, profiled) | | main | branch | |---|---|---| | settle (after the pose) | 7.0 s ×2 | 7.0 s ×2 | | main thread busy (connect → settle, 9.7–9.8 s) | 902 / 910 ms | **867 / 844 ms** | | — SQLite | 154 / 160 ms | **5 / 3 ms** | | — the writer (enqueue, overlays, commits) + `postMessage` to it | — | 31 + 10 / 25 + 10 ms | | look tick p50 / p99 | 0.18 / 2.5; 0.17 / 1.8 ms | 0.18 / 1.8; 0.19 / 1.7 ms | | peak RSS | 664 / 667 MB | **553 / 558 MB** (the fixture's rows are on disk, not in the heap) | The other categories move by ±30 ms between runs (the 1 ms sampler); the net is −35 to −65 ms busy. ## 6. Crash test: kill -9 mid-burst (2 runs each) `bench/write-offload/crash.sh`: a fresh earthlike world in a throwaway directory, one client dragging brushes (soak `edit`), one spawning dice at 4/s; 20 s into the burst every process of the server gets SIGKILL; `crash-check.ts` opens the DB (WAL recovered as a restart would) and compares it with every ack and every `EntitySpawn` the clients received. | | main run 1 / 2 | branch run 1 / 2 | |---|---|---| | edits sent / acked before the kill | 454 / 165; 453 / 160 | 454 / 453; 454 / 453 | | **acked edits missing from the DB** | **0; 0** | **0; 0** | | edited regions holding a committed, not yet acked state | 1; 1 | 0; 0 | | last ack before the kill | 4.5 s; 5.2 s (the server was behind) | 341 ms; 55 ms | | entities a client was sent / missing from the DB | 63 / 0; 60 / 0 | 81 / 0; 81 / 0 | | `integrity_check`, FK violations, entities pointing at a missing structure | ok, 0, 0 | ok, 0, 0 | Neither tree loses anything it acknowledged. Main had ~290 edits per run sent but not acked (queued behind its main thread), lost with the process; the branch had one. ## 7. Owner decisions (none landed) - **D1. Ack before the commit?** Holding the sends for the commit costs the commit wait: lone edits ack +15 ms p50 vs main (138 vs 122 ms; the wait itself 97 ms mean, 155 max — main paid the same put inside the apply, the extra is waiting for a batch already in flight), the soak 191–211 ms mean (max 770), spawns 6 ms mean (max 82). Sending at once instead would ack a lone edit at ≈ 40 ms and lose, on kill -9, the acked edits of at most one batch in flight plus the buffer: ≤ 155 ms of edits at the lone-edit rate, ≤ 770 ms under the soak (≈ 20 edits). Power-cut exposure is unchanged either way (§2.3). Landed: hold (today's guarantee). **Decided in round 2: terrain commands are sent at once (§10).** - **D2. The commit itself.** An edit's commit is 1.6–4.7 MB per region plus the auto-checkpoint's fsync every ~4 MB of WAL: 97 ms for a lone r 12 edit. A larger `wal_autocheckpoint` (checkpoints off the commit path) or `synchronous=OFF` on the cache files would shorten acks; the second weakens the caches' crash safety (they are rebuildable). Measured in round 2 (§12). - **D3. `DB_WRITER_MAX_MB` = 512** (the uncommitted bound before the main thread waits). Peak seen 17 MB. ## 8. Leftovers - **Region-row reads for coords never generated**: 10 k `SELECT`s/s while editing (5.8 s per 3 min, §1), now the largest main-thread SQLite item. `tryGet` could skip the store when `generatedKeys` lacks the key (generatedKeys holds every row: loaded at open, added on every persist). Not done: a read, outside this round's measurements. **Done in round 2 (§11).** - Entity and structure rows are still structured-cloned to the Worker (0.9 ms per pile-huge batch); a flat encoding (one transferred buffer per batch) would remove the clone. - The 1 s stall at the first `die` spawn into a fresh world is the same on both trees (not SQLite). ## 9. Reproduce ```sh bench/write-offload/run-baselines.sh editcost|ack|soak|entity|walkfast|walkslow|looktick|crash|arrival both OUT=…/bl2 bench/write-offload/run-baselines.sh looktick|entity|soak both python3 bench/write-offload/analyze.py