#7356 · Partial vacuum progress is omitted after contention
Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro
1. TL;DR
The maintenance sweep can reclaim some free database pages and then encounter another writer before its next chunk. The completed work remains effective, but the sweep logs only a failure and omits all progress figures. An actual SQLite write lock reproduced this for both the core database and plugin-database entry points. Two clean checkouts at the same trusted main commit produced the same two failing assertions, while four failure-classification controls passed.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Maintenance reclaims pages in chunks. | Verified | First chunk reduced free pages from 2550 to 2294, and database bytes from 11333632 to 10285056. |
| A competing writer can block a later chunk. | Verified | A second real connection acquires BEGIN IMMEDIATE after the first chunk; SQLite returns SQLITE_BUSY with message “database is locked”. |
| The log discards earlier progress. | Verified | The single warning says “Incremental database vacuum failed” and contains err, but no result. Plugin logs preserve pluginId but also omit progress. |
| This affects reporting rather than database integrity. | Verified within the reproduction | Earlier page reclamation remains visible; integrity_check returns ok after releasing the writer. This is not a proof for every possible database failure. |
3. Environment
- Public repository get-bb/bb; trusted origin/main commit
7c1353d80729983b86ea1555d18b42407f320406, also verified through the repository GitHub commit API. - Linux 4.19.0-gvisor; Node 22.19.0; pnpm 9.15.0; repository better-sqlite3 12.11.1; Vitest 4.1.12.
- Two new detached worktrees named base and verify, separate installations and file-backed SQLite databases. No live BB instance, provider session, HTTP ports, or user runtime data were used.
- Database seeds come from createMigratedConnection(), using the real migrations. The test uses the real WAL-checkpoint worker and a second real SQLite connection; no database mocks.
4. Minimal reproduction
- Create a clean checkout of the trusted commit and install the frozen dependencies:
git clone https://github.com/get-bb/bb.git bb-7356 cd bb-7356 git checkout --detach 7c1353d80729983b86ea1555d18b42407f320406 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build --filter=@get-bb/plugin-sdk pnpm exec turbo run build
- Save the exact test below as
apps/server/test/services/database-vacuum-contention.test.ts. It seeds over 1024 free pages, delegates checkpoints to the real worker, and acquires a competing writer lock only after observing reclaimed pages. The other cases acquire a lock before any progress, or inject a non-SQLite checkpoint error. - Run the existing server test task through Turbo:
pnpm exec turbo run test --filter=@bb/server -- test/services/database-vacuum-contention.test.ts
Expected: one stopped-early warning containing the initial and final successful page statistics after partial progress, no completed log, and unchanged failure handling for first-chunk contention and unrelated errors.
Actual on trusted main: exit 1; 2 failed, 4 passed. Only the core/plugin later-chunk cases fail. Before the failing log assertion, both show reclaimed pages and pass integrity_check.
Complete regression source
import Database from "better-sqlite3";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import {
createConnection,
getDatabaseFreelistStats,
startWalCheckpointer,
} from "@bb/db";
import { createMigratedConnection } from "@bb/db/testing";
import {
runDatabaseMaintenanceSweep,
runPluginDatabaseMaintenanceSweep,
} from "../../src/services/system/periodic-sweeps.js";
describe.each(["core", "plugin"] as const)(
"%s vacuum contention",
(surface) => {
it.each(["first chunk", "later chunk", "unexpected error"] as const)(
"reports %s without losing the outcome",
async (failure) => {
const directory = mkdtempSync(join(tmpdir(), "bb-vacuum-contention-"));
const databasePath = join(directory, "maintenance.db");
const template = createMigratedConnection();
try {
await template.$client.backup(databasePath);
} finally {
template.$client.close();
}
const db = createConnection(databasePath);
const writer = new Database(databasePath);
const logger = {
debug: vi.fn(),
error: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
};
const checkpointer = startWalCheckpointer({ logger });
checkpointer.attach(db.$client);
let interrupted = false;
try {
db.$client.exec("CREATE TABLE vacuum_payload (payload BLOB)");
const insert = db.$client.prepare(
"INSERT INTO vacuum_payload VALUES (zeroblob(8192))",
);
db.$client.transaction(() => {
for (let row = 0; row < 1200; row += 1) insert.run();
})();
db.$client.exec("DELETE FROM vacuum_payload");
const before = getDatabaseFreelistStats(db.$client);
expect(before.freelistCount).toBeGreaterThan(1024);
if (failure === "first chunk") writer.exec("BEGIN IMMEDIATE");
const unexpectedError = new Error("Checkpoint interrupted");
const walCheckpointer = {
...checkpointer,
async checkpoint(database: Database.Database): Promise<void> {
await checkpointer.checkpoint(database);
if (
failure !== "first chunk" &&
!interrupted &&
getDatabaseFreelistStats(database).freelistCount <
before.freelistCount
) {
interrupted = true;
if (failure === "unexpected error") throw unexpectedError;
writer.exec("BEGIN IMMEDIATE");
}
},
};
if (surface === "core") {
await runDatabaseMaintenanceSweep({ db, logger, walCheckpointer });
} else {
await runPluginDatabaseMaintenanceSweep({
logger,
walCheckpointer,
plugins: {
listOpenPluginDatabases: () => [
{ database: db.$client, pluginId: "contention-test" },
],
},
});
}
const after = getDatabaseFreelistStats(db.$client);
expect(after.freelistCount).toBeGreaterThan(0);
if (failure === "first chunk") {
expect(after).toEqual(before);
} else {
expect(interrupted).toBe(true);
expect(after.freelistCount).toBeLessThan(before.freelistCount);
}
if (writer.inTransaction) writer.exec("ROLLBACK");
expect(db.$client.pragma("integrity_check", { simple: true })).toBe(
"ok",
);
expect(logger.info).not.toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
...(surface === "plugin" ? { pluginId: "contention-test" } : {}),
err:
failure === "unexpected error"
? unexpectedError
: expect.objectContaining({ code: "SQLITE_BUSY" }),
...(failure === "later chunk"
? { result: { before, after } }
: {}),
}),
failure === "later chunk"
? "Incremental database vacuum stopped early"
: "Incremental database vacuum failed",
);
} finally {
if (writer.inTransaction) writer.exec("ROLLBACK");
writer.close();
await checkpointer.stop();
db.$client.close();
rmSync(directory, { recursive: true, force: true });
}
},
);
},
);
First run: verbatim test output
❯ |@bb/server| test/services/database-vacuum-contention.test.ts (6 tests | 2 failed) 947ms
✓ reports first chunk without losing the outcome 195ms
× reports later chunk without losing the outcome 195ms
✓ reports unexpected error without losing the outcome 78ms
✓ reports first chunk without losing the outcome 189ms
× reports later chunk without losing the outcome 195ms
✓ reports unexpected error without losing the outcome 88ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
FAIL |@bb/server| test/services/database-vacuum-contention.test.ts > core vacuum contention > reports later chunk without losing the outcome
AssertionError: expected "vi.fn()" to be called once with arguments: [ ObjectContaining{…}, …(1) ]
Received:
1st vi.fn() call:
[
- ObjectContaining {
- "err": ObjectContaining {
+ {
+ "err": SqliteError {
+ "message": "database is locked",
"code": "SQLITE_BUSY",
},
- "result": {
- "after": {
- "databaseBytes": 10285056,
- "freelistBytes": 9396224,
- "freelistCount": 2294,
- "pageCount": 2511,
- "pageSize": 4096,
},
- "before": {
- "databaseBytes": 11333632,
- "freelistBytes": 10444800,
- "freelistCount": 2550,
- "pageCount": 2767,
- "pageSize": 4096,
- },
- },
- },
- "Incremental database vacuum stopped early",
+ "Incremental database vacuum failed",
]
Number of calls: 1
❯ test/services/database-vacuum-contention.test.ts:95:29
93| expect(db.$client.pragma("integrity_check", { simple: true }))…
94| expect(logger.info).not.toHaveBeenCalled();
95| expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
| ^
96| expect.objectContaining({
97| ...(surface === "plugin" ? { pluginId: "contention-test" }…
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯
FAIL |@bb/server| test/services/database-vacuum-contention.test.ts > plugin vacuum contention > reports later chunk without losing the outcome
AssertionError: expected "vi.fn()" to be called once with arguments: [ ObjectContaining{…}, …(1) ]
Received:
1st vi.fn() call:
[
- ObjectContaining {
- "err": ObjectContaining {
+ {
+ "err": SqliteError {
+ "message": "database is locked",
"code": "SQLITE_BUSY",
},
"pluginId": "contention-test",
- "result": {
- "after": {
- "databaseBytes": 10285056,
- "freelistBytes": 9396224,
- "freelistCount": 2294,
- "pageCount": 2511,
- "pageSize": 4096,
},
- "before": {
- "databaseBytes": 11333632,
- "freelistBytes": 10444800,
- "freelistCount": 2550,
- "pageCount": 2767,
- "pageSize": 4096,
- },
- },
- },
- "Incremental database vacuum stopped early",
+ "Incremental database vacuum failed",
]
Number of calls: 1
❯ test/services/database-vacuum-contention.test.ts:95:29
93| expect(db.$client.pragma("integrity_check", { simple: true }))…
94| expect(logger.info).not.toHaveBeenCalled();
95| expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
| ^
96| expect.objectContaining({
97| ...(surface === "plugin" ? { pluginId: "contention-test" }…
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯
Test Files 1 failed (1)
Tests 2 failed | 4 passed (6)
Start at 12:10:39
Duration 6.89s (transform 2.74s, setup 1.62s, import 2.43s, tests 947ms, environment 0ms)
5. Root cause
The chunk loop saves the first and last successful results, but returns them only on normal completion. There is no local handling for contention at the incremental-vacuum call:
if (last !== null) {
await new Promise<void>((resolve) => setImmediate(resolve));
}
await walCheckpointer.checkpoint(client);
last = runIncrementalVacuum(client, {
maxPages: Math.min(
DATABASE_INCREMENTAL_VACUUM_CHUNK_PAGES,
DATABASE_INCREMENTAL_VACUUM_MAX_PAGES - vacuumedPages,
),
});
await walCheckpointer.checkpoint(client);
first ??= last;
if (last.after.freelistCount === 0) {
break;
}
}
if (first === null || last === null) {
throw new Error("Incremental vacuum ran no chunks");
}
return { before: first.before, after: last.after };
runIncrementalVacuum executes the actual SQLite pragma. Its maintenance timeout wrapper limits the busy wait to 100 milliseconds and restores the connection timeout afterward; it does not suppress errors.
The exception therefore leaves the loop before its aggregated result is returned. The outer handler logs only the error as a failed run. The already completed pragma is not rolled back: chunks are separate synchronous operations, with an event-loop yield between them.
Both core and plugin maintenance use that same reporting boundary, explaining the matching observations.
6. Proposed fix
Represent a later SQLITE_BUSY as an interrupted outcome carrying the first before statistics, last successful after statistics, and actual error. Let the existing reporting boundary log that outcome once as stopped early, retaining plugin identity and suppressing the completed log. Catch only the incremental-vacuum operation; first-chunk busy errors, checkpoint failures, and non-busy errors must retain the existing failure path. Keep the normal successful result unchanged. No database schema, stored data, public protocol, or dependency change is needed.
7. Related issues
#5192 concerns vacuum-related server stalls, a different impact from lost partial-progress reporting. No open pull request linked to #7356 was found through the issue timeline or repository pull-request search at investigation time.
8. Verification
The same agent repeated the reproduction in a second clean detached checkout named verify at exactly 7c1353d80729983b86ea1555d18b42407f320406, with its own frozen install, full build, new database directories, and SQLite connections. The command was identical to the first run. It again exited 1 with 2 failed and 4 passed: only the two partial-progress log assertions failed. This is a repeated clean reproduction, not independent-agent verification. No report correction was needed.
❯ |@bb/server| test/services/database-vacuum-contention.test.ts (6 tests | 2 failed) 937ms
✓ reports first chunk without losing the outcome 199ms
× reports later chunk without losing the outcome 198ms
✓ reports unexpected error without losing the outcome 78ms
✓ reports first chunk without losing the outcome 182ms
× reports later chunk without losing the outcome 195ms
✓ reports unexpected error without losing the outcome 79ms
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 2 ⎯⎯⎯⎯⎯⎯⎯
FAIL |@bb/server| test/services/database-vacuum-contention.test.ts > core vacuum contention > reports later chunk without losing the outcome
AssertionError: expected "vi.fn()" to be called once with arguments: [ ObjectContaining{…}, …(1) ]
Received:
1st vi.fn() call:
[
- ObjectContaining {
- "err": ObjectContaining {
+ {
+ "err": SqliteError {
+ "message": "database is locked",
"code": "SQLITE_BUSY",
},
- "result": {
- "after": {
- "databaseBytes": 10285056,
- "freelistBytes": 9396224,
- "freelistCount": 2294,
- "pageCount": 2511,
- "pageSize": 4096,
},
- "before": {
- "databaseBytes": 11333632,
- "freelistBytes": 10444800,
- "freelistCount": 2550,
- "pageCount": 2767,
- "pageSize": 4096,
- },
- },
- },
- "Incremental database vacuum stopped early",
+ "Incremental database vacuum failed",
]
Number of calls: 1
❯ test/services/database-vacuum-contention.test.ts:95:29
93| expect(db.$client.pragma("integrity_check", { simple: true }))…
94| expect(logger.info).not.toHaveBeenCalled();
95| expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
| ^
96| expect.objectContaining({
97| ...(surface === "plugin" ? { pluginId: "contention-test" }…
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/2]⎯
FAIL |@bb/server| test/services/database-vacuum-contention.test.ts > plugin vacuum contention > reports later chunk without losing the outcome
AssertionError: expected "vi.fn()" to be called once with arguments: [ ObjectContaining{…}, …(1) ]
Received:
1st vi.fn() call:
[
- ObjectContaining {
- "err": ObjectContaining {
+ {
+ "err": SqliteError {
+ "message": "database is locked",
"code": "SQLITE_BUSY",
},
"pluginId": "contention-test",
- "result": {
- "after": {
- "databaseBytes": 10285056,
- "freelistBytes": 9396224,
- "freelistCount": 2294,
- "pageCount": 2511,
- "pageSize": 4096,
},
- "before": {
- "databaseBytes": 11333632,
- "freelistBytes": 10444800,
- "freelistCount": 2550,
- "pageCount": 2767,
- "pageSize": 4096,
- },
- },
- },
- "Incremental database vacuum stopped early",
+ "Incremental database vacuum failed",
]
Number of calls: 1
❯ test/services/database-vacuum-contention.test.ts:95:29
93| expect(db.$client.pragma("integrity_check", { simple: true }))…
94| expect(logger.info).not.toHaveBeenCalled();
95| expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
| ^
96| expect.objectContaining({
97| ...(surface === "plugin" ? { pluginId: "contention-test" }…
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/2]⎯
Test Files 1 failed (1)
Tests 2 failed | 4 passed (6)
Start at 12:10:50
Duration 6.74s (transform 2.68s, setup 1.56s, import 2.40s, tests 937ms, environment 0ms)
9. Appendix and limits
All root-cause links were checked against the recorded commit. The reproduction is nonvisual, so no screenshot is applicable. Extended SQLITE_BUSY variants are accounted for in the proposed prefix check but were not induced in this reproduction. A non-busy checkpoint failure is injected as an explicit control; actual contention always comes from SQLite itself.
The first full build encountered a clean-install SDK build-order failure in the GitHub plugin. Building the existing SDK runtime first, then repeating the normal full build, passed all 73 build tasks in each checkout. No dependency was added or modified to address this setup issue.
Repository policy keeps raw logs and test artifacts out of the public report repository, so the reproducible source and exact expected-versus-actual evidence are embedded above. Raw evidence is retained locally. Issue content was treated as untrusted claims only; no issue-supplied code, commands, or instructions were executed.