Skip to content

Checkpoint SQLite WALs from a worker thread instead of inside commits (behind an experiment) - #7108

Merged
ymichael merged 7 commits into
mainfrom
bb/offload-sqlite-wal-checkpoints-thr_35rvuxysjd
Nov 9, 2026
Merged

ymichael merged 7 commits into
mainfrom
bb/offload-sqlite-wal-checkpoints-thr_35rvuxysjd

Conversation

@ymichael

@ymichael ymichael commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

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 explicit wal_checkpoint(PASSIVE) calls on the main thread around every 256-page chunk. Plugin data.db handles 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 walCheckpointWorker experiment 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) wraps startWalCheckpointer with the same interface and follows config-changed live. 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 restores wal_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 of runIncrementalVacuum into the chunk loop; with the experiment on, those calls wait for a worker pass instead). Test servers still use startWalCheckpointer directly. Documented in docs/configuration.md and bb guide customization.

  • packages/db/src/wal-checkpointer.ts (new): startWalCheckpointer({ logger }) starts one worker_threads worker. It opens its own better-sqlite3 connection (the same addon file as the main thread, so one SQLite copy per process) for each attached database and runs wal_checkpoint(PASSIVE):

    • every 100 ms;
    • immediately again while the WAL is at 4,096 frames or more and still growing or not fully backfilled.

    attach(database) sets wal_autocheckpoint=0 on 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 INTO copy) 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.

    • FULL/RESTART from the worker were rejected. They hold the writer lock, and a main-thread deferred transaction that reads and then writes gets SQLITE_BUSY immediately 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/detach promises 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 after initDb and stops the checkpointer last in shutdown, after plugins stop and the HTTP server closes. walCheckpointer is now an AppDeps field.

  • Incremental-vacuum sweep: runIncrementalVacuum no longer checkpoints. runChunkedIncrementalVacuum awaits walCheckpointer.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 plugin data.db. The runtime detaches after closing the handle on dispose and on candidate discard, and awaits the detach (discardCandidate is now async) before snapshot restore or uninstall can touch the files. This matters most on Windows and for restorePluginStateSnapshot, which deletes -wal/-shm and overwrites data.db. PluginServiceDeps.walCheckpointer is 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_VERSION bump: 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.ts checks that bb.db keeps wal_autocheckpoint=1000 while 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 on pnpm start:worktree: toggling with bb settings experiment walCheckpointWorker took 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 in sqlite3WalCheckpoint went 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 sqlite3WalCheckpoint went 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:
    • Back-to-back writes from the main connection with no inline checkpoints still restart the WAL (header checkpoint sequence advances). With the starvation backstop disabled: 0 restarts.
    • A reader that pins the WAL while it grows past twice the starvation threshold logs no "Sustained writes…" line, and the WAL restarts once the reader commits. Without the progress guard: 65–158 lines.
    • stop() backfills the remaining WAL and restores wal_autocheckpoint=1000.
    • After detach() resolves, the worker has released the files (the last close deletes -wal).
    • A database the worker cannot open stays on commit checkpoints, with a warning.
  • apps/server/test/services/database-maintenance-sweep.test.ts: the vacuum sweep restarts the WAL between chunks without main-thread checkpoints (without the checkpoint() wait: 0 restarts).
  • apps/server/test/services/plugins/plugin-settings-storage.test.ts: a plugin's data.db runs with wal_autocheckpoint=0, and its WAL file is gone once the plugin service stops (without the runtime's detach: the file remains).
  • Locally: turbo run typecheck --filter=@bb/db --filter=@bb/server, plus the files above and periodic-sweeps, plugin-update and plugin-state-snapshot tests. CI runs the full suites.

Dev server over a scrubbed heavy.db clone (3.9 GB, 4,426 threads):

  • Setup:
    • origin/main fa30b0a7dc vs this branch, the same production apps/server bundle built from each.
    • A fresh cp -c clone of heavy.db per run; env -i (no account-pool or BB_* variables); 60–90 s warm-up.
    • 180 s of load: list/get/timeline/events reads about every 50 ms, a rename → thread:changed push probe every second, and 4 writers renaming archived threads back to back (≈400–500 writes/s through the main connection).
  • Runs alternate main and branch. The machine was shared with another thread's 70-minute benchmark (load average up to 30), so neighbouring pairs are the fair comparison.

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).

run writes/s list p50 / p99 get p50 / p99 timeline p50 / p99 events p50 / p99 push p50 / p99 write p50 / p99 event-loop p99 (worst 5 s) WAL frames p50 / max WAL restarts main-thread samples in sqlite3WalCheckpoint worker samples in it
main1 393 6.5 / 87.1 2.2 / 69 7.6 / 149.5 7.5 / 101.6 4.5 / 101.5 2.7 / 44 86.6 529 / 1415 1740 887 / 15800 0
branch1 502 6 / 15.3 1.8 / 6.3 5.8 / 39.2 6.8 / 14 3.3 / 13.6 2.5 / 6.1 31.0 2369 / 6317 558 0 / 15490 450
main2 468 6.2 / 33.7 2 / 46.2 6.6 / 70.1 7 / 62.1 3.9 / 139.1 2.7 / 16.1 51.6 538 / 1296 2053 662 / 15510 0
branch2 450 6.2 / 100.3 1.9 / 67.2 6.6 / 108 7.1 / 81.2 4 / 66 2.7 / 22.5 65.4 1892 / 6025 593 0 / 15553 488
branch3 432 7.3 / 122.4 2.1 / 67.4 7.5 / 189.2 7.9 / 145.1 4.5 / 220.4 2.9 / 27.9 95.3 2006 / 5983 564 0 / 16134 618
main3 477 6 / 43.5 1.9 / 20.6 6.2 / 80.4 6.8 / 42.5 3.3 / 73.8 2.6 / 17 36.9 507 / 1248 2076 572 / 15460 0
main4 496 5.5 / 23.2 1.8 / 11 5.9 / 59.5 6.6 / 13.9 3.5 / 24 2.5 / 9.1 35.3 523 / 1263 2173 543 / 15594 0
branch4 508 5.4 / 16.3 1.8 / 8.8 5.7 / 50.9 6.4 / 15.1 3.1 / 13.8 2.4 / 5.6 36.4 2166 / 7115 615 0 / 15585 406
branch5 507 5.6 / 16.5 1.8 / 4.6 5.6 / 40.4 6.5 / 11.9 3.1 / 21.3 2.4 / 5.8 42.1 2217 / 7554 597 0 / 15556 383
main5 491 5.9 / 19.1 1.9 / 8.6 6.1 / 48.9 6.8 / 16.4 3.2 / 25.1 2.5 / 8.7 31.8 540 / 1279 2124 635 / 15444 0

Median across runs (p99, ms):

list get timeline events push write event-loop p99
origin/main (5 runs) 33.7 20.6 70.1 42.5 73.8 16.1 36.9
branch (5 runs) 16.5 8.8 50.9 15.1 21.3 6.1 42.1

Reading it:

  • No checkpoint on the main thread.
    • In each run's 20 s sample (1 ms interval) of the server process, origin/main's main thread spends 543–887 samples (3.5–5.7% of its time) inside sqlite3WalCheckpoint.
    • The branch has 0 main-thread samples there in all five runs; its 383–618 checkpoint samples are all on the worker thread.
    • The starvation backstop never fired: no "Sustained writes outpaced…" lines, and no worker warnings in any branch log.
  • The WAL stays bounded under sustained writes (400–500 renames/s for 180 s):
    • p50 1.9–2.4k frames, peak 6.0–7.6k frames (≤ 31 MB WAL file), restarting about 600 times per run.
    • origin/main peaks at about 1.4k frames, because each commit that crosses 1,000 frames checkpoints inline. The branch trades a somewhat larger WAL for no commit-time checkpoints. It is capped by the 4,096-frame catch-up and the 16,384-frame backstop.
  • Request and push p99 don't get worse.
    • The median p99 across the five runs improves for every request kind: list 33.7 → 16.5 ms, get 20.6 → 8.8, timeline 70.1 → 50.9, events 42.5 → 15.1, push 73.8 → 21.3, write 16.1 → 6.1.
    • p50s are unchanged or slightly lower.
    • On the quiet machine (pairs 4–5) the branch is lower on every p99 except events in pair 4 (13.9 → 15.1 ms).
    • Branch2 and branch3 are worse than their neighbours; they ran during the other benchmark's heaviest windows, and so did main1's high numbers.
  • Event-loop p99 (worst 5 s window) doesn't improve at the median (36.9 → 42.1 ms; 31–95 ms on the branch, 32–87 ms on main). Every run, on both builds, has the same ~270 ms worst stall: a periodic slow events query in the sweep, unrelated to checkpoints.
  • Idle cost. With nothing writing, the worker's ten no-op PASSIVE passes per second cost about 40 ms of CPU per 30 s (≈ 0.13% of one core), measured on a subset.db clone.

Raw per-run data (load summaries, WAL samples, event-loop log, sample output, server logs) is in the thread's storage under perf/runs/.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/offload-sqlite-wal-checkpoints-thr_35rvuxysjd branch from 6fc51bb to 956426d Compare November 7, 2026 00:43
ymichael and others added 5 commits November 7, 2026 12:17
…start test condition-based

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 and others added 2 commits November 9, 2026 10:28
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]>
@ymichael ymichael changed the title Checkpoint SQLite WALs from a worker thread instead of inside commits Checkpoint SQLite WALs from a worker thread instead of inside commits (behind an experiment) Nov 9, 2026
@ymichael
ymichael merged commit be3ca2c into main Nov 9, 2026
52 checks passed
@ymichael
ymichael deleted the bb/offload-sqlite-wal-checkpoints-thr_35rvuxysjd branch November 9, 2026 18:41
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant