Skip to content

Stop the hourly dbstat scan and automatic VACUUM on auto_vacuum=NONE databases - #7101

Merged
ymichael merged 1 commit into
mainfrom
bb/optimize-database-maintenance-tasks-thr_tabve4qfxc
Nov 6, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/optimize-database-maintenance-tasks-thr_tabve4qfxc

Conversation

@ymichael

@ymichael ymichael commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

On a database with auto_vacuum=NONE, the maintenance sweep ran on the first sweep tick after start and then every hour. When the app was idle, it called getDatabaseCompactionStats, which runs SELECT SUM(unused) FROM dbstat. That query reads every page of the file on the main thread. If at least 128 MB and 15% of the file was reclaimable, the sweep then called compactDatabase, a full VACUUM on the main thread with the write lock held. Below that threshold the database never converts, so it pays for the scan every hour. Above it, it converts through one long VACUUM stall. Files created before 2026-05-29 are NONE, as are copies made by bb server move from those files and every plugin data.db. This matches a Discord report from Oct 2 of a 7.7 GB bb.db blocking the event loop for 15–26 minutes hourly and after every restart. This is PR 1b of the bb.db size plan (§5a).

What changed

  • packages/db/src/data/maintenance.ts: deleted getDatabaseCompactionStats, the dbstat reader, shouldCompactDatabase, compactDatabase and the 128 MB / 15% thresholds. The only stats left are getDatabaseFreelistStats, which reads page_count, freelist_count and page_size from the header.
  • apps/server/src/services/system/periodic-sweeps.ts: runDatabaseMaintenanceSweep still drops the deferred legacy tables, then runs the chunked incremental vacuum on incremental databases. It does nothing on NONE or FULL databases. bb no longer runs a full VACUUM on its own; reclaiming space on NONE files is left to the planned opt-in offline compact.
  • apps/server/src/services/plugins/plugin-api.ts: storage.database() sets auto_vacuum = INCREMENTAL before journal_mode = WAL, so newly created plugin data.db files are incremental. Existing plugin files keep their mode, since the pragma has no effect on an existing file until it is vacuumed. The SDK's createFakePluginHost does the same for parity.
  • Docs: the PluginStorage.database() JSDoc and the bb-plugin-authoring backend reference now say new files are incremental and bb never runs a full VACUUM on them. Plugin SDK bumped to 0.6.127 for the doc comment.
  • Nothing displayed the in-page unused figure, so no UI loses a number. This PR does not depend on the worker-thread checkpoint PR.
  • No wire change, no migration.

How you verified

Real servers on NONE clones of the scrubbed heavy.db (3.93 GB, auto_vacuum=0, freelist 0). Each server had its own APFS clone, with active threads and pending interactions set idle so the sweep's idle check passes. The servers ran from source (pnpm start --data-dir … --perf-diagnostics), one on origin/main (fa30b0a) and one on this branch, with a fresh data dir, not signed in. Event-loop stall log (Event loop stalled, 100 ms threshold) and slow-query log (25 ms):

First sweep after start origin/main this branch
dbstat query 12,473 ms (3,451 ms CPU, 65,506 major page faults) not run
Event loop stalled maxDelayMs 12,511 ms, lastCompletedWork: sweep:database-maintenance none logged; worst 5 s sample maxDelayMs 85 ms (50 ms timer resolution)
Hourly sweep (60 min later) origin/main this branch
dbstat query 8,733 ms at 23:42:52 not run
Event loop stalled maxDelayMs 8,744 ms, lastCompletedWork: sweep:database-maintenance none logged at the tick

Over the whole 77-minute run (about 925 five-second samples each), origin/main logged two stalls over 150 ms, both from the maintenance sweep (12.5 s and 8.7 s). This branch's worst sample was 101 ms, from GET /api/v1/hosts at 23:51, which is unrelated to maintenance.

The sweep in isolation, timing runDatabaseMaintenanceSweep directly with each tree's code on fresh clones (production createConnection pragmas):

Database origin/main run 1 / 2 / 3 this branch run 1 / 2 / 3
heavy.db clone, NONE, 3.93 GB, below the 15% threshold 8,114 / 704 / 692 ms (dbstat every run; "skipped below compaction threshold") 0.10 / 0.03 / 0.03 ms
subset.db clone, NONE, 686 MB, archived threads' events deleted (418 MB / 61% free) 4,016 ms full VACUUM, file 686 → 261 MB and converted to incremental; then 0.14 ms 0.29 / 0.20 ms; file, mode and freelist unchanged

Plugin databases created by the two servers above: on origin/main automations, bb--git, bb--github-pr-status and side-chat have auto_vacuum=0; on this branch all four have auto_vacuum=2.

Tests:

  • database-maintenance-sweep.test.ts gains "leaves idle auto_vacuum=NONE databases untouched without scanning pages". It fails on origin/main because dbstat is prepared, and passes here.
  • plugin-settings-storage.test.ts and fake-plugin-host.test.ts assert auto_vacuum = 2 after a plugin's first table.
  • The compactDatabase and shouldCompactDatabase tests were removed along with the code.
  • Ran locally: turbo run typecheck --filter=@bb/db --filter=@bb/server --filter=@get-bb/plugin-sdk, the db maintenance test, the server sweep and plugin storage tests, the SDK fake-host test, and check-plugin-sdk-version.mjs. CI runs the full suites.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael added a commit that referenced this pull request Nov 5, 2026
#7101 owns creating new plugin data.db files with incremental auto-vacuum,
its SDK doc comment, the plugin-authoring note and the SDK bump. This PR
keeps the hourly sweep that returns free pages of incremental plugin files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…databases

The maintenance sweep ran SELECT SUM(unused) FROM dbstat on the main thread
for every idle non-incremental database, at startup and hourly, and then a
full VACUUM when 15% of the file was reclaimable. Both block the event loop
for as long as reading or rewriting the whole file takes.

The sweep now only runs chunked incremental vacuum on incremental databases
and does nothing on NONE ones; stats come from page_count, freelist_count and
page_size. compactDatabase and the dbstat-based compaction stats are removed.
Plugin data.db files are created with auto_vacuum=INCREMENTAL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/optimize-database-maintenance-tasks-thr_tabve4qfxc branch from 46b10e4 to 933bf31 Compare November 5, 2026 23:50
@ymichael
ymichael merged commit 18aeb40 into main Nov 6, 2026
52 checks passed
@ymichael
ymichael deleted the bb/optimize-database-maintenance-tasks-thr_tabve4qfxc branch November 6, 2026 00:01
ymichael added a commit that referenced this pull request Nov 6, 2026
…databases (#7106)

## Human comments

## What was wrong

Four pieces of storage were growing with nothing to remove them:

- **Exited `terminal_sessions` rows were never deleted.** The usage
plugin's scans leave about 3.7k a day. The storage report measured
186,399 exited rows, 41 MB with their 6 indexes. Nothing reads them: the
daemon keeps an exited terminal's output for 30 minutes
(`HOST_DAEMON_TERMINAL_EXIT_RETENTION_MS`), and the UI shows only live
sessions.
- **Archived threads kept their per-thread pruning cursors** (8,028
rows). Archiving and late idle transitions run one live pruning step,
and that step created a scoped cursor nothing used again; the background
sweep is what finishes archived threads. Four
`completed_event_output_truncation` scan cursors were also left over
from a superseded migration.
- **Plugin `data.db` files were created with `auto_vacuum=NONE`**
(`plugin-api.ts` opened them with only WAL and busy_timeout), so free
pages never left the file. The installed `usage` plugin's file is 195
MB, of which 178 MB is free pages.
- **A plugin update's rollback snapshot stayed for 7 days after the
update settled** (`plugins/snapshots/usage`, another 195 MB). Only a
failed stabilization ever reads it, and the replaced artifact it would
roll back to is deleted as soon as the update settles.

This is PLAN.md §6 items 3 and 3b of the bb.db storage plan
(thr_y6xhxw8t8w).

## What changed

- **Exited terminals:** new `pruneExitedTerminalSessions`
(`packages/db/src/data/terminal-sessions.ts`) and an
`exited-terminal-session-prune` sweep job. It deletes rows exited more
than 7 days ago, 1,000 per 10 s tick, through a new partial index
`terminal_sessions_exited_prune_idx` (`updated_at, id WHERE status =
'exited'`). With the index, the steady-state empty check costs about
0.03 ms instead of a scan of every exited row.
- **Pruning cursors:** archiving a thread still runs its one live
pruning step, then deletes that thread's scoped cursors
(`deleteThreadScopedPruningCursors`, called from `thread-archive.ts`);
the background sweep finishes archived threads. Migration
`0152_small_storage_cleanups` deletes the existing archived-thread
cursors and the dead truncation cursors, and creates the index.
- The cleanup sits in the archive flow, not in the pruning step itself:
the usage policy carries its keeper state across live steps, so deleting
cursors after every step would stop a live pass on an archived thread
from ever getting past its first policy. A turn that finishes during the
archive undo grace still runs one idle step and can leave one scoped row
behind; archiving again clears it.
- **Plugin databases:** a new hourly `plugin-database-maintenance` job
takes open handles from `PluginService.listOpenPluginDatabases()` and
returns the free pages of those in incremental auto-vacuum mode, using
the same chunked incremental vacuum bb.db uses. The freelist/mode/vacuum
primitives in `maintenance.ts` now take the raw SQLite client so both
sweeps share them.
- **Builds on #7101 (merged):** #7101 makes `storage.database()` create
new `data.db` files with `auto_vacuum = INCREMENTAL`, so new plugin
files get this sweep. This branch is rebased on it.
- Existing NONE files are left alone: converting one needs a full
VACUUM, which measured 0.7–1.0 s on the event loop for a usage-sized
file. The plan sends that conversion to the opt-in offline compact (§5a,
PR 18).
- **Snapshots:** `activateManagedUpdate` deletes its snapshot once the
update settles. Startup GC (`listDiscardablePluginStateSnapshots`) also
discards snapshots created by an earlier server process, except
rollbacks still `rollback-pending` or `restoring`. That is what removes
an existing install's leftover copy on its next restart.
- Docs: `docs/configuration.md` (plugin data.db and the snapshots
directory) and `docs/events-table-pruning.md`. No plugin SDK surface
change.
- No `HOST_DAEMON_PROTOCOL_VERSION` change: the daemon never opens bb.db
or plugin databases.
- **Behaviour notes:**
- The default title of a new terminal ("Terminal N") counts a thread's
terminals, including exited ones. After 7 days, exited terminals stop
counting.
- Two tests asserted the old snapshot retention ("keeps rollback state
through the grace period", and a `restored` row after restart); they now
assert the snapshot is gone.

## How you verified

**Measurements on the scrubbed copies** (APFS clones of
`thr_n6cyn6sk25/perf/data-heavy/heavy.db` and `perf/data/subset.db`;
nothing ran against `~/.bb`). The scrub emptied `terminal_sessions` and
`thread_pruning_cursors`. As-is, both copies save nothing: heavy.db's
only affected rows are the 4 dead truncation cursors, and the new empty
index adds 4 KB. To get numbers at production scale, I seeded a heavy.db
clone with the report's counts:
- 186,399 exited threadless terminals spread over 50 days;
- 8,028 scoped cursors on 4,014 archived threads.

I then ran the real migration and the sweep function. The seeded rows
are about 20% larger than production's (51 MB against 41 MB), so expect
the production saving to be about 20% smaller.

| heavy.db + seeded rows | Before | After |
|---|---|---|
| `terminal_sessions` + indexes (incl. the new one) | 51.3 MB | 8.0 MB
(26,095 rows from the last 7 days) |
| `thread_pruning_cursors` | 1.01 MB | 12 KB |
| dead truncation cursors | 4 rows | 0 |
| File, incremental copy, after one `runDatabaseMaintenanceSweep` |
3,920,027,648 B | 3,870,126,080 B (**−49.9 MB**) |
| File, NONE copy | 3,998,072,832 B | unchanged; 55.8 MB moved to the
freelist for reuse |

- Migration 0152 on heavy.db: cursor deletes 6–7 ms; the index build
over 186k rows 43–91 ms (one time).
- Sweep batches of 1,000 rows: 161 batches, p50 2.2 ms, p99 2.6 ms, max
3.6 ms. The backlog drains in about 27 minutes at one batch per tick.
256-row batches were 0.6 ms each but needed 104 minutes, so 1,000
matches the closed-session prune.

**Usage plugin database.** No copy exists under the scrubbed
directories, and I didn't copy the live one. I measured on a synthetic
DB with the same shape (195 MB file, 175 MB free after the plugin's
delete pattern), created in incremental mode the way #7101 makes
`storage.database()` create files, and ran
`runPluginDatabaseMaintenanceSweep` on it hourly:

| | File | Freelist | Sweep work |
|---|---|---|---|
| Before | 194.9 MB | 174.5 MB | — |
| Hour 1 | 112.9 MB | 92.6 MB | 98 ms in 256-page chunks |
| Hour 2 | 30.9 MB | 10.7 MB | 62 ms |
| Hour 3 | 20.2 MB | 0 | 7 ms |

The 195 MB Oct 29 snapshot copy goes at the next restart; that is
covered by the GC test below, not observed live. Together that is the
plan's −373 MB for the usage plugin, except the 178 MB inside the
existing NONE file, which needs the offline compact.

**Tests** (each fails without its change):
- `pruneExitedTerminalSessions` deletes only rows exited before the
cutoff, oldest first, within the limit.
- Archiving through the API leaves no scoped cursor for the thread, and
draining live pruning afterwards still applies every retention rule
(`event-pruning.test.ts`).
- Migration 0152 keeps global and live cursors and drops archived and
dead ones.
- The plugin sweep empties an incremental plugin DB's freelist and
neither vacuums nor converts a NONE one.
- Startup GC drops `ready`/`restored` snapshots from an earlier process
and keeps `rollback-pending`, `restoring` and this process's snapshots.
- A settled update leaves no snapshot row or directory.

Commands:
- `turbo run lint typecheck --filter=@bb/db --filter=@bb/server`
- vitest in packages/db: terminal-sessions, thread-pruning, maintenance,
completed-event-output-migration, migrate, query-plans, schema,
plugin-state-snapshots, sweeps
- vitest in apps/server: plugin
snapshot/update/cache-prune/settings-storage,
database-maintenance-sweep, periodic-sweeps, test/system,
public-terminals, public-thread-lifecycle-ownership, services/threads

The full suites run in CI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

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