#5005 · Global maintenance gate starves settled-thread pruning
Verdict: REPRODUCED · Root-cause confidence: high · reproduction label: confirmed-repro
1. TL;DR
Background cleanup does not remove eligible old events from settled threads while any other thread is running, starting, or awaiting an interaction. The sweep checks workspace-wide activity before advancing even one policy. A frequently busy workspace can therefore indefinitely delay existing cleanup, independently of whether the settled thread is safe to prune. Four real migrated-SQLite regression cases fail at the same settled-history assertion in two clean checkouts. This does not establish the reported production database size, or promise substantial space savings from these retention rules.
2. Claims vs findings
| Claim | Status | Evidence |
|---|---|---|
| An unrelated active or starting thread prevents cleanup of settled history. | Verified | Both parameterized thread-status cases retain sequences [1, 2, 3] instead of [3], in both checkouts. |
| A pending interaction anywhere prevents the sweep. | Verified | Pending and resolving interaction cases show the same failure. |
| The background sweep is bounded and uses nonblocking SQLite write-lock acquisition. | Verified from source | 50 ms/64-advance sweep budget; 500-event pages for usage/diffs; busy_timeout is temporarily zero. These limits do not guarantee that each synchronous statement completes within 50 ms. |
| Production has a large database and many unpruned rows. | Unverified | No production data or credentials accessed. The reproduction uses six synthetic events. |
| Changing vacuum limits is necessary to solve this defect. | Not established | The failure occurs before any event deletion. Vacuum behavior and payload retention are separate questions. |
3. Environment
- Trusted repository: public
get-bb/bb; origin/main commitdf913a79dc687341d9bec06e483ff545376225de. - Linux 4.19.0-gvisor, Node v22.19.0, pnpm 9.15.0, Vitest 4.1.1.
- Two separately installed clean clones at the same commit. Only the authored regression test differs from that commit during reproduction.
- Existing server test harness creates and migrates isolated SQLite databases and new temporary test-data directories; no live server or provider session is started. No listening ports are required.
- Dependencies installed with
pnpm install --frozen-lockfile; test prerequisites built through Turbo. No dependency added.
4. Minimal reproduction
- Clone the trusted repository at the recorded commit and install the frozen dependencies:
git clone https://github.com/get-bb/bb.git bb-5005 cd bb-5005 git checkout --detach df913a79dc687341d9bec06e483ff545376225de pnpm install --frozen-lockfile
- Apply the authored test-only patch:
curl -fsS https://get-bb.github.io/reports/issues/5005/repro/reproduction.patch -o /tmp/reproduction-5005.patch git apply /tmp/reproduction-5005.patch
- Run the actual sweep against the real test database:
pnpm exec turbo run test --filter=@bb/server -- test/system/thread-pruning-sweep.test.ts -t 'prunes settled history while another thread'
- The fixture seeds a busy thread and a settled thread, each containing three obsolete turn-diff snapshots. It marks only the first thread active/starting, or adds a pending/resolving interaction belonging only to it. After the sweep, the busy history must be unchanged while the settled history must retain only its current tail. Once the busy state clears, a subsequent sweep must revisit that thread.
Expected: busy thread [1, 2, 3]; settled thread [3]. Actual: both retain [1, 2, 3]. All four cases fail at the settled-thread assertion, not during setup.
FAIL |@bb/server| test/system/thread-pruning-sweep.test.ts > thread pruning sweep > prunes settled history while another thread is active, then revisits it when idle @bb/server:test: FAIL |@bb/server| test/system/thread-pruning-sweep.test.ts > thread pruning sweep > prunes settled history while another thread is starting, then revisits it when idle @bb/server:test: FAIL |@bb/server| test/system/thread-pruning-sweep.test.ts > thread pruning sweep > prunes settled history while another thread is pending, then revisits it when idle @bb/server:test: FAIL |@bb/server| test/system/thread-pruning-sweep.test.ts > thread pruning sweep > prunes settled history while another thread is resolving, then revisits it when idle @bb/server:test: AssertionError: expected [ 1, 2, 3 ] to deeply equal [ 3 ] @bb/server:test: @bb/server:test: - Expected @bb/server:test: + Received @bb/server:test: @bb/server:test: [ @bb/server:test: + 1, @bb/server:test: + 2, @bb/server:test: 3, @bb/server:test: ] @bb/server:test: @bb/server:test: ❯ test/system/thread-pruning-sweep.test.ts:116:45 @bb/server:test: 114| await runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS… @bb/server:test: 115| expect(sequences(busyThread.id)).toEqual([1, 2, 3]); @bb/server:test: 116| expect(sequences(settledThread.id)).toEqual([3]); @bb/server:test: | ^ @bb/server:test: 117| harness.db @bb/server:test: 118| .update(threads) @bb/server:test: ❯ withTestHarness test/helpers/test-app.ts:367:12 @bb/server:test: ❯ test/system/thread-pruning-sweep.test.ts:84:7 @bb/server:test: @bb/server:test: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/4]⎯ @bb/server:test: @bb/server:test: @bb/server:test:
Artifacts: test-only patch, complete test file, first run, second run.
Regression test file
import { performance } from "node:perf_hooks";
import { eq, sql } from "drizzle-orm";
import { describe, expect, it, vi } from "vitest";
import {
advanceThreadPruning,
events,
getNextThreadPruningPolicy,
getThreadEventRewriteGeneration,
pendingInteractions,
threadPruningCursors,
threads,
} from "@bb/db";
import {
threadTimelineResponseSchema,
type ThreadTimelineResponse,
} from "@bb/server-contract";
import {
runThreadPruningSweep,
THREAD_PRUNING_SWEEP_LIMITS,
type ThreadPruningSweepLimits,
} from "../../src/services/system/thread-pruning-sweep.js";
import {
seedHost,
seedProjectWithSource,
seedThread,
} from "../helpers/seed.js";
import { readJson } from "../helpers/json.js";
import { withTestHarness, type TestAppHarness } from "../helpers/test-app.js";
function seed(harness: TestAppHarness, count: number) {
const host = seedHost(harness.deps);
const { project } = seedProjectWithSource(harness.deps, { hostId: host.id });
const thread = seedThread(harness.deps, { projectId: project.id });
harness.db.transaction((tx) => {
for (let sequence = 1; sequence <= count; sequence++)
tx.insert(events)
.values({
id: `${thread.id}-${sequence}`,
threadId: thread.id,
sequence,
scopeKind: "turn",
turnId: "turn",
type: "turn/diff/updated",
data: '{"diff":"unused"}',
createdAt: 1,
})
.run();
});
return thread;
}
async function getTimeline(
harness: TestAppHarness,
threadId: string,
afterSequence?: number,
): Promise<ThreadTimelineResponse> {
const query =
afterSequence === undefined ? "" : `?afterSequence=${afterSequence}`;
const response = await harness.app.request(
`/api/v1/threads/${threadId}/timeline${query}`,
);
expect(response.status).toBe(200);
return threadTimelineResponseSchema.parse(await readJson(response));
}
function removedEvents(fields: unknown): boolean {
return (
typeof fields === "object" &&
fields !== null &&
"removed" in fields &&
fields.removed !== 0
);
}
const UNTIMED_SWEEP_LIMITS: ThreadPruningSweepLimits = {
elapsedBudgetMs: Number.POSITIVE_INFINITY,
maxAdvances: THREAD_PRUNING_SWEEP_LIMITS.maxAdvances,
};
describe("thread pruning sweep", () => {
it.each(["active", "starting", "pending", "resolving"] as const)(
"prunes settled history while another thread is %s, then revisits it when idle",
async (activity) => {
await withTestHarness(async (harness) => {
const busyThread = seed(harness, 3);
const settledThread = seed(harness, 3);
if (activity === "active" || activity === "starting") {
harness.db
.update(threads)
.set({ status: activity })
.where(eq(threads.id, busyThread.id))
.run();
} else {
harness.db
.insert(pendingInteractions)
.values({
id: "pruning-interaction",
threadId: busyThread.id,
status: activity,
payload: "{}",
createdAt: 1,
updatedAt: 1,
})
.run();
}
const sequences = (threadId: string) =>
harness.db
.select({ sequence: events.sequence })
.from(events)
.where(eq(events.threadId, threadId))
.orderBy(events.sequence)
.all()
.map((event) => event.sequence);
await runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS);
expect(sequences(busyThread.id)).toEqual([1, 2, 3]);
expect(sequences(settledThread.id)).toEqual([3]);
harness.db
.update(threads)
.set({ status: "idle" })
.where(eq(threads.id, busyThread.id))
.run();
harness.db
.delete(pendingInteractions)
.where(eq(pendingInteractions.threadId, busyThread.id))
.run();
await runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS);
expect(sequences(busyThread.id)).toEqual([3]);
});
},
);
it("skips busy work and rechecks activity after a committed advance", async () => {
await withTestHarness(async (harness) => {
const thread = seed(harness, 1200);
harness.db
.update(threads)
.set({ status: "active" })
.where(eq(threads.id, thread.id))
.run();
await runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS);
expect(harness.db.select().from(threadPruningCursors).all()).toEqual([]);
harness.db
.update(threads)
.set({ status: "idle" })
.where(eq(threads.id, thread.id))
.run();
const generation = getThreadEventRewriteGeneration(thread.id);
const notify = vi
.spyOn(harness.deps.hub, "notifyThread")
.mockImplementation(() => {});
const debug = vi
.spyOn(harness.deps.logger, "debug")
.mockImplementation((fields, message) => {
if (
message === "Thread pruning policy advanced" &&
removedEvents(fields)
) {
expect(getThreadEventRewriteGeneration(thread.id)).toBeGreaterThan(
generation,
);
expect(harness.db.select().from(events).all()).toHaveLength(700);
harness.db
.update(threads)
.set({ status: "active" })
.where(eq(threads.id, thread.id))
.run();
}
});
await runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS);
expect(notify).toHaveBeenCalledExactlyOnceWith(thread.id, [
"history-compacted",
]);
expect(harness.db.select().from(events).all()).toHaveLength(700);
notify.mockRestore();
debug.mockRestore();
});
});
it("keeps notifications for earlier commits when the next transaction fails, then resumes", async () => {
await withTestHarness(async (harness) => {
const thread = seed(harness, 1200);
const notify = vi
.spyOn(harness.deps.hub, "notifyThread")
.mockImplementation(() => {});
const debug = vi
.spyOn(harness.deps.logger, "debug")
.mockImplementation((fields, message) => {
if (
message === "Thread pruning policy advanced" &&
removedEvents(fields)
)
harness.db.run(
sql`CREATE TRIGGER fail_next_prune BEFORE UPDATE ON thread_pruning_cursors BEGIN SELECT RAISE(ABORT, 'next batch failed'); END`,
);
});
await expect(
runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS),
).rejects.toThrow("next batch failed");
debug.mockRestore();
expect(notify).toHaveBeenCalledExactlyOnceWith(thread.id, [
"history-compacted",
]);
expect(harness.db.select().from(events).all()).toHaveLength(700);
harness.db.run(sql`DROP TRIGGER fail_next_prune`);
notify.mockRestore();
for (let i = 0; i < 3; i++)
await runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS);
expect(
harness.db
.select()
.from(events)
.all()
.map((row) => row.sequence),
).toEqual([1200]);
});
});
it("notifies one history compaction per thread and answers every earlier viewer with a full timeline", async () => {
await withTestHarness(async (harness) => {
const thread = seed(harness, 2400);
harness.db
.insert(events)
.values({
id: `${thread.id}-message`,
threadId: thread.id,
sequence: 2401,
scopeKind: "turn",
turnId: "turn",
type: "item/completed",
data: JSON.stringify({
item: { type: "agentMessage", id: "assistant-1", text: "Done." },
}),
createdAt: 1,
})
.run();
const before = await getTimeline(harness, thread.id);
expect(before.maxSeq).toBe(2401);
const notify = vi.spyOn(harness.deps.hub, "notifyThread");
const debug = vi.spyOn(harness.deps.logger, "debug");
await runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS);
expect(
debug.mock.calls.filter(
([fields, message]) =>
message === "Thread pruning policy advanced" &&
removedEvents(fields),
).length,
).toBeGreaterThan(1);
expect(notify).toHaveBeenCalledExactlyOnceWith(thread.id, [
"history-compacted",
]);
expect(harness.db.select().from(events).all().length).toBeLessThan(2401);
const cold = await getTimeline(harness, thread.id);
const firstViewer = await getTimeline(harness, thread.id, before.maxSeq);
const secondViewer = await getTimeline(harness, thread.id, before.maxSeq);
for (const after of [firstViewer, secondViewer]) {
expect(after.maxSeq).toBe(before.maxSeq);
expect(after.delta).toBeUndefined();
expect(after.rows).toEqual(cold.rows);
}
harness.db
.insert(events)
.values({
id: `${thread.id}-follow-up`,
threadId: thread.id,
sequence: 2402,
scopeKind: "turn",
turnId: "turn",
type: "item/completed",
data: JSON.stringify({
item: { type: "agentMessage", id: "assistant-2", text: "More." },
}),
createdAt: 2,
})
.run();
const caughtUp = await getTimeline(harness, thread.id, before.maxSeq);
expect(caughtUp.delta).toBeUndefined();
expect(caughtUp.maxSeq).toBe(2402);
const next = await getTimeline(harness, thread.id, caughtUp.maxSeq);
expect(next.delta).toEqual({ upsertRows: [] });
notify.mockRestore();
debug.mockRestore();
});
});
it("stops at the elapsed budget between advances", async () => {
await withTestHarness(async (harness) => {
seed(harness, 1200);
let elapsed = 0;
const now = vi
.spyOn(performance, "now")
.mockImplementation(() => elapsed);
const debug = vi
.spyOn(harness.deps.logger, "debug")
.mockImplementation((_fields, message) => {
if (message === "Thread pruning policy advanced") elapsed = 51;
});
try {
await runThreadPruningSweep(harness.deps, THREAD_PRUNING_SWEEP_LIMITS);
expect(
debug.mock.calls.filter(
(call) => call[1] === "Thread pruning policy advanced",
),
).toHaveLength(1);
} finally {
now.mockRestore();
debug.mockRestore();
}
});
});
it("reports an advance that overruns the elapsed budget and then yields", async () => {
await withTestHarness(async (harness) => {
seed(harness, 1200);
const now = vi
.spyOn(performance, "now")
.mockReturnValueOnce(0)
.mockReturnValueOnce(0)
.mockReturnValueOnce(0)
.mockReturnValue(75);
const warn = vi.spyOn(harness.deps.logger, "warn");
const debug = vi.spyOn(harness.deps.logger, "debug");
try {
await runThreadPruningSweep(harness.deps, THREAD_PRUNING_SWEEP_LIMITS);
expect(warn).toHaveBeenCalledWith(
expect.objectContaining({ advanceElapsedMs: 75 }),
"Slow thread pruning advance",
);
expect(debug).toHaveBeenCalledWith(
expect.objectContaining({
advances: 1,
maxAdvanceMs: 75,
reason: "budget",
}),
"Thread pruning sweep finished",
);
} finally {
now.mockRestore();
warn.mockRestore();
debug.mockRestore();
}
});
});
it("rotates durable policy progress and honors the advance budget", async () => {
await withTestHarness(async (harness) => {
const first = seed(harness, 0);
for (let i = 0; i < 100; i++)
seedThread(harness.deps, { projectId: first.projectId });
const debug = vi.spyOn(harness.deps.logger, "debug");
await runThreadPruningSweep(harness.deps, UNTIMED_SWEEP_LIMITS);
const steps = debug.mock.calls.filter(
(call) => call[1] === "Thread pruning policy advanced",
);
expect(steps.length).toBeLessThanOrEqual(64);
expect(harness.db.select().from(threadPruningCursors).all()).toHaveLength(
4,
);
const before = getNextThreadPruningPolicy(harness.db, new Set());
expect(before).not.toBeNull();
if (before === null) throw new Error("Missing next policy");
advanceThreadPruning(harness.db, before);
expect(getNextThreadPruningPolicy(harness.db, new Set())).not.toBe(
before,
);
debug.mockRestore();
});
});
});
5. Root cause
The sweep checks global maintenance idleness before selecting a policy:
while (
advances < limits.maxAdvances &&
performance.now() - startedAt < limits.elapsedBudgetMs &&
completed.size < THREAD_PRUNING_POLICIES.length
) {
const activity = getDatabaseMaintenanceActivity(deps.db);
if (!isDatabaseMaintenanceIdle(activity)) {
reason = "busy";
deps.logger.debug(
{ activity, advances },
"Thread pruning skipped while app work is active",
);
break;
}
const policy = getNextThreadPruningPolicy(deps.db, completed);
if (policy === null) break;
const advanceStartedAt = performance.now();
const result = advanceThreadPruning(deps.db, policy);
The predicate includes all active threads and pending interactions. Any nonzero count immediately exits the sweep, so safe settled threads cannot be reached:
export function isDatabaseMaintenanceIdle(
activity: DatabaseMaintenanceActivity,
): boolean {
return (
activity.activeEnvironmentProvisioningCount === 0 &&
activity.activePendingInteractionCount === 0 &&
activity.activeProjectDeletionCount === 0 &&
activity.activeThreadCount === 0 &&
activity.activeThreadProvisioningCount === 0
);
}
Simply deleting the gate would be unsafe: the existing cursor traversal selects threads by ID and rechecks only existence, without checking their activity. A cursor can also point at a thread that became busy between yielded advances.
if (cursor.currentThreadId === null) {
const next = tx
.select({ id: threads.id })
.from(threads)
.where(
threadScope === undefined
? gt(threads.id, cursor.lastThreadId)
: eq(threads.id, threadScope),
)
.orderBy(threads.id)
.limit(1)
.get();
if (!next) {
cursor.lastThreadId = "";
cursor.cycle += 1;
action = "cycle-complete";
} else {
cursor.currentThreadId = next.id;
cursor.upperSequence = getHighWaterMarks(tx, [next.id])[next.id] ?? 0;
cursor.sequence = 0;
cursor.step = 0;
cursor.latestRootSequence = 0;
cursor.latestContextSequence = 0;
Object.assign(cursor, emptyResolvedItemPruningProbe());
}
}
const threadId = cursor.currentThreadId;
if (threadId !== null) {
const thread = tx
.select({ id: threads.id })
.from(threads)
.where(eq(threads.id, threadId))
.get();
if (!thread) {
action = "missing-thread";
} else if (policy === "rate-limits") {
Advance temporarily uses busy_timeout = 0 and restores it afterward. That bounds lock waiting, not all SQLite execution time.
6. Proposed fix
Move background eligibility to the existing transactional thread traversal: select only threads that are neither active nor starting and have no pending/resolving interaction, and recheck that eligibility before every resumed deletion batch. Skipped threads must become eligible again on a later cursor cycle. Leave live per-thread pruning behavior unchanged. Retain the existing global pause during project deletion or environment provisioning and leave database-vacuum gates and limits unchanged. Exercise activity changes between advances, interaction lifecycle states, and deferred-thread recovery through regression tests.
7. Verification
The same agent repeated the reproduction in a second clean temporary clone at df913a79dc687341d9bec06e483ff545376225de, with a fresh frozen dependency installation and fresh harness data directories. It applied only the same authored test patch, then ran the exact Turbo command from section 4. The second run again reports 4 failed | 6 skipped, with the same expected [3] versus actual [1, 2, 3] assertion. This is a repeated check by the same agent, not independent verification. No report correction was needed.
8. Related issues
#2534 concerns event-loop blocking by unbounded pruning, rather than starvation from global idleness. The proposed repair must preserve existing bounded batches and yields. GitHub cross-reference metadata and an open-PR search found no linked open pull request at investigation time.
9. Appendix
Both complete test logs are linked above; checkout-specific filesystem prefixes are replaced with symbolic checkout names, without changing assertion output. Source permalinks were checked against the recorded base commit. No visual evidence is needed for this nonvisual database-maintenance defect. The issue was treated only as untrusted claims: no issue-provided command, linked script, external attachment, or pull-request branch was executed. Production size and performance claims remain unverified.
Reads: gh repo view get-bb/bb --json nameWithOwner,isPrivate gh issue view 5005 --repo get-bb/bb --json number,title,body,labels,comments gh pr list --repo get-bb/bb --state open --search 5005 --json number,url,title git fetch origin main git rev-parse origin/main git log --oneline -- packages/db/src/data/thread-pruning.ts apps/server/src/services/system/thread-pruning-sweep.ts Reproduction: frozen install plus exact section-4 Turbo command, in each clean checkout.