Repository navigation
Description
Summary
On a Linux VPS with typical virtualized storage (fsync median 6.5 ms, vs ~0.1 ms on Apple Silicon), bb server experiences hundreds of 0.5–5.4 s event loop stalls and thousands of slow WAL checkpoints per day even while overall host CPU is 15–20% (steal = 0%) and 26/30 GiB RAM is free.
Three low-effort SQLite/WAL behaviors — all still present on main at b0ddaad731565d7e4de68d824120d802fc78f7d5 — amplify slow fsync into continuous main-thread blocking:
walCheckpointWorkerpollsPRAGMA wal_checkpoint(PASSIVE)unconditionally every 100 ms forbb.dband every plugindata.db(34 databases on this instance ≈ 340 checkpoints/sec), with 86.5% of slow checkpoints firing whenwalFrames <= 16(and 227 whenwalFrames == 0).- Plugin databases opened in
plugin-api.tsomitPRAGMA synchronous = NORMAL(unlikebb.dband the checkpoint worker), leaving every plugin SQLite write at SQLite's defaultsynchronous = FULL— forcing a synchronousfsync()on the main event loop on every plugin commit. - Synchronous single-row/small DB writes on the main event loop (
heartbeatSession,plugin_kv,plugin_schedules,INSERT INTO events) contend with that I/O/WAL storm and block the main thread for 100–2,500 ms while spending only 4–35% of wall time on CPU.
Versions and environment
- bb version:
0.50.1(bb-appinstalled via npm; code paths also verified againstmainatb0ddaad731565d7e4de68d824120d802fc78f7d5) - Node:
v22.22.1 - OS / Hardware (remote server): Linux KVM VPS (8 vCPU,
Intel Xeon Silver 4216 @ 2.10 GHz, 30 GiB RAM / 26 GiB free, 429 GB disk free,CPU steal = 0%) - Setup: Remote server mode on Linux VPS with
walCheckpointWorkerenabled, 1 remote macOS host-daemon connected, 44 active plugins (33 plugindata.dbfiles +bb.db= 34 SQLite DBs),bb.dbsize964 MB(events: 230k rows / 735 MB). - Comparison baseline: Same workload previously ran smoothly on macOS (Apple M4), where
4 KB write + fsyncis ~65× faster and single-threadJSON.parseis ~3.7× faster.
Steps to reproduce
The underlying disk/WAL amplification is reproducible on any Linux VPS with virtualized storage (fsync ~5–15 ms) running bb server with walCheckpointWorker enabled and multiple plugins that call bb.storage.database():
- Measure baseline
4 KB write + fsynclatency on the host filesystem (e.g., 15 sequential 4 KB writes +os.fsync()):- On this VPS:
min=2.0ms median=6.5ms p90=16.9ms max=18.8ms avg=8.9ms. - On Apple Silicon macOS (reference):
median=0.11ms.
- On this VPS:
- Enable
walCheckpointWorkerand runbbserver withbb.db+ ~25–35 plugins that openplugins/<id>/data.dbviabb.storage.database(). - Connect a remote host-daemon (sending periodic heartbeats) and run 2–3 concurrent agent threads while watching
logs/server.*.logfor"Slow WAL checkpoint","Slow DB query", and"Event loop stalled". - Note:
wal_checkpoint(PASSIVE)on a 1-frame WAL takes0.11 msmedian on macOS, so this behavior stays mostly invisible on local Apple Silicon dev machines and surfaces sharply on virtualized VPS storage (especially when hostiowaitrises from0.05%to0.3–0.6%).
Expected vs actual
Observed in a single day's server log (server.5.log):
Slow WAL checkpoint(>= 100 ms):3,762occurrences- Duration:
min=100.0 ms,median=146.0 ms,p90=313.2 ms,max=2,316.9 ms,avg=187.2 ms. - Distribution by WAL size:
3,256 / 3,762(86.5%) hadwalFrames <= 16, and227hadwalFrames == 0. - Split across DBs:
2,078onbb.db+1,684across plugindata.dbfiles (account-pool: 141,server-watch: 129,burn: 117,agent-calendar: 112,bb--storage-retention: 112,automations: 105,agentation: 86,bb-recap: 82,side-chat: 79, etc.).
- Duration:
Event loop stalled(>= 500 ms):1,220occurrences (304 >= 1 s,max = 5,447.7 ms)- Top stall causes attributed in logs:
254—ws:daemon heartbeat > db:transaction deferred: update "host_daemon_sessions"...159—sweep:thread-event-pruning (until first await)94—db:transaction immediate: INSERT INTO events ...81—sweep:environment-provider-lifecycle (until first await)56—db:all select "threads"...38 + 23—timeline-buildon large threads28—db:run insert into "plugin_kv"...
- Top stall causes attributed in logs:
Slow DB query(>= 100 ms) — wall time vs CPU time proves I/O & lock waiting, not just CPU:1,577slow transactions total (max = 2,516.7 ms);414spent< 35%of wall time on CPU.run insert into "plugin_kv":n=57,avg_wall=178.0 ms,avg_cpu=20.3 ms(11.4%CPU),max=668.4 ms.run update "plugin_schedules":n=15,avg_wall=186.1 ms,avg_cpu=8.0 ms(4.3%CPU),max=763.9 ms.
Trimmed verbatim log samples (paths redacted):
{"level":30,"component":"server","database":"<dataDir>/bb.db","walFrames":12,"checkpointedFrames":12,"durationMs":119.75,"msg":"Slow WAL checkpoint"}
{"level":30,"component":"server","bindingArgumentCount":1,"durationMs":118.4,"cpuDurationMs":118.6,"operation":"transaction","sql":"TRANSACTION IMMEDIATE","thresholdMs":100,"msg":"Slow DB query"}Expected:
- Idle or nearly-empty WAL files (
walFrames == 0or a handful of frames) should not trigger 100 ms polling checkpoints across 30+ SQLite databases. - Plugin
data.dbconnections should usePRAGMA synchronous = NORMALconsistently withbb.dbandwalCheckpointWorker, rather than issuing synchronousFULLfsync()calls on the main event loop. - Routine single-row writes (like daemon heartbeats /
plugin_kv/plugin_schedules/ streaming event appends) should not stall the main thread for hundreds of milliseconds due to background checkpoint I/O contention.
Evidence
1. Code permalinks on main (b0ddaad731565d7e4de68d824120d802fc78f7d5)
-
Unconditional 100 ms
wal_checkpoint(PASSIVE)loop for every attached database:packages/db/src/wal-checkpointer.ts#L7-L10setsWAL_CHECKPOINT_INTERVAL_MS = 100.packages/db/src/wal-checkpointer.ts#L30-L74unconditionally callstarget.database.pragma("wal_checkpoint(PASSIVE)")and reschedulessetTimeout(() => run(id, target), catchUp ? 0 : workerData.intervalMs)every 100 ms for every attached DB — regardless of whether any writes happened or how many WAL frames exist, and with no jitter across the 30+ attached databases.
-
Plugin
data.dbconnections omitPRAGMA synchronous = NORMAL:- Main
bb.dbsetssynchronous = NORMALatpackages/db/src/connection.ts#L426-L432, and the checkpoint worker setssynchronous = NORMALon its own connections atpackages/db/src/wal-checkpointer.ts#L80-L81. - However,
apps/server/src/services/plugins/plugin-api.ts#L775-L784opens each plugin'sdata.dbwith onlyauto_vacuum = INCREMENTAL,journal_mode = WAL, andbusy_timeout = 5000— omittingsynchronous = NORMAL. In WAL mode, SQLite defaults tosynchronous = FULL, which forces anfsync()on every commit made by plugin code on the main thread.
- Main
-
Synchronous daemon heartbeat transaction on the main thread:
apps/server/src/ws/daemon-protocol.ts#L310-L334andpackages/db/src/data/sessions.ts#L192-L214runheartbeatSessionsynchronously insiderunEventLoopWorkSync("ws:daemon heartbeat", ...)(updatinghost_daemon_sessions+hosts.last_seen_at). Although gated byLEASE_RENEWAL_INTERVAL_MS, whenever it collides with WAL checkpoint I/O on a slow disk it stalls the event loop (254 stalls in 24h) and cascades into host-daemonheartbeat-ack-timeoutdisconnects.
2. Host benchmark measurements (how numbers were measured)
Same scripts run on both the Linux VPS and the macOS Apple M4 machine:
| Metric | Linux VPS (Xeon Silver 4216, KVM) |
macOS (Apple M4) | Ratio |
|---|---|---|---|
4 KB write + fsync (15× sequential, median) |
6.5 ms (p90 16.9 ms, max 18.8 ms) |
0.10 ms |
~65× slower |
SQLite 1-frame wal_checkpoint(PASSIVE) (15×, median) |
~6–19 ms idle / 146 ms median under load |
0.11 ms |
60–1,300× slower |
Node JSON.parse (200× ~500-item payload) |
151.8 ms |
40.8 ms |
3.7× slower |
Node single-thread int loop (200M iters) |
3,287.9 ms |
1,828.6 ms |
1.8× slower |
3. Concrete low-effort fixes (no full multi-threaded DB rewrite needed)
- Add
database.pragma("synchronous = NORMAL");inapps/server/src/services/plugins/plugin-api.ts#L778-L780to matchbb.dbandwalCheckpointWorker. - Stop polling
wal_checkpoint(PASSIVE)every 100 ms on idle/tiny WALs inwal-checkpointer.ts:- Check the
-walfile size viastat()(or a dirty/write notification from the main thread) before invokingPRAGMA wal_checkpoint(PASSIVE), or only checkpoint when WAL exceeds a frame/byte threshold (e.g.,>= 1,000frames /4 MB) or after an idle backoff interval (e.g.,5–30 swith per-DB jitter, rather than a flat100 msacross all 30+ DBs). - Keeping
WAL_CHECKPOINT_INTERVAL_MSadaptive (fast catch-up when WAL is large, slow/idle whenwalFrames == 0or unchanged) eliminates thousands of redundantfsynccalls on VPS disks and also cuts disk write amplification on laptops.
- Check the
- Batch/coalesce small frequent writes on the main thread (e.g.,
INSERT INTO eventsbursts during active agent turns, and deferring/coalescinghosts.last_seen_at/host_daemon_sessionslease writes off the synchronous WS heartbeat critical path).
What you ruled out
- Not a duplicate of bb.db unbounded growth (23.3 GB live data): unpruned event types, retained first deltas, archived history, and no wal_checkpoint(TRUNCATE) #8325 (
bb.dbunbounded growth / retention): even after controlling DB growth, 1,684 slow WAL checkpoints came from tiny 0.02–8 MB plugindata.dbfiles, and 86.5% of all slow checkpoints hadwalFrames <= 16. - Not a duplicate of Thread timeline can materialize a whole diagnostic-heavy turn before enforcing its byte cap #8302 (timeline byte cap) or bb Connect tunnel deflates response bodies that the server already compressed #8222 (double compression in Connect tunnel) or bb Connect drops every 20–30s; persistent HTTPS connections to the account endpoint also stall #7500 (Connect tunnel disconnects): the stalls and slow WAL checkpoints happen directly at the SQLite/disk layer, and
bb.dbstalls were in fact triggering downstream Connect/host-daemon timeouts. - Related to closed PR Run conversation outline and timeline reads in reader worker threads #7766 (offloading SQLite reads to worker threads): unlike Run conversation outline and timeline reads in reader worker threads #7766 (~7k LOC architectural change), the fixes above (
synchronous = NORMALfor plugin DBs + threshold/backoff WAL checkpointing + write coalescing) are small, localized changes that immediately make self-hosted VPS deployments much more resilient without rewriting the DB layer. - Ruled out host CPU starvation / OOM:
CPU steal = 0%, total VPS CPU averaged15–20%across 8 vCPUs, and26 / 30 GiBRAM remained free throughout. - Separate plugin bugs were isolated: We also identified and separately fixed plugin-level issues (unbounded concurrency in
burnand missing-root/offline retries inworkbench-explorer), but theSlow WAL checkpointstorm (3,762/day across 34 DBs) and I/O-bound main-thread DB writes (4–11%CPU ratio) are inbbserver core and verified present onmainatb0ddaad731565d7e4de68d824120d802fc78f7d5.
Suggested priority and effort
Medium-High for self-hosted Linux VPS users (no good workaround other than moving to local-NVMe hardware or disabling most plugins); effort is Low for items 1 and 2 (plugin-api.ts one-liner + adaptive/threshold backoff in wal-checkpointer.ts).
Checks
- I reproduced this on the latest release (
0.50.1) and verified the exact code paths are still unchanged onmain(b0ddaad731565d7e4de68d824120d802fc78f7d5). - I searched open and closed issues for the same problem.
- If an agent wrote this, the body ends with
> AGENT GENERATED.
AGENT GENERATED
Activity
bb-slop-cop commentedon Nov 29, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilothost,plugins,perfand reproduction labelpartial-repro; no existing classification was replaced.synchronous=1(NORMAL), withDEFAULT_WAL_SYNCHRONOUS=1in this build. The reported FULL-default explanation did not reproduce.alpine-vortex commentedon Nov 30, 2026
Same pattern on a home Linux server (bb 0.50.1, ext4 on NVMe, no VPS), seen from the disk-wear side rather than stalls.
jbd2is the top device-level writer, i.e. many small fsync commits.pidstat -d, the largest single source attributable to one app.data.dbfiles (host-monitor, agent-lanes, shell-tasks, etc.) show 4-6 MB WALs touched every few seconds, consistent with the missingsynchronous = NORMALand the 100 ms PASSIVE checkpoint polling described here.Setting
synchronous = NORMALon plugin DBs and skipping the checkpoint when the WAL is empty would likely cut this noticeably.Checkpoint a WAL only once it holds 1,000 frames the database lacks (g…
Checkpoint a WAL only once it holds 1,000 frames the database lacks (g…