Skip to content

fix(db): avoid repeated latest-state scans in thread batches - #4931

Merged
SawyerHood merged 1 commit into
get-bb:mainfrom
yteruel31:fix/thread-state-query-scaling
Oct 5, 2026
Merged

SawyerHood merged 1 commit into
get-bb:mainfrom
yteruel31:fix/thread-state-query-scaling

Conversation

@yteruel31

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

listLatestThreadStateEventRowsByThreadIds correlates a latest-state MAX(sequence) lookup with every outer state-event row in a multi-thread batch. In the observed SQLite plan, threads containing many unrelated extension-state events cause repeated scans and json_extract calls, particularly when there is no matching provider-codex/goal state. This synchronous read blocks the server event loop during sidebar bootstrap. The issue remains reproducible on main at 75308f407660efe0f93ffb9626936e5067b5bb03; the historical fix in get-bb/bb#1204 addressed the older latest-goal access path, not this current amplification.

What changed

  • packages/db/src/data/events.ts: replace the outer state-event scan and correlated MAX with a VALUES list of requested thread IDs and one descending scalar rowid lookup per requested thread.
  • Retain the existing pinned partial index, type/kind filtering, SQLite-variable batching, ID deduplication, and returned stored-event row fields.
  • Expand semantic and query-plan coverage for multi-thread histories, unrelated extension kinds, absent states, duplicate/empty inputs, and real results across the SQLite variable-limit boundary.
  • No new index, schema migration, public API, CLI, or server/daemon wire change.

How you verified

  • The multi-thread query-plan regression fails with the original query and passes after the rewrite.
  • Focused event/query-plan suites: 137 tests passed.
  • Complete @bb/db suite: 568 tests across 48 files passed on the final patch.
  • pnpm exec turbo run typecheck --filter=@bb/db: passed, including the cross-batch fixture.
  • Formatter and git diff --check: passed on all three changed files.
  • A read-only code review identified a SQLite-version-sensitive plan-detail assertion; it was replaced with stable SQL/index assertions before the final full-suite run.
  • Synthetic migrated-database benchmark using the exact old SQL and the actual patched source function, Node v22.22.1, 6 threads, unrelated state payloads of 4,141 bytes, three warm runs per size:
State events per thread Original SQL median Patched source median
100 44.644 ms 1.786 ms
250 337.071 ms 3.168 ms
500 1,332.262 ms 6.009 ms

The requested kind is absent in this benchmark, forcing the worst-case unrelated-state scan. Result IDs are identical for every run. These are query timings, not end-to-end mobile measurements. Functional legacy-goal/extension-state results are covered by the repository tests. No private database, prompts, tool outputs, credentials, or logs containing user content are included in this change.

Commands:

pnpm exec turbo run test --filter=@bb/db -- test/data/events.test.ts test/query-plans.test.ts --maxWorkers=2
pnpm exec turbo run test --filter=@bb/db -- --maxWorkers=2
pnpm exec turbo run typecheck --filter=@bb/db
pnpm exec oxfmt --check packages/db/src/data/events.ts packages/db/test/data/events.test.ts packages/db/test/query-plans.test.ts

AGENT GENERATED

@yteruel31
yteruel31 force-pushed the fix/thread-state-query-scaling branch from 99eef75 to 96ca477 Compare October 5, 2026 19:33
@SawyerHood
SawyerHood force-pushed the fix/thread-state-query-scaling branch from 96ca477 to 39ceb1e Compare October 5, 2026 20:48
@SawyerHood
SawyerHood merged commit ef57029 into get-bb:main Oct 5, 2026
1 check failed
ymichael added a commit that referenced this pull request Nov 2, 2026
## Human comments

## What was wrong

`listLatestThreadStateEventRowsByThreadIds` finds the latest goal event
or `thread/extensionState/updated` row of one kind per thread. Its
partial index (`events_thread_state_thread_sequence_idx`) keys only
`(thread_id, sequence)`, not the kind. When the requested kind's latest
row is old or absent, SQLite walks back through every newer
extension-state row and `json_extract`s its `data` to check the kind.
#4931 removed the repeated re-scan but left this one scan per thread.
The thread list repeats the lookup every refresh. With a provider that
publishes ~20 KB snapshots per change (5,724 in one thread for the
reporter), that means hundreds of MB of JSON parsed per refresh and
0.6–1.4 s event-loop freezes every ~2 s. The shape dates back to #2164
(Aug 21), which widened the index to all extension-state kinds; it is
not a recent regression. Investigation report:
https://get-bb.github.io/reports/issues/6825.html

## What changed

`packages/db/src/data/events.ts`: the lookup now keeps a per-connection
watermark cache. For each (thread, kind) it remembers the latest
matching sequence and the newest state sequence already scanned. Later
lookups scan only state rows past that watermark, using a bounded
`(thread_id=? AND sequence>?)` seek on the existing index, and then
fetch the remembered row by `(thread_id, sequence)`.

- No schema change or migration. This deliberately deviates from the
issue's suggested kind-aware index: building an expression index on
`events` would stall startup on large databases (12.5 s on a 9 GB copy),
and any malformed `data` row would fail the migration.
- No pruning of superseded snapshots. Plugins page through
extension-state history through the SDK
(`plugins/provider-codex/src/async-questions.ts`).
- Invalidation:
- Entries are dropped when the thread's event rewrite generation changes
(rewinds, rewrites, pruning) or when `PRAGMA data_version` changes.
- A thread is rescanned when its scanned watermark went backwards or the
remembered row no longer exists or matches.
- Reads inside a transaction bypass the cache, so rolled-back rows are
never remembered.
- The signature narrows from `DbQueryConnection` to `DbConnection`;
every caller already passes a connection.
- Callers and results are unchanged. The first lookup per (thread, kind)
after a server start still pays a full scan, once.

## How you verified

- New tests in `packages/db/test/data/events.test.ts` (`repeated
latest-state lookups`): appends, goal events, a rewind that reinserts at
already-scanned sequences, a deleted remembered row, rows removed below
the watermark, and a rolled-back transaction. I disabled each of the
four guards in turn, and each time the matching test failed.
- `packages/db/test/query-plans.test.ts`: a warm lookup binds the
previous watermark and uses a `sequence>?` range seek on
`events_thread_state_thread_sequence_idx`, with no temp B-tree.
- Benchmark in the issue's shape (200 threads; 8 with 5,000 × 21 KB
snapshots), thread-list lookup for `provider-codex/goal`:

  | | main | this PR |
  |---|---:|---:|
  | first refresh | 327 ms | 328 ms |
| later refreshes, 2 new snapshots per heavy thread between each | ~310
ms | 0.5–1.4 ms |

- `pnpm exec turbo run test typecheck --filter=@bb/db` (650 passed).
`turbo run typecheck --filter=@bb/server`. Server suites covering the
goal banner, timeline head state, session options and runtime display
(174 passed).
- Ran `pnpm start:worktree` on this branch; the app and thread API
respond normally.

Fixes #6825

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants