#5598 · Parent resolution uses a thread-wide access path
Verdict: REPRODUCED · Root-cause confidence: high
1. TL;DR
Opening a timeline can require looking up parents that are not in its current window. The database lookup for several parent IDs returns correct rows, but SQLite chooses an index that searches only by thread, not by item ID. That access path can visit the thread's entire event history even when the requested parents have no qualifying rows. A new test of the real exported lookup, using the real migrated SQLite schema, fails at the query-plan assertion in two clean trusted checkouts; its preceding row-content and ordering assertions pass. This proves the access-path defect, not the reported multi-second timing or every cause of server stalls.
2. Claims vs findings
| Claim | Status | Evidence |
|---|---|---|
| Multiple missing parent IDs can use a thread-only lookup. | Verified | Both runs capture SQL from the exported function and explain it with its actual bound arguments: events_thread_sequence_idx (thread_id=?). |
| An existing thread-and-item partial index is available. | Verified | Trusted schema and migration define events_delegating_item_lookup_idx on thread_id, item_id, sequence, item_kind for toolCall/delegation rows. |
| Missing or non-delegating parents need not produce results. | Verified | The test requests absent and commandExecution IDs alongside real toolCall and delegation parents. Only the latter lifecycle rows are returned, in sequence order and from the requested thread. |
| The defect applies to the ordinary timeline path, not only a workflow plugin. | Verified in source | The server timeline builder calls this function for collected missing parents with no workflow-specific gate. |
| A particular desktop/provider combination experiences about nine seconds of delay. | Unverified | No desktop, provider, private thread, or production database was used. No latency claim is made by this report. |
| Exactly two IDs always trigger this plan; statistics never change it. | Not established | This reproduction requests four distinct nonempty IDs in a migrated database without ANALYZE. SQLite planner choices may vary with statistics and workload. |
3. Environment
- Trusted repository: public get-bb/bb, origin/main at
4363ba27d6f942d6b42ae61c8f85800e756b9085; package version 0.46.1. - Linux 4.19.0-gvisor, x86_64; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.1; better-sqlite3 12.10.0; bundled SQLite 3.53.1.
- Two fresh source clones of the trusted repository, named source and verify under a temporary work directory. Neither linked PR code nor linked issue scripts were executed.
- Real SQLite databases created by createMigratedConnection(): the production migrations build a template, then each case receives its own database copy. No database mocks, dependency additions, statistics updates, dev server, ports, providers, account credentials, or user runtime data.
4. Minimal reproduction
The following patch is newly authored for this investigation from trusted repository evidence. It adds a test to the existing query-plan harness, rather than replacing the exported query with a hand-written approximation. The test protects the item-seek access-path contract and returned-row semantics. Existing neighboring tests do not exercise this multi-ID lookup. It needs no production test seam.
- Clone the public repository into a new directory, check out the recorded trusted commit, and install/build normally:
git clone https://github.com/get-bb/bb.git source cd source git checkout --detach 4363ba27d6f942d6b42ae61c8f85800e756b9085 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build
- Save the complete patch below as
regression.patchoutside the checkout, then apply it:git apply ../regression.patch pnpm exec turbo run test --filter=@bb/db -- test/query-plans.test.ts -t 'seeks multiple missing timeline parents'
- Expect a nonzero exit caused only by the plan assertion. Both output-cap cases first verify returned sequence numbers, item IDs/kinds/types, thread IDs, and JSON data. They then explain the SQL actually executed by the lookup, with the captured bound parameters. No result is synthesized by a database mock.
Complete regression patch
diff --git a/packages/db/test/query-plans.test.ts b/packages/db/test/query-plans.test.ts
index 4131da77a..3062aa9ec 100644
--- a/packages/db/test/query-plans.test.ts
+++ b/packages/db/test/query-plans.test.ts
@@ -33,6 +33,7 @@ import {
listStoredConversationOutlineEventRows,
listStoredEventRows,
listStoredEventRowsByParentToolCallIds,
+ listStoredDelegatingItemRowsByItemIds,
listStoredTurnCompletedKeys,
listTodoSnapshotEventRowsForThread,
} from "../src/data/events.js";
@@ -755,6 +756,86 @@ describe("slow query index plans", () => {
db.$client.close();
});
+ it.each([null, 32_000])(
+ "seeks multiple missing timeline parents by item ID with output cap %s",
+ (maxInlineOutputChars) => {
+ const { db, project, thread } = setup();
+ try {
+ const otherThread = createThread(db, noopNotifier, {
+ projectId: project.id,
+ providerId: "codex",
+ });
+ const fixtures = [
+ [9, "parent-tool", "toolCall", "item/completed"],
+ [3, "parent-delegation", "delegation", "item/started"],
+ [1, "parent-tool", "toolCall", "item/started"],
+ [7, "parent-delegation", "delegation", "item/completed"],
+ [5, "command-parent", "commandExecution", "item/completed"],
+ ] as const;
+ insertEvents(
+ db,
+ noopNotifier,
+ [thread.id, otherThread.id].flatMap((threadId) =>
+ fixtures.map(([sequence, itemId, itemKind, type]) => ({
+ threadId,
+ sequence,
+ scope: threadScope(),
+ type,
+ itemId,
+ itemKind,
+ parentToolCallId: null,
+ data: JSON.stringify({ item: { id: itemId, type: itemKind } }),
+ })),
+ ),
+ );
+
+ const [query] = captureStatements(db, () => {
+ const rows = listStoredDelegatingItemRowsByItemIds(db, {
+ threadId: thread.id,
+ itemIds: [
+ "parent-delegation",
+ "command-parent",
+ "parent-tool",
+ "absent-parent",
+ "parent-tool",
+ "",
+ ],
+ maxInlineOutputChars,
+ });
+ expect(
+ rows.map((row) => [
+ row.sequence,
+ row.itemId,
+ row.itemKind,
+ row.type,
+ row.threadId,
+ row.data,
+ ]),
+ ).toEqual(
+ [fixtures[2], fixtures[1], fixtures[3], fixtures[0]].map(
+ ([sequence, itemId, itemKind, type]) => [
+ sequence,
+ itemId,
+ itemKind,
+ type,
+ thread.id,
+ JSON.stringify({ item: { id: itemId, type: itemKind } }),
+ ],
+ ),
+ );
+ });
+ if (!query) {
+ throw new Error("Expected the missing timeline parent lookup SQL");
+ }
+ expect(queryPlanDetails({ db, ...query })).toMatch(
+ /SEARCH events USING (?:COVERING )?INDEX events_delegating_item_lookup_idx \(thread_id=\? AND item_id=\?\)/u,
+ );
+ } finally {
+ db.$client.close();
+ }
+ },
+ );
+
it("scans background-task history once without a completed-set join", () => {
const { db, thread } = setup();
Expected vs actual
Expected plan includes an item-constrained search (a temporary sort to restore global sequence order is acceptable):
SEARCH events USING INDEX events_delegating_item_lookup_idx (thread_id=? AND item_id=?)
Actual plan, verbatim in both runs:
SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)
First-run Vitest output excerpt:
FAIL |@bb/db| test/query-plans.test.ts > slow query index plans > seeks multiple missing timeline parents by item ID with output cap null
FAIL |@bb/db| test/query-plans.test.ts > slow query index plans > seeks multiple missing timeline parents by item ID with output cap 32000
AssertionError: expected 'SEARCH events USING INDEX events_thre…' to match /SEARCH events USING (?:COVERING )?IN…/u
+ Received:
"SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)"
Test Files 1 failed (1)
Tests 2 failed | 43 skipped (45)
There is no visual component, so screenshots are not applicable. All reproduction code and decisive output are embedded here; repository publishing policy forbids separate test files, logs, or diffs on the public reports site.
5. Root cause
The timeline caller collects unresolved parent IDs and calls listStoredDelegatingItemRowsByItemIds without restricting the lookup to the visible sequence window. That unrestricted history lookup is necessary to find older parents, but it must seek the requested item IDs.
The exported lookup deduplicates IDs, discards empty IDs, and uses this shape:
FROM events
WHERE thread_id = ?
AND item_id IN (...)
AND item_kind IN ('toolCall', 'delegation')
AND type IN ('item/started', 'item/completed')
ORDER BY sequence
With several item IDs, the planner chooses events_thread_sequence_idx, which delivers sequence order but constrains only thread_id. Filtering item IDs then happens while walking that thread's index entries. If none of the requested IDs qualify, it still must traverse the whole thread range to establish absence; the SQL has no LIMIT to bound that work.
The existing partial index instead begins with thread_id and item_id, followed by sequence and item_kind, and uses the same literal kind predicate. That access path can seek each requested ID but may need a temporary sort across matches. The emitted EXPLAIN result demonstrates the selected access path; it is not a wall-clock benchmark or a count of VM steps.
The connection uses better-sqlite3, and this query ends in a synchronous .all(). Consequently, extra work occurs on the executing server thread. The implication for event-loop responsiveness follows from the synchronous call; unrelated-request delays were not measured here.
6. Proposed fix from repository evidence
Constrain this narrow parent-resolution query to the existing delegating-item index while preserving the literal partial-index predicate, lifecycle-type filtering, deduplication, sequence ordering, and inline output cap. This repository already uses INDEXED BY events_delegating_item_lookup_idx for another delegating-item query. For a raw indexed FROM expression, use the existing SQL row projection helper so Drizzle retains the stored-row shape and capped-output expression. No index, migration, wire field, or caller contract needs to change.
Risks: an unavailable or incompatible required index makes preparation fail, and requests for many matching IDs could have a different optimal plan. Keep a real migrated-database plan regression and row-semantic assertions for capped and uncapped output. A broader performance claim requires a separate representative workload measurement.
7. Linked PR: #5599 (static review only)
PR #5599 was open and draft during investigation. GitHub metadata explicitly lists #5598 in its closing-issue references. Therefore the autopilot did not make or push a production fix and did not open a duplicate PR.
The diff changes only the database lookup and its query-plan test: it requires the existing partial index, uses the existing SQL projection helper, and adds a migrated-database test that checks multi-ID row results and the plan with a numeric cap. Statically, those changes target the reproduced root cause rather than a timeline cache or UI workaround.
Findings: no demonstrated blocker in the small production diff. The raw indexed-table projection is accounted for by an existing helper in trusted main. Limit: this is not an execution-based approval; neither the PR branch nor its test was checked out or run, and its reported green checks are not claimed as our verification. Our newly authored red regression was run only on trusted main. The large-match-set crossover and released-app timing remain unmeasured.
8. Verification: second clean reproduction by the same agent
A second fresh clone named verify was checked out at exactly 4363ba27d6f942d6b42ae61c8f85800e756b9085. Its working tree was clean before applying only this investigation's regression patch. It received its own frozen dependency install and fresh migrated-database test process. There are no ports or persistent data directories to reuse in this database-only test. This is a repeat by the same agent, not an independent review.
git clone https://github.com/get-bb/bb.git verify cd verify git checkout --detach 4363ba27d6f942d6b42ae61c8f85800e756b9085 git status --porcelain git apply ../regression.patch pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run test --filter=@bb/db -- test/query-plans.test.ts -t 'seeks multiple missing timeline parents'
The same two cases reached the plan assertion with correct returned rows and failed with the same thread-only search:
"SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)"
Test Files 1 failed (1)
Tests 2 failed | 43 skipped (45)
Duration 8.48s (transform 2.81s, setup 0ms, import 3.59s, tests 51ms, environment 0ms)
Result: the second run supports the same verdict and root cause. Report correction: none. The second clone did not execute linked PR code or reuse a user database.
9. Related issues
Repository search also surfaced #5192, a broader server-stall investigation. This report establishes only the specific parent-query access path, not all timeline or maintenance costs. The explicitly linked open PR #5599 is why no new fix PR is safe or necessary.
10. Appendix
- Trusted origin/main resolved to the recorded base; production code stayed unchanged in both clones.
- Normal frozen installation succeeded in each clone. Initial build on trusted main: 66 successful Turbo tasks, 4 cached, 1m36.583s.
- First focused run: two intended plan failures, 43 skipped, 8.24s. Second run: the same failures, 43 skipped, 8.48s. Neither failure was a setup, migration, module-resolution, or row-content failure.
pnpm exec turbo run typecheck --filter=@bb/dbpassed after adding the new regression.git diff --checkpassed. The local investigation patch is one text file, 81 additions and zero deletions; it was not committed or pushed to get-bb/bb.- Other relevant inspection commands:
git fetch origin main,git rev-parse HEAD,git log -- packages/db/src/data/events.ts,gh pr view 5599 --repo get-bb/bb, and read-onlygh pr diff 5599 --repo get-bb/bb. No commands from the issue were executed. - Trust note: issue text and PR contents were treated solely as untrusted claims. No external URLs from issue content were fetched; no supplied script, patch, test, or branch was executed. PR metadata and diff were read as untrusted data. Only trusted main and this investigation's own new regression executed. No production instances, credentials, or unrelated files were read.
- Reproduction label:
confirmed-repro. Classification: Bug / Medium / Low / threads, perf. These were missing and were filled; no existing values were replaced.
> AGENT GENERATED