Repository navigation
Checkpoint SQLite WALs from a worker thread instead of inside commits (behind an experiment) - #7108
Merged
Merged
Conversation
ymichael
force-pushed
the
bb/offload-sqlite-wal-checkpoints-thr_35rvuxysjd
branch
from
November 7, 2026 00:43
6fc51bb to
956426d
Compare
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…start test condition-based Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A reader that holds an old snapshot (for example a VACUUM INTO copy) stops PASSIVE checkpoints from backfilling while writes keep growing the WAL. The worker treated that as write starvation: it paused, asked the main thread to checkpoint the tail, resumed, and repeated on every write, logging one "Sustained writes" line each time (about 2,000 lines per 15 s pin on a bb.db snapshot). The main-thread checkpoint could not help either, since the same reader blocks it. The worker now only reports starvation, and only re-runs immediately, when the previous pass made checkpoint progress or the WAL restarted. A pinned WAL falls back to the normal interval until the reader finishes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eader test A fixed 1.5 s write window depends on runner speed, and stopping just past the threshold let the unpatched worker pass before its starvation messages landed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/offload-sqlite-wal-checkpoints-thr_35rvuxysjd
branch
from
November 7, 2026 20:19
956426d to
394c71f
Compare
…-checkpoints-thr_35rvuxysjd
The worker now starts only while the walCheckpointWorker experiment is on (default off, also off for early adopters). startGatedWalCheckpointer wraps startWalCheckpointer with the same interface, follows config-changed live, and re-attaches bb.db and open plugin databases when turned on. While it is off, commits checkpoint as before and the incremental vacuum runs a PASSIVE checkpoint before and after each chunk inline, as on main. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closed
3 tasks done
ymichael
added a commit
that referenced
this pull request
Dec 1, 2026
…8430) ## Human comments ## What was wrong The WAL checkpoint worker (#7108) ran `wal_checkpoint(PASSIVE)` every 100 ms on `bb.db` and every plugin `data.db`. Any commit in that window had its frames copied into the database file straight away, with one fsync of the WAL and one of the database file. Under `synchronous=NORMAL` commits never fsync on their own, so this turned each small commit (heartbeats, plugin kv rows, event appends) into two fsyncs. It also rewrote hot pages into the database file again and again, where SQLite's default 1,000-frame autocheckpoint writes each page once per batch. On slow-fsync Linux disks this saturated the device and stalled the server. On NVMe it showed up as sustained small 4 KB writes (alpine-vortex: about 150 GB/day). The issue's second claim, that plugin `data.db` connections run at `synchronous=FULL`, does not hold. better-sqlite3 is built with `SQLITE_DEFAULT_WAL_SYNCHRONOUS=1`, and plugin connections read back `synchronous=1` once in WAL mode, so that one-liner would change nothing. The main-thread stalls in the issue's third point are a symptom of the fsync storm, so this PR does not coalesce writes. ## What changed - `packages/db/src/wal-checkpointer.ts`: every 100 ms the worker reads `mxFrame` and `nBackfill` from the WAL-index (`-shm`) header with a plain `pread` of the first 100 bytes, which stays clear of the lock bytes Windows enforces at offset 120 and up. It runs `wal_checkpoint(PASSIVE)` only once 1,000 frames are not yet backfilled, the point where SQLite's default autocheckpoint would have run inside a commit. If the header cannot be read or has an unexpected version, the worker checkpoints as before. Explicit `checkpoint()` requests (the vacuum sweep), the 4,096-frame catch-up, the starvation backstop and `stop()` are unchanged. - `docs/configuration.md`: describes the new trigger. - Durability matches bb before #7108 and SQLite's `synchronous=NORMAL` default: up to 1,000 frames of recent commits can sit un-fsynced, so a power loss can lose them but cannot corrupt the database. ## How you verified - New test `leaves a WAL alone until it holds a thousand frames the database lacks` in `packages/db/test/wal-checkpointer.test.ts`. It fails on main (the WAL restarts after one small commit) and passes on this branch. All 6 checkpointer tests pass. - `turbo run test --filter=@bb/server` on database-maintenance-sweep, plugin-settings-storage, periodic-sweeps, plugin-state-snapshot and plugin-update: 90 passed. `turbo run typecheck --filter=@bb/db`: clean. - **Live production server (macOS, 60 s, sampling the `-shm` headers):** 626 commits caused 299 backfills (about 600 fsyncs/min). On `bb.db` about 6,000 WAL frames written led to 6,714 frames backfilled, so almost every write was copied straight into the database file. The process wrote about 2.1 MB/s. - **Linux (`node:22-bookworm`, strace), real checkpointer module, 34 databases, about 16 small commits/s, 60 s, two runs each:** | | fsyncs (setup excluded) | block `write_bytes` | slow checkpoint logs | |---|---|---|---| | main | about 2,200–2,450 | 123–132 MB | 0–29 | | this branch | about 30 | 15 MB | 0–1 | | no worker (commit autocheckpoint) | 0 | 15 MB | 0 | - **`pnpm start:worktree` on this branch, 90 s:** `bb.db` took 4 commits and 16 frames with 0 backfills, and no "Slow WAL checkpoint" lines. Fixes #8345 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
scowalt
pushed a commit
to scowalt/bb
that referenced
this pull request
Dec 1, 2026
…et-bb#8430) ## Human comments ## What was wrong The WAL checkpoint worker (get-bb#7108) ran `wal_checkpoint(PASSIVE)` every 100 ms on `bb.db` and every plugin `data.db`. Any commit in that window had its frames copied into the database file straight away, with one fsync of the WAL and one of the database file. Under `synchronous=NORMAL` commits never fsync on their own, so this turned each small commit (heartbeats, plugin kv rows, event appends) into two fsyncs. It also rewrote hot pages into the database file again and again, where SQLite's default 1,000-frame autocheckpoint writes each page once per batch. On slow-fsync Linux disks this saturated the device and stalled the server. On NVMe it showed up as sustained small 4 KB writes (alpine-vortex: about 150 GB/day). The issue's second claim, that plugin `data.db` connections run at `synchronous=FULL`, does not hold. better-sqlite3 is built with `SQLITE_DEFAULT_WAL_SYNCHRONOUS=1`, and plugin connections read back `synchronous=1` once in WAL mode, so that one-liner would change nothing. The main-thread stalls in the issue's third point are a symptom of the fsync storm, so this PR does not coalesce writes. ## What changed - `packages/db/src/wal-checkpointer.ts`: every 100 ms the worker reads `mxFrame` and `nBackfill` from the WAL-index (`-shm`) header with a plain `pread` of the first 100 bytes, which stays clear of the lock bytes Windows enforces at offset 120 and up. It runs `wal_checkpoint(PASSIVE)` only once 1,000 frames are not yet backfilled, the point where SQLite's default autocheckpoint would have run inside a commit. If the header cannot be read or has an unexpected version, the worker checkpoints as before. Explicit `checkpoint()` requests (the vacuum sweep), the 4,096-frame catch-up, the starvation backstop and `stop()` are unchanged. - `docs/configuration.md`: describes the new trigger. - Durability matches bb before get-bb#7108 and SQLite's `synchronous=NORMAL` default: up to 1,000 frames of recent commits can sit un-fsynced, so a power loss can lose them but cannot corrupt the database. ## How you verified - New test `leaves a WAL alone until it holds a thousand frames the database lacks` in `packages/db/test/wal-checkpointer.test.ts`. It fails on main (the WAL restarts after one small commit) and passes on this branch. All 6 checkpointer tests pass. - `turbo run test --filter=@bb/server` on database-maintenance-sweep, plugin-settings-storage, periodic-sweeps, plugin-state-snapshot and plugin-update: 90 passed. `turbo run typecheck --filter=@bb/db`: clean. - **Live production server (macOS, 60 s, sampling the `-shm` headers):** 626 commits caused 299 backfills (about 600 fsyncs/min). On `bb.db` about 6,000 WAL frames written led to 6,714 frames backfilled, so almost every write was copied straight into the database file. The process wrote about 2.1 MB/s. - **Linux (`node:22-bookworm`, strace), real checkpointer module, 34 databases, about 16 small commits/s, 60 s, two runs each:** | | fsyncs (setup excluded) | block `write_bytes` | slow checkpoint logs | |---|---|---|---| | main | about 2,200–2,450 | 123–132 MB | 0–29 | | this branch | about 30 | 15 MB | 0–1 | | no worker (commit autocheckpoint) | 0 | 15 MB | 0 | - **`pnpm start:worktree` on this branch, 90 s:** `bb.db` took 4 commits and 16 frames with 0 backfills, and no "Slow WAL checkpoint" lines. Fixes get-bb#8345 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
bb's main SQLite connection kept SQLite's default
wal_autocheckpoint=1000, so whichever commit pushed the WAL past 1,000 frames ran the checkpoint inside that commit on the event loop. That meant copying frames into the database file plus two fsyncs. On a large database this stalls writes for seconds: the cold-tier investigation measured checkpoint p999 at 256 ms and a max of 2.75 s for 250 frames on an 8.4 GB file (PLAN.md §4). The hourly incremental-vacuum sweep also ran explicitwal_checkpoint(PASSIVE)calls on the main thread around every 256-page chunk. Plugindata.dbhandles have the same problem at a smaller scale. On a synthetic 200 MB plugin-sized database, each inline autocheckpoint costs the commit 18–22 ms (commit p999 18–20 ms with autocheckpoint on, 2.2 ms with it off).What changed
Behind an experiment. Everything below runs only while the
walCheckpointWorkerexperiment is on (Settings → Experiments → "Background database checkpoints",bb settings experiment walCheckpointWorker true). It is off by default and also off for early adopters.startGatedWalCheckpointer(apps/server/src/services/system/wal-checkpoint-experiment.ts) wrapsstartWalCheckpointerwith the same interface and followsconfig-changedlive. Turning it on starts the worker and attaches bb.db and the open plugin databases; turning it off runs a final checkpoint, stops the worker and restoreswal_autocheckpoint=1000. While it is off, behaviour matches main: commits checkpoint inline, and the incremental vacuum runs a PASSIVE checkpoint before and after each chunk (moved out ofrunIncrementalVacuuminto the chunk loop; with the experiment on, those calls wait for a worker pass instead). Test servers still usestartWalCheckpointerdirectly. Documented indocs/configuration.mdandbb guide customization.packages/db/src/wal-checkpointer.ts(new):startWalCheckpointer({ logger })starts oneworker_threadsworker. It opens its ownbetter-sqlite3connection (the same addon file as the main thread, so one SQLite copy per process) for each attached database and runswal_checkpoint(PASSIVE):attach(database)setswal_autocheckpoint=0on the caller's connection once the worker has opened the file. Until then, and whenever the worker isn't running, commits keep checkpointing as before.checkpoint(database)waits for one worker pass.detach(database)closes the worker's connection and restores the old autocheckpoint value.stop()runs a final checkpoint and exits the worker.Starvation backstop. PASSIVE never takes the writer lock. But with back-to-back writes, SQLite only restarts the WAL when a write begins while the log is fully backfilled, and that may never happen while the worker is mid-pass. If the WAL keeps growing past 16,384 frames (64 MB at 4 KB pages) across two worker passes, the worker pauses and asks the main thread to checkpoint the remaining tail between tasks. The worker has already backfilled almost everything, so the tail is small: the unit test logged 38 frames in 0.2 ms. The next write then restarts the log. This is the one place a checkpoint still runs on the main thread, it only happens under sustained write starvation, and it is logged ("Sustained writes outpaced the WAL checkpoint worker…"). It never fired in the server benchmarks below. A reader that pins the WAL (for example a
VACUUM INTOcopy) also stops the WAL from backfilling, but the main thread can't get past that reader either. So the worker only reports starvation, or re-runs a pass immediately, when the previous pass made checkpoint progress or the WAL restarted. While a reader pins the WAL, it simply retries every 100 ms until the reader finishes. Before this guard, an 8.6 GB production-snapshot clone logged about 2,000 "Sustained writes…" lines per 15 s reader.SQLITE_BUSYimmediately when another connection holds that lock; SQLite skips the busy handler for a read-to-write upgrade.Worker crash. If the worker exits unexpectedly, every attached connection returns to commit checkpoints right away, the pending
checkpoint/detachpromises resolve, a warning is logged, and a worker that had started successfully is restarted after 10 s and re-attaches everything. A worker that cannot start (or a database it cannot open) leaves those connections on commit checkpoints and logs a warning, with no restart loop. Invalid worker messages terminate the worker instead of throwing on the main thread.Server (
start-server.ts): attaches bb.db afterinitDband stops the checkpointer last in shutdown, after plugins stop and the HTTP server closes.walCheckpointeris now anAppDepsfield.Incremental-vacuum sweep:
runIncrementalVacuumno longer checkpoints.runChunkedIncrementalVacuumawaitswalCheckpointer.checkpoint(client)between chunks, so the WAL still restarts every chunk, but the copy and fsync happen off the event loop. This covers bb.db and the plugin databases that the hourly sweep now also vacuums (Prune exited terminals, drop dead pruning cursors, and vacuum plugin databases #7106).Plugin databases:
storage.database()attaches each plugindata.db. The runtime detaches after closing the handle on dispose and on candidate discard, and awaits the detach (discardCandidateis now async) before snapshot restore or uninstall can touch the files. This matters most on Windows and forrestorePluginStateSnapshot, which deletes-wal/-shmand overwritesdata.db.PluginServiceDeps.walCheckpointeris optional: isolated plugin tests omit it, and those plugin databases keep commit checkpoints.Not changed: plugin-update snapshots still
TRUNCATE-checkpoint the plugin file once before copying it.No
HOST_DAEMON_PROTOCOL_VERSIONbump: the daemon never opens bb.db. No CLI, SDK or setting surface.How you verified
Experiment gate:
apps/server/test/services/wal-checkpoint-experiment.test.tschecks that bb.db keepswal_autocheckpoint=1000while the experiment is off, goes to 0 once it is turned on, and returns to 1000 when it is turned off (fails if the gate is bypassed). Live onpnpm start:worktree: toggling withbb settings experiment walCheckpointWorkertook the server from 13 to 14 threads and back. Rerun on a 10 GB copy of a production bb.db (≈410 commits/s for 60 s, two runs each): with the worker, main-thread samples insqlite3WalCheckpointwent from 695/620 to 0, commit p99 from 12.7/11.5 ms to 1.0/0.8 ms, and the slowest commit from 148/64 ms to 15/35 ms.Independent check on an 8.6 GB production-snapshot clone (perf audit thread, 18 s runs): main-thread samples in
sqlite3WalCheckpointwent from 1,656–2,526 per run (about 80% of them in fsync) to 0. Commits that checkpointed inline went from 110–124 per run to 0. Total transaction time fell from 7,688 to 3,510 ms, and transaction p99 from 39.6 to 8.1 ms.Tests (each fails with its mechanism removed, checked by mutation):
packages/db/test/wal-checkpointer.test.ts:stop()backfills the remaining WAL and restoreswal_autocheckpoint=1000.detach()resolves, the worker has released the files (the last close deletes-wal).apps/server/test/services/database-maintenance-sweep.test.ts: the vacuum sweep restarts the WAL between chunks without main-thread checkpoints (without thecheckpoint()wait: 0 restarts).apps/server/test/services/plugins/plugin-settings-storage.test.ts: a plugin'sdata.dbruns withwal_autocheckpoint=0, and its WAL file is gone once the plugin service stops (without the runtime's detach: the file remains).turbo run typecheck --filter=@bb/db --filter=@bb/server, plus the files above andperiodic-sweeps,plugin-updateandplugin-state-snapshottests. CI runs the full suites.Dev server over a scrubbed heavy.db clone (3.9 GB, 4,426 threads):
fa30b0a7dcvs this branch, the same productionapps/serverbundle built from each.cp -cclone of heavy.db per run;env -i(no account-pool or BB_* variables); 60–90 s warm-up.thread:changedpush probe every second, and 4 writers renaming archived threads back to back (≈400–500 writes/s through the main connection).Ten runs, in this order: main1, branch1, main2, branch2, branch3, main3, main4, branch4, branch5, main5. The other benchmark was loading the machine during pairs 1–3 (load average up to 30). Pairs 4–5 ran on a quiet machine (load average about 5).
sqlite3WalCheckpointMedian across runs (p99, ms):
Reading it:
sample(1 ms interval) of the server process, origin/main's main thread spends 543–887 samples (3.5–5.7% of its time) insidesqlite3WalCheckpoint.eventsquery in the sweep, unrelated to checkpoints.Raw per-run data (load summaries, WAL samples, event-loop log,
sampleoutput, server logs) is in the thread's storage underperf/runs/.🤖 Generated with Claude Code