#5234 · Latest-state lookup is already linear on main
Verdict: ALREADY FIXED · Root-cause confidence: high
1. TL;DR
The report describes long server pauses during thread-list loading when threads have unrelated extension history but no goals. The earlier database query correlated a latest-state search with every state-event row, allowing repeated parsing of the same history. Trusted main already replaces that outer event scan with one descending candidate search per requested thread. The repair is commit ef570298ef45b39d837da0fcab0fb94ea086783b, merged in #4931 on October 5, 2026 at 21:04:53 UTC, before this issue was created on October 8. Two fresh checkouts of current main inspect each synthetic unrelated payload once and return no goals, so another patch would duplicate an existing fix.
2. Claims vs findings
| Claim | Finding | Evidence |
|---|---|---|
| Goal reads repeatedly rescan unrelated state history on current main. | Refuted for inspected main | The eight-thread fixture performs exactly 768 JSON extractions for 768 events and 3,072 for 3,072 events, twice from fresh databases. |
| The old correlated MAX lookup can repeat work per outer event. | Verified statically | Trusted main's merged repair diff shows the previous event-correlated MAX removed. No historical checkout or issue-provided SQL was executed. |
| No goal is necessary to exercise the slow path. | Verified fixture shape | Every inserted event has an unrelated extension kind; both current-source lookups return zero rows. |
| A missing index is the cause. | Not supported | Current query pins the existing partial index. Repository plan coverage passes. |
| The installed desktop binary stalls for seconds and contains the old query. | Unverified here | No production database, installation, source map, or server log was accessed. This report tests Linux source main, not the reporter's macOS binary. |
3. Environment
- Trusted origin:
https://github.com/get-bb/bb.git; detached main atff94848832b22c3281ffc4b5b9069d2490ddea36. The working project's differently named origin was not used for execution. - Linux 4.19.0-gvisor; Node v22.19.0; pnpm 9.15.0; Vitest 4.1.1; better-sqlite3 12.10.0; runtime SQLite 3.53.1.
- Two separate temporary Git clones and freshly migrated in-memory SQLite databases. No live server, provider process, network-facing plugin runtime, listening port, or persistent BB data directory was used.
- Both checkouts use frozen installation and normal Turbo builds; full build logs remain local because they are not reproduction evidence.
4. Minimal reproduction
This investigator-authored test calls the actual source database function. It creates eight threads, each with 96 or 384 unrelated extension-state events, each payload containing 8 KiB synthetic text. It first measures an uninstrumented native lookup. It then counts executed two-argument SQLite JSON extractions by delegating each call to the genuine built-in function in a separate migrated in-memory connection. This is work-count instrumentation, not a database mock or a replacement query. The instrumented call also supplies a duplicate thread ID.
- Clone and check out the trusted commit using the first three commands below.
- Save the complete test printed below to
packages/db/test/issue-5234-repro.test.tsin that clone. - Run the remaining install, build, and test commands:
git clone https://github.com/get-bb/bb.git bb-5234-check cd bb-5234-check git checkout --detach ff94848832b22c3281ffc4b5b9069d2490ddea36 pnpm install --frozen-lockfile --prefer-offline pnpm exec turbo run build pnpm exec turbo run test --force --filter=@bb/db -- test/issue-5234-repro.test.ts --silent=false pnpm exec turbo run test --filter=@bb/db -- test/data/events.test.ts test/query-plans.test.ts
- Expected: empty results and no more than one payload inspection per history row. Actual: empty results and exactly one inspection per row in both clean runs.
| Run | Threads | Events/thread | Rows | JSON extractions | Uninstrumented query time |
|---|---|---|---|---|---|
| First clean checkout | 8 | 96 | 0 | 768 | 2.210 ms |
| First clean checkout | 8 | 384 | 0 | 3072 | 5.726 ms |
| Second clean checkout | 8 | 96 | 0 | 768 | 3.538 ms |
| Second clean checkout | 8 | 384 | 0 | 3072 | 4.850 ms |
The operation count grows fourfold when history grows fourfold, not sixteenfold. Timings are single warm in-memory samples; they are not desktop latency measurements or cold-cache benchmarks, and no timing threshold is asserted.
Complete reproduction test (save as packages/db/test/issue-5234-repro.test.ts):
import { performance } from "node:perf_hooks";
import { expect, it } from "vitest";
import { threadScope } from "@bb/domain";
import { createConnection } from "../src/connection.js";
import { migrate } from "../src/migrate.js";
import { noopNotifier } from "../src/notifier.js";
import { createProject } from "../src/data/projects.js";
import { upsertHost } from "../src/data/hosts.js";
import { createThread } from "../src/data/threads.js";
import {
insertEvents,
listLatestThreadStateEventRowsByThreadIds,
} from "../src/data/events.js";
it.each([96, 384])(
"inspects unrelated extension payloads at most once with %i events per thread",
(historyLength) => {
const db = createConnection(":memory:");
const delegate = createConnection(":memory:");
try {
migrate(db);
migrate(delegate);
const host = upsertHost(db, noopNotifier, { name: "synthetic-host" });
const { project } = createProject(db, noopNotifier, {
name: "synthetic-project",
source: { type: "local_path", hostId: host.id, path: "/tmp/synthetic" },
});
const threads = Array.from({ length: 8 }, () =>
createThread(db, noopNotifier, {
projectId: project.id,
providerId: "codex",
}),
);
const payload = JSON.stringify({
kind: "synthetic/state",
payload: { text: "z".repeat(8192) },
});
insertEvents(
db,
noopNotifier,
threads.flatMap((thread) =>
Array.from({ length: historyLength }, (_, index) => ({
data: payload,
itemId: null,
itemKind: null,
parentToolCallId: null,
scope: threadScope(),
sequence: index + 1,
threadId: thread.id,
type: "thread/extensionState/updated" as const,
})),
),
);
const threadIds = threads.map((thread) => thread.id);
const started = performance.now();
expect(
listLatestThreadStateEventRowsByThreadIds(db, {
threadIds,
kind: "provider-codex/goal",
}),
).toEqual([]);
const elapsedMs = performance.now() - started;
const builtinJsonExtract = delegate.$client.prepare<
[string, string],
{ value: string | null }
>("SELECT json_extract(?, ?) AS value");
let jsonExtractions = 0;
db.$client.function(
"json_extract",
{ deterministic: true },
(data: string, path: string) => {
jsonExtractions += 1;
const result = builtinJsonExtract.get(data, path);
if (!result) throw new Error("Missing SQLite JSON result");
return result.value;
},
);
expect(
listLatestThreadStateEventRowsByThreadIds(db, {
threadIds: [...threadIds, threadIds[0]!],
kind: "provider-codex/goal",
}),
).toEqual([]);
const maximumExtractions = threads.length * historyLength;
console.log(
JSON.stringify({
historyLength,
threads: threads.length,
rows: 0,
nativeQueryMs: Number(elapsedMs.toFixed(3)),
jsonExtractions,
maximumExtractions,
sqlite: delegate.$client
.prepare("SELECT sqlite_version()")
.pluck()
.get(),
}),
);
expect(jsonExtractions).toBeGreaterThan(0);
expect(jsonExtractions).toBeLessThanOrEqual(maximumExtractions);
} finally {
db.$client.close();
delegate.$client.close();
}
},
);
5. Root cause
The old implementation searched outer state-event rows and evaluated a correlated MAX(candidate.sequence) against each row's thread. A missing goal forces the kind predicate to parse unrelated state history; correlating this work to each outer event amplifies it. That historical mechanism is visible in the trusted merged source diff, not inferred from the issue's executable snippet.
The repair changes the correlation domain to a VALUES list of requested thread IDs, selects one candidate row in descending sequence order with LIMIT 1, and uses the existing partial state index. Missing goals still require one history pass per requested thread, but not a history pass per state event.
- Current latest-state query and batching.
- Thread-list prompt-banner candidate lookup calls the function for requested threads.
- Existing semantics: legacy goals, clear events, extension kinds, missing state, duplicate/empty IDs, and SQLite-variable-limit batching.
- Existing multi-thread query-plan regression.
- Trusted merged repair; local ancestry check confirms it is an ancestor of the tested base.
6. Proposed fix / disposition
No new source fix is appropriate: the requested root-cause rewrite and semantic safeguards already exist on main. No simple-fix branch, commit, push, or duplicate PR was created. If an installed artifact still exhibits the event-correlated MAX query, the next investigation should identify the exact packaged server artifact and compare it with the merged repair; this report makes no claim that any particular published binary contains the repair.
7. Related issues and pull requests
The issue's open closing-PR references and an open-PR search for its trusted number were both empty. The already merged #4931 is evidence of an existing repair, not a linked open PR to execute or review. Its source change was inspected through trusted main's Git history; no PR branch was checked out or run.
8. Verification
The same investigator created a second clean Git clone, checked out ff94848832b22c3281ffc4b5b9069d2490ddea36, confirmed a clean tracked tree, performed a frozen install and normal Turbo build, and applied only the authored reproduction file. The reproduction ran with --force to prevent a Turbo test-cache replay. It created entirely new in-memory databases, so there are no reused data or ports. Both cases passed again, confirming the final ALREADY FIXED verdict. This is a repeated clean verification, not independent verification.
Command: pnpm exec turbo run test --force --filter=@bb/db -- test/issue-5234-repro.test.ts --silent=false. Result: 2 passed, with 768 and 3,072 JSON extractions. The first checkout's existing event and query-plan suites also passed: 138 tests across two files. No report correction was needed after the second run.
9. Appendix and trust boundary
Issue text, code blocks, logs, and links were treated only as untrusted claims. None of its scripts, commands, patches, or linked code were run or fetched. Reproduction code was authored from trusted repository APIs and current query evidence. The historical installed-binary claim, reported production timings, latest-release claim, and macOS symptoms are outside the tested scope.
First clean reproduction — exact output
• turbo 2.10.12
• Packages in scope: @bb/db
• Running test in 1 packages
• Remote caching disabled
//:ensure-native-modules: cache bypass, force executing 826d1a05842e4443
//:ensure-native-modules:
//:ensure-native-modules: > bb@ ensure-native-modules CHECKOUT-A
//:ensure-native-modules: > node scripts/ensure-native-modules.mjs
//:ensure-native-modules:
//:ensure-native-modules: [ensure-native-modules] Detached hardlinked better-sqlite3 binary before verification
@bb/db:test: cache miss, executing 6e47841b9fd1dfc5
@bb/db:test:
@bb/db:test: > @bb/db@0.0.1 test CHECKOUT-A/packages/db
@bb/db:test: > vitest run --config vitest.config.ts "test/issue-5234-repro.test.ts" "--silent=false"
@bb/db:test:
@bb/db:test:
@bb/db:test: RUN v4.1.1 CHECKOUT-A/packages/db
@bb/db:test:
@bb/db:test: stdout | test/issue-5234-repro.test.ts > inspects unrelated extension payloads at most once with 96 events per thread
@bb/db:test: {"historyLength":96,"threads":8,"rows":0,"nativeQueryMs":2.21,"jsonExtractions":768,"maximumExtractions":768,"sqlite":"3.53.1"}
@bb/db:test:
@bb/db:test: stdout | test/issue-5234-repro.test.ts > inspects unrelated extension payloads at most once with 384 events per thread
@bb/db:test: {"historyLength":384,"threads":8,"rows":0,"nativeQueryMs":5.726,"jsonExtractions":3072,"maximumExtractions":3072,"sqlite":"3.53.1"}
@bb/db:test:
@bb/db:test: ✓ |@bb/db| test/issue-5234-repro.test.ts (2 tests) 806ms
@bb/db:test: ✓ inspects unrelated extension payloads at most once with 96 events per thread 358ms
@bb/db:test: ✓ inspects unrelated extension payloads at most once with 384 events per thread 447ms
@bb/db:test:
@bb/db:test: Test Files 1 passed (1)
@bb/db:test: Tests 2 passed (2)
@bb/db:test: Start at 22:03:37
@bb/db:test: Duration 4.39s (transform 2.95s, setup 0ms, import 3.42s, tests 806ms, environment 0ms)
@bb/db:test:
Tasks: 2 successful, 2 total
Cached: 0 cached, 2 total
Time: 6.005s
Second clean reproduction — exact output
• turbo 2.10.12
• Packages in scope: @bb/db
• Running test in 1 packages
• Remote caching disabled
//:ensure-native-modules: cache bypass, force executing 826d1a05842e4443
//:ensure-native-modules:
//:ensure-native-modules: > bb@ ensure-native-modules CHECKOUT-B
//:ensure-native-modules: > node scripts/ensure-native-modules.mjs
//:ensure-native-modules:
//:ensure-native-modules: [ensure-native-modules] Detached hardlinked better-sqlite3 binary before verification
@bb/db:test: cache bypass, force executing 6e47841b9fd1dfc5
@bb/db:test:
@bb/db:test: > @bb/db@0.0.1 test CHECKOUT-B/packages/db
@bb/db:test: > vitest run --config vitest.config.ts "test/issue-5234-repro.test.ts" "--silent=false"
@bb/db:test:
@bb/db:test:
@bb/db:test: RUN v4.1.1 CHECKOUT-B/packages/db
@bb/db:test:
@bb/db:test: stdout | test/issue-5234-repro.test.ts > inspects unrelated extension payloads at most once with 96 events per thread
@bb/db:test: {"historyLength":96,"threads":8,"rows":0,"nativeQueryMs":3.538,"jsonExtractions":768,"maximumExtractions":768,"sqlite":"3.53.1"}
@bb/db:test:
@bb/db:test: stdout | test/issue-5234-repro.test.ts > inspects unrelated extension payloads at most once with 384 events per thread
@bb/db:test: {"historyLength":384,"threads":8,"rows":0,"nativeQueryMs":4.85,"jsonExtractions":3072,"maximumExtractions":3072,"sqlite":"3.53.1"}
@bb/db:test:
@bb/db:test: ✓ |@bb/db| test/issue-5234-repro.test.ts (2 tests) 764ms
@bb/db:test: ✓ inspects unrelated extension payloads at most once with 96 events per thread 337ms
@bb/db:test: ✓ inspects unrelated extension payloads at most once with 384 events per thread 425ms
@bb/db:test:
@bb/db:test: Test Files 1 passed (1)
@bb/db:test: Tests 2 passed (2)
@bb/db:test: Start at 22:04:32
@bb/db:test: Duration 4.25s (transform 2.82s, setup 0ms, import 3.30s, tests 764ms, environment 0ms)
@bb/db:test:
Tasks: 2 successful, 2 total
Cached: 0 cached, 2 total
Time: 5.989s
Existing event and query-plan suites — exact output
• turbo 2.10.12 • Packages in scope: @bb/db • Running test in 1 packages • Remote caching disabled //:ensure-native-modules: cache bypass, force executing 0d58bd96dfb9b06a //:ensure-native-modules: //:ensure-native-modules: > bb@ ensure-native-modules CHECKOUT-A //:ensure-native-modules: > node scripts/ensure-native-modules.mjs //:ensure-native-modules: @bb/db:test: cache miss, executing f88234a1887be901 @bb/db:test: @bb/db:test: > @bb/db@0.0.1 test CHECKOUT-A/packages/db @bb/db:test: > vitest run --config vitest.config.ts "test/data/events.test.ts" "test/query-plans.test.ts" @bb/db:test: @bb/db:test: @bb/db:test: RUN v4.1.1 CHECKOUT-A/packages/db @bb/db:test: @bb/db:test: ✓ |@bb/db| test/data/events.test.ts (96 tests) 1839ms @bb/db:test: ✓ keeps window-hint lookup bounded as request history grows 595ms @bb/db:test: ✓ |@bb/db| test/query-plans.test.ts (42 tests) 6733ms @bb/db:test: ✓ checks spawn-agent history without reading unrelated event payloads 316ms @bb/db:test: ✓ finds a plugin's held queued messages through the partial holder index 322ms @bb/db:test: @bb/db:test: Test Files 2 passed (2) @bb/db:test: Tests 138 passed (138) @bb/db:test: Start at 22:04:04 @bb/db:test: Duration 11.80s (transform 8.20s, setup 0ms, import 10.12s, tests 8.57s, environment 0ms) @bb/db:test: Tasks: 2 successful, 2 total Cached: 0 cached, 2 total Time: 14.344s
Filesystem prefixes in output are replaced by CHECKOUT-A / CHECKOUT-B. Raw artifacts stay local; site policy publishes only the self-contained HTML and summary metadata.
- Preparation commands in each clean clone:
pnpm install --frozen-lockfile --prefer-offlineandpnpm exec turbo run build. First reproduction used the same test command without--forceand was a cache miss. - Read-only metadata and source checks: issue fields, labels, comments and closing-PR references; open PR search by issue number;
git fetch origin main;git rev-parse origin/main;git merge-base --is-ancestor ef570298ef45b39d837da0fcab0fb94ea086783b HEAD; and the trusted merged commit's source diff.
> AGENT GENERATED