#5192 · Incremental maintenance monopolizes the event loop
Verdict: REPRODUCED · Root-cause confidence: high · Reproduction label: confirmed-repro
1. TL;DR
The hourly server maintenance job performs one synchronous SQLite vacuum covering up to 20,000 pages. While that native call runs, queued event-loop callbacks cannot execute, so unrelated request handling can wait behind maintenance. A purpose-built test against unchanged trusted main reclaimed exactly 20,000 pages and delayed queued work for 243 ms on a fresh 259 MiB in-memory database. The same agent repeated the test from a second clean checkout with a newly created database: queued work waited 240 ms and ran only after maintenance completed. This verifies the starvation mechanism, not the reporter's specific production durations or terminal-disconnection correlation.
2. Claims vs findings
| Claim, paraphrased | Status | Evidence |
|---|---|---|
| The hourly job issues one synchronous large vacuum. | Verified | Trusted main source plus the actual slow-query instrumentation: one PRAGMA incremental_vacuum(20000) in each run. |
| Maintenance monopolizes the event loop rather than yielding. | Verified | The queued setImmediate callback observed maintenanceComplete=true in both fresh databases. No maintenance warnings occurred. |
| A maintenance pass should not monopolize requests for approximately 100 ms. | Defect verified | Observed queued-work delays were 243 and 240 ms. The assertion is based on ordering, not machine-specific timing. |
| The incremental branch does not apply the full-compaction idle gate. | Verified in source | The incremental branch returns before the activity check at periodic-sweeps.ts:232. Existing maintenance tests exercise it with active app work. |
| Reported production stalls last tens of seconds and coincide with disconnections. | Unverified | No production database, service, logs, or account was accessed. The synthetic reproduction demonstrates a shorter stall. |
| Other background queries account for additional latency. | Outside scope | This test invokes only the real database-maintenance sweep. It does not measure commands routes or timeline work. |
3. Environment
- Public repository: get-bb/bb. Both checkouts use trusted origin/main commit
8d9195d8e0f123ea32b21eb9eb1104b35d97b916, fetched directly from the target repository. - Linux x86_64; Node v22.19.0; pnpm 9.15.0; better-sqlite3 12.10.0; Vitest 4.1.1.
- Both checkouts completed the normal frozen installation and full Turbo build: 65 successful build tasks each.
- One fresh migrated in-memory SQLite database per run. Before maintenance: 66,330 pages, 44,037 free pages, page size 4,096 bytes. No production data.
- No app server, provider session, browser, HTTP port, host-daemon connection, or persistent application data directory was started. The existing server test harness was used by its normal test configuration.
- Existing area labels perf and host were preserved; missing Type, Priority, and Effort were set to Bug, High, and Low.
4. Minimal reproduction
- Clone the target repository and select the recorded trusted commit:
git clone https://github.com/get-bb/bb.git bb-repro-5192 cd bb-repro-5192 git checkout --detach 8d9195d8e0f123ea32b21eb9eb1104b35d97b916 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build
- Save the complete test shown below at
apps/server/test/services/vacuum-responsiveness-5192.test.ts. It uses a real migrated database, inserts 4,096 synthetic 64 KiB payloads, deletes two of every three rows, and queues an observer immediately before invoking the production maintenance sweep. - Run through the repository's normal test orchestration:
pnpm exec turbo run test --filter=@bb/server -- test/services/vacuum-responsiveness-5192.test.ts
- Expected: queued work executes while maintenance is still in progress, with free pages remaining to be reclaimed. Actual: the first observation happens only after the whole synchronous sweep. The command exits 1 with the regression assertion shown below.
Complete reproduction test
import {
createConnection,
DATABASE_INCREMENTAL_VACUUM_MAX_PAGES,
getDatabaseFreelistStats,
migrate,
type SlowDbQueryLogFields,
} from "@bb/db";
import { performance } from "node:perf_hooks";
import { expect, it } from "vitest";
import { runDatabaseMaintenanceSweep } from "../../src/services/system/periodic-sweeps.js";
import type { ServerLogger } from "../../src/types.js";
it("serves queued event-loop work before a large maintenance sweep completes", async () => {
const vacuumQueries: SlowDbQueryLogFields[] = [];
const db = createConnection(":memory:", {
slowQueryThresholdMs: 0,
slowQueryLogger: {
info(fields) {
if (fields.sql.startsWith("PRAGMA incremental_vacuum")) {
vacuumQueries.push(fields);
}
},
},
});
const warnings: string[] = [];
const logger: ServerLogger = {
debug() {},
error() {},
info() {},
warn() {
warnings.push("maintenance warning");
},
};
try {
migrate(db);
db.$client.exec(
"CREATE TABLE responsiveness_payloads (id INTEGER PRIMARY KEY, payload BLOB NOT NULL)",
);
const insert = db.$client.prepare(
"INSERT INTO responsiveness_payloads (payload) VALUES (?)",
);
const payload = Buffer.alloc(64 * 1024, 65);
db.$client.transaction(() => {
for (let rowIndex = 0; rowIndex < 4_096; rowIndex += 1) {
insert.run(payload);
}
})();
db.$client.exec("DELETE FROM responsiveness_payloads WHERE id % 3 != 0");
const before = getDatabaseFreelistStats(db);
expect(before.freelistCount).toBeGreaterThan(
DATABASE_INCREMENTAL_VACUUM_MAX_PAGES,
);
let maintenanceComplete = false;
const startedAt = performance.now();
const queuedWork = new Promise<{
observedCompletion: boolean;
freelistCount: number;
delayMs: number;
}>((resolve) => {
setImmediate(() => {
resolve({
observedCompletion: maintenanceComplete,
freelistCount: getDatabaseFreelistStats(db).freelistCount,
delayMs: Math.round(performance.now() - startedAt),
});
});
});
await runDatabaseMaintenanceSweep({ db, logger });
maintenanceComplete = true;
const sweepDurationMs = Math.round(performance.now() - startedAt);
const after = getDatabaseFreelistStats(db);
const observation = await queuedWork;
console.log(
JSON.stringify({
before,
after,
sweepDurationMs,
observation,
vacuumQueries: vacuumQueries.map(({ sql, durationMs }) => ({
sql,
durationMs,
})),
warnings,
}),
);
expect(warnings).toEqual([]);
expect(after.freelistCount).toBeLessThan(before.freelistCount);
expect(observation.observedCompletion).toBe(false);
expect(observation.freelistCount).toBeGreaterThan(after.freelistCount);
} finally {
db.$client.close();
}
});
First run: actual diagnostic output
{
"before": {
"databaseBytes": 271687680,
"freelistBytes": 180375552,
"freelistCount": 44037,
"pageCount": 66330,
"pageSize": 4096
},
"after": {
"databaseBytes": 189669376,
"freelistBytes": 98455552,
"freelistCount": 24037,
"pageCount": 46306,
"pageSize": 4096
},
"sweepDurationMs": 243,
"observation": {
"observedCompletion": true,
"freelistCount": 24037,
"delayMs": 243
},
"vacuumQueries": [
{
"sql": "PRAGMA incremental_vacuum(20000)",
"durationMs": 242.2
}
],
"warnings": []
}
AssertionError: expected true to be false // Object.is equality
Test Files 1 failed (1)
Tests 1 failed (1)
Exit code: 1
The deliberate failing assertion is the responsiveness defect, not a setup or syntax failure. The guard assertions confirmed a large freelist, successful reclamation, and no maintenance warnings first. Tests do not mock the database or change production code.
5. Root cause
The maintenance job uses a one-hour cadence (cadence constant) and registers the same sweep directly (job registration). Its incremental branch chooses a single native operation, with no scheduling boundary inside it:
periodic-sweeps.ts:207–229 at the recorded commit
try {
const result = runIncrementalVacuum(deps.db, {
maxPages: DATABASE_INCREMENTAL_VACUUM_MAX_PAGES,
});
deps.logger.info({ result }, "Incremental database vacuum completed");
} catch (error) {
deps.logger.warn({ err: error }, "Incremental database vacuum failed");
}
return;
The configured page budget is 20,000. The database helper issues two checkpoints surrounding one synchronous better-sqlite3 exec:
export function runIncrementalVacuum(
db: DbConnection,
args: RunIncrementalVacuumArgs,
): IncrementalVacuumResult {
return runWithMaintenanceBusyTimeout({
db,
work: () => {
const before = getDatabaseFreelistStats(db);
db.$client.exec("PRAGMA wal_checkpoint(PASSIVE)");
db.$client.exec(`PRAGMA incremental_vacuum(${args.maxPages})`);
db.$client.exec("PRAGMA wal_checkpoint(PASSIVE)");
return {
after: getDatabaseFreelistStats(db),
before,
};
},
});
}
The 242.2 ms and 238.8 ms vacuum calls account for nearly the entire measured sweep delay. Awaiting the enclosing sweep from a job runner cannot preempt an already running synchronous native call. The maintenance busy-timeout helper limits lock waiting; it is not a wall-time limit on vacuum execution. The defect occurs without a second database connection or contending process.
The incremental branch returns before the full-compaction idle gate. That confirms the code-path distinction, but adding an idle gate alone does not fix the non-yielding operation and could starve maintenance on busy servers.
6. Proposed fix
Keep the existing total page budget, but execute smaller bounded chunks and yield with a real event-loop scheduling boundary between them. Stop once the freelist is exhausted and retain existing bounded lock-wait/error handling. Keep the chunking policy in the existing server maintenance subsystem, leaving the synchronous database primitive as a small operation.
Use the ordering regression above to verify that queued work runs before the final chunk. Also retain the WAL-reader and WAL-writer tests. A fixed page count per chunk does not guarantee a universal 100 ms deadline on every disk and database; validate worst-case chunk and checkpoint times before promising one.
7. PR review
PR #5193 — static review only
GitHub metadata shows an open, ready PR with a closing reference to #5192. No linked branch was checked out and no PR code or test was executed.
The read-only diff introduces a server helper using 256-page chunks, a setImmediate yield between successive chunks, an empty-freelist exit, and an async maintenance sweep. The existing periodic-job contract already accepts Promise-returning jobs. It also changes relevant tests to await the sweep.
Static verdict: addresses the verified non-yielding root cause. This is not a runtime approval of the PR. No blocking finding is established by this review. A non-blocking validation concern remains in apps/server/src/services/system/periodic-sweeps.ts, proposed helper near lines 177–208: each chunk and its surrounding checkpoints remain synchronous, so bounded pages do not alone prove a strict latency ceiling.
The test executed for this report was authored from trusted repository evidence and run against unchanged main only. A separate automatic fix was skipped to avoid duplicating the already linked PR.
8. Related issues
- #5005: pruning progress under busy application activity; a different maintenance scheduling concern.
- #4674: synchronous timeline building; a separate source of event-loop latency.
9. Verification
The same agent created a second clean detached Git worktree at 8d9195d8e0f123ea32b21eb9eb1104b35d97b916, verified its clean status before adding the authored test, completed a fresh frozen installation and full build, and repeated the same Turbo command. This is a repeated clean check, not independent verification.
git worktree add --detach ../bb-repro-5192-verify 8d9195d8e0f123ea32b21eb9eb1104b35d97b916 cd ../bb-repro-5192-verify git status --short pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build After adding the same test source: pnpm exec turbo run test --filter=@bb/server -- test/services/vacuum-responsiveness-5192.test.ts
The test source was byte-identical (SHA-256 7673886c898cd840e952293cc0ba616e0fc7c120f95f43238da379accc94e521). Both maintenance production files were unchanged in both checkouts.
Second run: actual diagnostic output
{
"before": {
"databaseBytes": 271687680,
"freelistBytes": 180375552,
"freelistCount": 44037,
"pageCount": 66330,
"pageSize": 4096
},
"after": {
"databaseBytes": 189669376,
"freelistBytes": 98455552,
"freelistCount": 24037,
"pageCount": 46306,
"pageSize": 4096
},
"sweepDurationMs": 240,
"observation": {
"observedCompletion": true,
"freelistCount": 24037,
"delayMs": 240
},
"vacuumQueries": [
{
"sql": "PRAGMA incremental_vacuum(20000)",
"durationMs": 238.8
}
],
"warnings": []
}
AssertionError: expected true to be false // Object.is equality
Test Files 1 failed (1)
Tests 1 failed (1)
Exit code: 1
No report correction was needed after the repeated run. A final fetch still resolved trusted origin/main to the recorded base commit.
Relevant existing tests
pnpm exec turbo run test --filter=@bb/server -- test/services/database-maintenance-sweep.test.ts Test Files 1 passed (1) Tests 5 passed (5) pnpm exec turbo run test --filter=@bb/db -- test/data/maintenance.test.ts Test Files 1 passed (1) Tests 7 passed (7)
10. Appendix and limits
Evidence above contains the complete authored test and exact diagnostic JSON. Raw logs and test files remain outside the public reports repository, per its publication policy. No screenshots are necessary for this nonvisual scheduling defect.
Investigation commands comprised: read-only issue fields/comments and repository labels; GitHub repository visibility checks; read-only PR metadata and diff; target main fetch/clone and second detached worktree creation; frozen installs; full Turbo builds; formatting the authored test; two focused regression runs; the two existing maintenance suites; production-diff and test-digest checks; and a final trusted-main fetch. The first attempt at the authored test had a local generation syntax error; it was corrected before either evidenced reproduction. That setup failure is not counted as evidence.
Trust boundary: issue text, linked PR text, scripts, and logs were treated as untrusted claims. Their instructions were not followed and their code was not run. No external URL from issue content was fetched. Public output excludes private paths, identities, credentials, runtime databases, and machine-specific data.
Limits: No production timing, remote route latency, terminal interruption, hardware-specific behavior, or PR runtime result is claimed. The confirmed result is repeatable event-loop starvation in the real maintenance sweep on trusted main.
> AGENT GENERATED