Repository navigation
Description
Summary
In a long-running thread, sending a message while a turn is active (a steer, bb thread tell, a queued send, or a child's report to its parent) blocks the server's event loop for seconds before the message is recorded. The check that #6420 added to queue sends during a provider-started compaction, isStoredTurnProviderCompactionRunning, looks for the active turn's latest compaction item with a query SQLite answers by walking the thread's entire event history through events_thread_sequence_idx (thread_id=?). Expected: the check reads only the active turn's events, so its cost no longer grows with the thread's history.
Versions and environment
- bb 0.48.1 (desktop app), macOS 27.0.1, Apple M5 Pro, 18 logical CPUs, 64 GiB
- Regression from Queue messages sent while Pi runs an extension-started compaction #6420 (
7421e656d6), first released in desktop v0.48.0. Still present onmainat916d684ac2. - Seen in a claude-code thread (Claude Code 2.1.314). The check is provider-agnostic, so the provider does not matter.
- Local server; the database is 33 GB with 33M event rows. The affected thread has 348,448 retained events and 5,798 turns. The machine was heavily loaded (one-minute load average 1.1 to 2.1 times the CPU count), which stretches wall time but does not cause the scan.
Steps to reproduce
Closest faithful repro without a real long thread, at the code path. Both run against a migrated database built by @bb/db's own migrations.
Query plan (unit test). Add the case below to the slow query index plans block of packages/db/test/query-plans.test.ts, import isStoredTurnProviderCompactionRunning from ../src/data/events.js, and run pnpm exec vitest run test/query-plans.test.ts -t "running provider compaction" in packages/db. The PR that fixes this adds the same case. On main the behaviour assertions pass and the plan assertion fails:
Test case
it("finds a turn's running provider compaction through the turn index", () => {
const { db, thread } = setup();
const compactionEvent = (args: {
sequence: number;
turnId: string;
type: "item/started" | "item/completed";
itemId: string;
parentToolCallId?: string;
}) => ({
threadId: thread.id,
sequence: args.sequence,
type: args.type,
scope: turnScope(args.turnId),
itemId: args.itemId,
itemKind: "contextCompaction" as const,
parentToolCallId: args.parentToolCallId ?? null,
data: JSON.stringify({
providerThreadId: "provider-plan",
item: { type: "contextCompaction", id: args.itemId },
}),
});
insertEvents(db, noopNotifier, [
compactionEvent({
sequence: 1,
turnId: "turn-running",
type: "item/started",
itemId: "compaction-running",
}),
compactionEvent({
sequence: 2,
turnId: "turn-completed",
type: "item/started",
itemId: "compaction-completed",
}),
compactionEvent({
sequence: 3,
turnId: "turn-completed",
type: "item/completed",
itemId: "compaction-completed",
}),
compactionEvent({
sequence: 4,
turnId: "turn-nested",
type: "item/started",
itemId: "compaction-nested",
parentToolCallId: "call-child-agent",
}),
{
threadId: thread.id,
sequence: 5,
type: "turn/input/accepted",
scope: turnScope("turn-accepted"),
itemId: null,
itemKind: null,
parentToolCallId: null,
data: JSON.stringify({ providerThreadId: "provider-plan" }),
},
compactionEvent({
sequence: 6,
turnId: "turn-accepted",
type: "item/started",
itemId: "compaction-accepted",
}),
]);
const isRunning = (turnId: string) =>
isStoredTurnProviderCompactionRunning(db, {
threadId: thread.id,
turnId,
});
const captured = captureStatements(db, () => {
expect(isRunning("turn-running")).toBe(true);
});
expect(isRunning("turn-completed")).toBe(false);
expect(isRunning("turn-nested")).toBe(false);
expect(isRunning("turn-accepted")).toBe(false);
expect(isRunning("turn-without-compaction")).toBe(false);
expect(captured).toHaveLength(2);
const [compactionQuery] = captured;
expect(queryPlanDetails({ db, ...compactionQuery! })).toContain(
"events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?)",
);
for (const query of captured) {
expectNoThreadOnlyEventSeek(queryPlanDetails({ db, ...query }));
}
db.$client.close();
});AssertionError: expected 'SEARCH events USING INDEX events_thre…' to contain 'events_thread_turn_type_item_sequence…'
Expected: "events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?)"
Received: "SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)"
bb never runs ANALYZE, so real databases have no sqlite_stat1 either and get the same plan: EXPLAIN QUERY PLAN of the statement on the 33 GB database above gives the same SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?).
Timing (synthetic database).
- In a bb checkout at
916d684ac2with dependencies installed:cd packages/db. - Save the script below as
repro-compaction-admission-scan.mtsanywhere. - Run
node --conditions=source --import tsx /path/to/repro-compaction-admission-scan.mts --repo <checkout> --db /tmp/bb-compaction-repro.db --events 350000 --neighbours 3.
The script migrates a fresh database at the given path, seeds one 350,000-event thread whose turns occasionally compact, interleaved with three neighbour threads (1.4M rows), and times the statement main emits against the same statement pinned to events_thread_turn_type_item_sequence_idx. It checks that both return the same row, and deletes the database afterwards. Seeding takes 20 to 50 seconds. --large-turn-items N adds two provider-started turns of N items at the tip, to time a large current turn.
repro-compaction-admission-scan.mts
// Synthetic repro for the active-thread send-admission scan in
// isStoredTurnProviderCompactionRunning (packages/db/src/data/events.ts).
//
// Builds a fresh on-disk bb database with the real migrations, seeds one long
// thread (plus interleaved neighbour threads so its rows are spread across
// pages, as in a long-lived database), then times:
// main - the statement main emits (the shape logged by the server)
// fixed - the same statement with INDEXED BY the turn index
// function - the real isStoredTurnProviderCompactionRunning from this tree
// reorder - the alternative fix: the turn/input/accepted probe alone
// for a user turn (accepted input) and an open provider-started turn (none).
//
// Usage (from a bb checkout's packages/db, any data under /tmp):
// node --conditions=source --import tsx repro-compaction-admission-scan.mts \
// --repo <bb checkout> --db /tmp/bb-compaction-repro.db \
// [--events 350000] [--neighbours 1] [--runs 5] [--payload-bytes 220]
// [--ordering-context] [--large-turn-items 5000]
// --ordering-context also times listTimelineOrderingContext over the whole
// thread, the query the timeline build reruns after each new turn request.
// --large-turn-items N adds two provider-started turns of N items each at the
// tip, one without a compaction and one ending in a running compaction, to
// measure the pinned plan's cost (reading and sorting the whole turn) on a
// large current turn, where main's backward walk can stop early.
// It refuses to touch an existing file, and never opens ~/.bb.
import { existsSync, rmSync } from "node:fs";
import { resolve } from "node:path";
import { parseArgs } from "node:util";
import { performance } from "node:perf_hooks";
const { values } = parseArgs({
options: {
repo: { type: "string" },
db: { type: "string" },
events: { type: "string", default: "350000" },
neighbours: { type: "string", default: "1" },
runs: { type: "string", default: "5" },
"payload-bytes": { type: "string", default: "220" },
"ordering-context": { type: "boolean", default: false },
"large-turn-items": { type: "string", default: "0" },
keep: { type: "boolean", default: false },
},
});
if (!values.repo || !values.db) {
throw new Error("--repo and --db are required");
}
const dbPath = resolve(values.db);
if (dbPath.includes("/.bb/") || existsSync(dbPath)) {
throw new Error(`Refusing to use ${dbPath}: it exists or is under ~/.bb`);
}
const targetEvents = Number(values.events);
const neighbourCount = Number(values.neighbours);
const runs = Number(values.runs);
const largeTurnItems = Number(values["large-turn-items"]);
const bbDb = await import(resolve(values.repo, "packages/db/src/index.ts"));
const {
createConnection,
migrate,
noopNotifier,
upsertHost,
createProject,
createThread,
isStoredTurnProviderCompactionRunning,
listTimelineOrderingContext,
} = bbDb;
const db = createConnection(dbPath);
migrate(db);
const sqlite = db.$client;
const host = upsertHost(db, noopNotifier, { name: "repro-host" });
const { project } = createProject(db, noopNotifier, {
name: "repro-project",
source: { type: "local_path", hostId: host.id, path: "/tmp/repro" },
});
const target = createThread(db, noopNotifier, {
projectId: project.id,
providerId: "claude-code",
});
const neighbours = Array.from({ length: neighbourCount }, () =>
createThread(db, noopNotifier, {
projectId: project.id,
providerId: "codex",
}),
);
const insert = sqlite.prepare(`INSERT INTO events
(id, thread_id, scope_kind, turn_id, sequence, type, item_id, item_kind,
parent_tool_call_id, data, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)`);
const nextSequence = new Map<string, number>();
let idCounter = 0;
const payload = JSON.stringify({
text: "x".repeat(Number(values["payload-bytes"])),
});
function append(
threadId: string,
turnId: string | null,
type: string,
itemKind: string | null = null,
): void {
const sequence = (nextSequence.get(threadId) ?? 0) + 1;
nextSequence.set(threadId, sequence);
idCounter += 1;
insert.run(
`evt_repro_${idCounter}`,
threadId,
turnId === null ? "thread" : "turn",
turnId,
sequence,
type,
itemKind === null ? null : `item_${idCounter}`,
itemKind,
payload,
idCounter,
);
}
const ITEMS_PER_TURN = 28;
function appendTurn(
threadId: string,
turnId: string,
args: {
acceptedInput: boolean;
compaction: boolean | "running";
complete: boolean;
items?: number;
},
): number {
let written = 0;
const add = (...rest: [string, string?]) => {
append(threadId, turnId, rest[0], rest[1] ?? null);
written += 1;
};
if (args.acceptedInput) {
append(threadId, null, "client/turn/requested");
written += 1;
}
add("turn/started");
if (args.acceptedInput) add("turn/input/accepted");
for (let item = 0; item < (args.items ?? ITEMS_PER_TURN); item += 1) {
const kind = item % 3 === 0 ? "agentMessage" : "commandExecution";
add("item/started", kind);
add("item/completed", kind);
}
if (args.compaction !== false) {
add("item/started", "contextCompaction");
if (args.compaction !== "running") add("item/completed", "contextCompaction");
}
if (args.complete) add("turn/completed");
return written;
}
const seedStart = performance.now();
sqlite.transaction(() => {
let written = 0;
let turn = 0;
while (written < targetEvents) {
turn += 1;
written += appendTurn(target.id, `turn_t_${turn}`, {
acceptedInput: turn % 40 !== 0,
compaction: turn % 6 === 0,
complete: true,
});
for (const neighbour of neighbours) {
appendTurn(neighbour.id, `turn_n_${neighbour.id}_${turn}`, {
acceptedInput: true,
compaction: false,
complete: true,
});
}
}
appendTurn(target.id, "turn_user_last", {
acceptedInput: true,
compaction: false,
complete: true,
});
appendTurn(target.id, "turn_provider_open", {
acceptedInput: false,
compaction: false,
complete: false,
});
if (largeTurnItems > 0) {
appendTurn(target.id, "turn_large_no_compaction", {
acceptedInput: false,
compaction: false,
complete: true,
items: largeTurnItems,
});
appendTurn(target.id, "turn_large_running_compaction", {
acceptedInput: false,
compaction: "running",
complete: false,
items: largeTurnItems,
});
}
})();
const seedMs = performance.now() - seedStart;
const targetRows = sqlite
.prepare("SELECT count(*) AS n FROM events WHERE thread_id = ?")
.get(target.id).n;
const totalRows = sqlite.prepare("SELECT count(*) AS n FROM events").get().n;
const MAIN_SQL = `SELECT type FROM events
WHERE thread_id = ? AND turn_id = ?
AND type IN (?, ?) AND item_kind = ?
AND parent_tool_call_id IS NULL
ORDER BY sequence DESC LIMIT ?`;
const FIXED_SQL = MAIN_SQL.replace(
"FROM events",
"FROM events INDEXED BY events_thread_turn_type_item_sequence_idx",
);
const ACCEPTED_SQL = `SELECT sequence FROM events
WHERE thread_id = ? AND turn_id = ? AND type = ? LIMIT ?`;
function plan(sql: string): string {
return sqlite
.prepare(`EXPLAIN QUERY PLAN ${sql}`)
.all(target.id, "t", "item/started", "item/completed", "contextCompaction", 1)
.map((row: { detail: string }) => row.detail)
.join(" | ");
}
function median(samples: number[]): number {
const sorted = [...samples].sort((a, b) => a - b);
return sorted[Math.floor(sorted.length / 2)]!;
}
function time(run: () => unknown): { medianMs: number; maxMs: number } {
const samples: number[] = [];
for (let index = 0; index < runs; index += 1) {
const start = performance.now();
run();
samples.push(performance.now() - start);
}
return { medianMs: median(samples), maxMs: Math.max(...samples) };
}
const mainStatement = sqlite.prepare(MAIN_SQL);
const fixedStatement = sqlite.prepare(FIXED_SQL);
const acceptedStatement = sqlite.prepare(ACCEPTED_SQL);
const compactionParams = (turnId: string) => [
target.id,
turnId,
"item/started",
"item/completed",
"contextCompaction",
1,
];
const results: Record<string, unknown> = {};
const measuredTurnIds = [
"turn_user_last",
"turn_provider_open",
...(largeTurnItems > 0
? ["turn_large_no_compaction", "turn_large_running_compaction"]
: []),
];
for (const turnId of measuredTurnIds) {
const fixedRow = fixedStatement.get(...compactionParams(turnId));
const mainRow = mainStatement.get(...compactionParams(turnId));
if ((fixedRow?.type ?? null) !== (mainRow?.type ?? null)) {
throw new Error(`Fixed and main rows differ for ${turnId}`);
}
const hasAccepted =
acceptedStatement.get(target.id, turnId, "turn/input/accepted", 1) !==
undefined;
results[turnId] = {
acceptedInput: hasAccepted,
main: time(() => mainStatement.get(...compactionParams(turnId))),
fixed: time(() => fixedStatement.get(...compactionParams(turnId))),
function: time(() =>
isStoredTurnProviderCompactionRunning(db, {
threadId: target.id,
turnId,
}),
),
reorder: hasAccepted
? time(() =>
acceptedStatement.get(target.id, turnId, "turn/input/accepted", 1),
)
: "accepted probe misses; reorder still runs the main statement",
};
}
if (values["ordering-context"]) {
const maxSeq = nextSequence.get(target.id)!;
let rowCount = 0;
const timing = time(() => {
rowCount = listTimelineOrderingContext(db, {
threadId: target.id,
sequenceStart: 0,
maxSeq,
}).length;
});
results.orderingContext = { ...timing, rows: rowCount };
}
console.log(
JSON.stringify(
{
sqliteVersion: sqlite.prepare("SELECT sqlite_version() AS v").get().v,
hasSqliteStat1:
sqlite
.prepare(
"SELECT count(*) AS n FROM sqlite_master WHERE name = 'sqlite_stat1'",
)
.get().n > 0,
targetRows,
totalRows,
seedSeconds: Math.round(seedMs / 100) / 10,
runsPerMeasurement: runs,
mainPlan: plan(MAIN_SQL),
fixedPlan: plan(FIXED_SQL),
results,
},
null,
2,
),
);
sqlite.close();
if (!values.keep) {
for (const suffix of ["", "-wal", "-shm"]) {
rmSync(`${dbPath}${suffix}`, { force: true });
}
}Expected vs actual
Synthetic database, warm page cache, medians of 5 runs on the loaded machine above:
rows/event turn shape main pinned to turn index
220 B user turn (accepted input) 52.1 ms 0.03 ms
220 B provider-started open turn 51.4 ms 0.03 ms
1 KB user turn (accepted input) 180 ms 0.03 ms
1 KB provider-started open turn 210 ms 0.07 ms
plan (main): SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)
plan (pinned): SEARCH events USING INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?) | USE TEMP B-TREE FOR ORDER BY
The synthetic numbers are a warm-cache CPU floor. On the real database the rows are about 1 KB on average, and the logged walks took about 6 times their CPU time. I take that to be reads from disk and waiting on the loaded machine, but I did not measure page-cache residency or I/O, so that cause is an inference. Measured on the real database, from the server's own slow-query log, same statement shape:
2026-11-01T06:07:15.448Z Slow DB query durationMs 9153.7 cpuDurationMs 1430.2
2026-11-01T06:10:29.565Z Slow DB query durationMs 16087.8 cpuDurationMs 2491.2
2026-11-01T06:10:29.830Z Event loop stalled maxDelayMs 16366.2
inFlightWorkAtObservation: ... | POST /api/v1/threads/thr_m5frcbr4p2/send
2026-11-01T06:54:26.941Z Slow DB query durationMs 17993.4 cpuDurationMs 3208.5
sql: select "type" from "events" where (("events"."thread_id" = ? and "events"."turn_id" = ?) and "events"."type" in (?, ?) and "events"."item_kind" = ? and "events"."parent_tool_call_id" is null) order by "events"."sequence" desc limit ?
The user's steer in that send was recorded 4 s after the 06:10 stall ended, and accepted by the provider 14 ms after it was recorded. The time is spent before the message is stored, not in the provider.
Expected: the lookup reads only the active turn's lifecycle rows, which on this thread is at most 505 rows in any turn (20 on average).
I did not time the turn-bounded query against the real database, which would mean running queries against its data rather than only explaining them. A larger synthetic run reproduces the seconds without it: an 8 GB database (4.8M events of about 1 KB, 350,000 in the target thread) on a Linux VM with 4 GiB of RAM, page cache dropped before each sample. There the lookup took a median of 34.8 s on main and 21 ms pinned (n=8), and an HTTP send into the active provider-started turn took a median of 503 ms on main and 22 ms pinned with a warm cache (12 alternating pairs).
Evidence
- Why it walks: the query filters
thread_id,turn_id,type IN ('item/started', 'item/completed'),item_kindandparent_tool_call_id IS NULL, ordered bysequence DESC LIMIT 1. With no statistics SQLite prefers the unique(thread_id, sequence)index because it returns rows inORDER BYorder, then reads the table row for every event in the thread, newest first, until one matches. Most turns contain no compaction, so the usual case reads the whole history. - Code:
isStoredTurnProviderCompactionRunning, called fromisManualCompactionActive. Callers on the send paths:dispatch-attempt.ts#L557(non-start sends into a thread with an active turn),queued-messages.ts#L584and#L670(queued sends), andparent-system-messages.ts#L245, which runs it inside the write transaction that records a child's report to its parent. - A selective index already exists:
events_thread_turn_type_item_sequence_idxon(thread_id, turn_id, type, item_id, sequence). - Counts on the affected thread, read-only: 348,448 events; 5,798 turns; at most 505
item/started/item/completedrows in one turn; 1,876contextCompactionlifecycle rows in the thread's history. - With this lookup pinned to the turn index, a sweep of every
SELECToneventsduring a test-harness steer (active turn with and without accepted input) found no other statement that walks the whole thread. Two thread-prefix seeks remain, both bounded:getLastStoredTurnRequestEventstops at the newest turn request (at most 1,983 rows back on this thread), and the thread-state lookup seeks the partialevents_thread_state_thread_sequence_idx, which holds only goal and extension-state events. - One older lookup on the same path reads more than the turn, and is separate from this regression.
getStoredTurnRequestEventForTurn, whichisManualCompactionActivehas called since Add manual context compaction across providers #1152, seeksevents_thread_type_sequence_idx (thread_id=? AND type=?)for the turn'sturn/input/acceptedrow. In a user turn the newest such row is the turn's own, so it stops at once. In a provider-started turn, which has none, it reads every accepted-input row in the thread (7,718 on this thread now). In the synthetic run above, with about 5,800 such rows, that took 8 ms warm and 0.9 s cold in a profiled send (profiler overhead included). - Measurement:
durationMsis wall time andcpuDurationMsis the executing thread's CPU from the server's slow-query logger (packages/db/src/connection.ts). Synthetic timings areperformance.now()around oneget().
What you ruled out
- Not the provider: the logged steers were accepted 4 to 16 ms after they were stored (22 steers in the sampled window).
- Not the Codex Fast setting: the thread is claude-code and that setting only selects the service tier.
- Not WebSocket compression or timeline pushes: the stall is a synchronous query before the send is stored.
- Not Multi-ID timeline parent lookup scans every event in long threads #5598, fix(db): seek missing timeline parents by item #5599 or fix(db): seek background-task and request-outcome events by index #5655: those fixed other
eventslookups with the same plan shape. This one was added afterwards, in Queue messages sent while Pi runs an extension-started compaction #6420. - Not Latest timeline page decodes every event of an open turn on each build, bypassing timelineWindowEventBudget #4674 or Timeline response cache admits nothing above 200 rows, so identical requests each rebuild the projection #3951: those are timeline-build costs. Slow timeline builds in this thread are a separate report.
- Checking
turn/input/acceptedbefore the compaction lookup is not enough on its own. It returns the same answer, but a turn with no accepted input still walks the history, and provider-started turns are common: 152 of the 5,798 turns on this claude-code thread have none. - Still present on
mainat916d684ac2.
Suggested priority and effort (optional)
Medium to high: every send into an active long thread pays it, including child reports into a lead thread. No data is lost, but the server stops serving everything else for the duration. Effort low. A proposed fix pins the existing turn index with INDEXED BY events_thread_turn_type_item_sequence_idx, the same approach as #5599 and #5655, and adds a query-plan test. It leaves #6420's predicate unchanged. Its costs (a sort over the current turn's lifecycle rows, and a loud no such index if the index is ever dropped) are in the PR.
Checks
- I reproduced this on the latest release or on
main, or I say above that I could not. - I searched open and closed issues for the same problem.
- If an agent wrote this, the body ends with
> AGENT GENERATED. The investigation ran in a private bb thread (thr_u8ijveakxs) that cannot be linked, so this issue carries its report in full instead: the test case, the timing script, the log excerpts and the code permalinks above.
AGENT GENERATED
Activity
bb-slop-cop commentedon Nov 1, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotthreads,perf.confirmed-repro.916d684ac2; 100,000 historical events raise the warm lookup to ~34 ms versus ~0.02–0.03 ms using the existing turn index. The unchanged query-plan suite passes 49/49. Production multi-second timings were not independently measured.Seek a turn's provider compaction through the turn index (get-bb#6787)