Repository navigation
fix(db): avoid repeated latest-state scans in thread batches - #4931
Merged
Merged
Conversation
yteruel31
force-pushed
the
fix/thread-state-query-scaling
branch
from
October 5, 2026 19:33
99eef75 to
96ca477
Compare
SawyerHood
force-pushed
the
fix/thread-state-query-scaling
branch
from
October 5, 2026 20:48
96ca477 to
39ceb1e
Compare
Closed
3 tasks done
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
listLatestThreadStateEventRowsByThreadIdscorrelates a latest-stateMAX(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 andjson_extractcalls, particularly when there is no matchingprovider-codex/goalstate. This synchronous read blocks the server event loop during sidebar bootstrap. The issue remains reproducible onmainat75308f407660efe0f93ffb9626936e5067b5bb03; 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 correlatedMAXwith aVALUESlist of requested thread IDs and one descending scalarrowidlookup per requested thread.How you verified
@bb/dbsuite: 568 tests across 48 files passed on the final patch.pnpm exec turbo run typecheck --filter=@bb/db: passed, including the cross-batch fixture.git diff --check: passed on all three changed files.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: