Repository navigation
Seek a turn's provider compaction through the turn index - #6787
Merged
ymichael merged 1 commit intoNov 2, 2026
Merged
Conversation
Send admission asks whether the active turn is a provider-started compaction (get-bb#6420). With no sqlite_stat1, SQLite answered that lookup through events_thread_sequence_idx and read every event in the thread, newest first, which takes seconds in long threads. Pin the existing thread, turn and type index so the lookup reads only the active turn's lifecycle rows, and pin the plan in a query-plan test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
3 tasks done
3 tasks done
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
Every send into an active thread checks whether the active turn is a provider-started compaction. That check,
isStoredTurnProviderCompactionRunning, came in with #6420 and first shipped in desktop v0.48.0. In long threads it blocks the server for seconds (#6786).Its first query looks for the turn's latest root
contextCompactionlifecycle event. It filters by thread, turn, type, item kind and parent, ordered bysequence DESC LIMIT 1. bb never runsANALYZE, so there is nosqlite_stat1. Without statistics, SQLite picks the uniqueevents_thread_sequence_idx (thread_id=?)because it already returns rows inORDER BYorder. It then reads the table row of every event in the thread, newest first, until one matches. Most turns contain no compaction, so the usual send reads the thread's whole history.On a 348k-event thread that took 9 to 18 s of wall time (1.4 to 3.2 s CPU). The event loop stalled with the send in flight, before the message was stored.
What changed
packages/db/src/data/events.ts, the compaction query inisStoredTurnProviderCompactionRunningreads fromevents INDEXED BY events_thread_turn_type_item_sequence_idx. That index seeks(thread_id, turn_id, type), so the query reads only the active turn'sitem/startedanditem/completedrows, then sorts them in a temporary B-tree. On the thread above that is at most 505 rows in any turn, 20 on average.sql<ThreadEventType>, because drizzle will not resolveevents.typeagainst a raw-SQLfrom(). The other pinned queries in this file do the same.INDEXED BYchanges only the access path, and theWHEREclause is unchanged.(thread_id, sequence)is unique, soORDER BY sequence DESC LIMIT 1has no ties and returns the same row. The repro script checks this on every turn it times. Queue messages sent while Pi runs an extension-started compaction #6420's predicate, and which sends it queues, are unchanged for every provider and turn shape.events_thread_type_item_kind_sequence_idx. That one would read every compaction event in the thread's history (1,876 on the thread above), and that count only grows. The turn index's cost is bounded by the turn.turn/input/acceptedfirst returns the same answer and would skip the lookup in user turns. On its own, though, it leaves the history walk in every turn that accepted no input, and those are common: 152 of the 5,798 turns on that claude-code thread. With the index pinned, the lookup is bounded either way.HOST_DAEMON_PROTOCOL_VERSIONbump.Costs and failure mode:
no such index, and every send that reaches this lookup (a send into a thread with an active turn) fails loudly. It does not fall back to a scan. The new query-plan test calls the function and asserts the index name in its plan, and the existing "drops redundant events indexes after creating their consolidated replacement" test asserts the index exists. Both would fail first.How you verified
New test:
packages/db/test/query-plans.test.ts, "finds a turn's running provider compaction through the turn index".trueonly for the first, andfalsefor those and for a turn with no compaction.events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?), and that neither statement seeks by thread only.events.tschange reverted, the return-value assertions pass and the plan assertion fails withReceived: "SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)". With the change, it passes.packages/db:pnpm exec vitest run test/query-plans.test.ts: 50 tests passed.pnpm exec vitest run test/data/events.test.ts test/data/event-rewrite-generation.test.ts: 103 passed.pnpm exec turbo run lint test --filter=@bb/db(the CI job's form): 54 files, 635 tests passed.@bb/dbhas no lint task.pnpm run typecheckpasses.apps/server:pnpm run typecheckpasses.pnpm exec vitest runonpublic-thread-compaction,thread-events,thread-send-dispatch,requested-queue-drain,queue-drain-failure,parent-system-message-dispatch,thread-send-error-recoveryandpublic-thread-offline-followuppassed 105 tests in 8 files. These include Queue messages sent while Pi runs an extension-started compaction #6420's queued-during-compaction case and its three steering controls.Full suites on Linux (Node 22.21.1, pnpm 9.15.0, better-sqlite3 12.10.0 with SQLite 3.53.1, one Vitest worker):
@bb/db: 635 tests passed in 54 files.@bb/server: 3,786 passed, 3 failed, 1 skipped. The 3 failures also fail with both changed files restored to916d684ac2: two cases of "resolves an unset HOME and preserves explicit HOME" ininstall-machine-script.test.ts, and "uses the first and last committer dates from plugin history" inbb-official-generator.test.ts(a+00:00date suffix where the test expectsZ).turbo run build --filter=@bb/db --filter=@bb/serverpasses, which builds the server and its dependencies;@bb/dbitself has no build script.oxlintaborted inside its allocator there, on this head and onmainalike, so that run gives no lint result. The Mac lint run above is the lint evidence.Same rows as before: a differential harness ran the production function and both raw statements on real migrated SQLite over 2,013 cases, 2,000 of them randomized event sequences. Every case returned the same selected row (
type, or no row) from both statements, and the function returned the expected boolean against an independent oracle. The cases cover empty turns, several compactions where the latest wins, nested compactions, older turns, other threads, accepted input and a 60,000-event turn. The pinned plan was also checked on a schema upgraded from desktop v0.47.1 with that release's own migration runner, and afterANALYZE, where both statements pick the turn index.Lint and format:
oxlint -c .oxlintrc.jsonon both files reports only twobb(no-comments)errors, on lines 477–478 ofquery-plans.test.ts. They are already onmainand outside this change.oxfmt --checkon the test file,git diff --checkandscripts/check-source-nul.mjspass.packages/db/src/data/is excluded from oxfmt, and running oxfmt on the changed function leaves it unchanged.Plan on a real database: read-only
EXPLAIN QUERY PLANon a 33 GB, 33M-row bb database (nosqlite_stat1):SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)SEARCH events USING INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?),USE TEMP B-TREE FOR ORDER BYSynthetic timing, with the script from the issue:
A database larger than memory: the numbers above are a warm-cache CPU floor. The logged production walks took about 6 times their CPU time, which I take to be disk reads and waiting on a loaded machine; I did not measure the Mac's page cache or I/O, so that is an inference. To measure the cold case directly, the comparison was repeated on a Linux VM with 4 CPUs and 4 GiB of RAM:
ANALYZE, and used the production connection's cache and mmap settings.syncandecho 3 > /proc/sys/vm/drop_caches. The variant order alternated every iteration, and every result was checked against the expected answer.POST /api/v1/threads/:id/sendinto the active provider-started turn of a 350,001-event thread, 12 alternating pairs with a warm cache. The median was 503 ms on main and 22 ms pinned, and the slowest was 27.9 s on main and 33 ms pinned. All requests returneddelivery: "sent".Send-path sweep: I captured every
SELECToneventsduring a test-harness steer, into an active turn with and without accepted input, and explained each plan. With the change, no statement walks the whole thread. Two seeks by thread prefix remain, and both are bounded:getLastStoredTurnRequestEventstops at the newest turn request.events_thread_state_thread_sequence_idx, which holds only goal and extension-state events.Not changed here:
getStoredTurnRequestEventForTurn, whichisManualCompactionActivehas called since Add manual context compaction across providers #1152, seeksevents_thread_type_sequence_idx (thread_id=? AND type=?)for the turn's accepted input. In a provider-started turn, which has none, it reads every accepted-input row in the thread. In the large run that was about 5,800 rows, and the lookup took 8 ms warm and 0.9 s cold in a profiled send (profiler overhead included). It predates Queue messages sent while Pi runs an extension-started compaction #6420, and the issue describes it.Fixes #6786