Skip to content

Seek a turn's provider compaction through the turn index - #6787

Merged
ymichael merged 1 commit into
get-bb:mainfrom
Danielalnajjar:seek-provider-compaction-by-turn
Nov 2, 2026
Merged

ymichael merged 1 commit into
get-bb:mainfrom
Danielalnajjar:seek-provider-compaction-by-turn

Conversation

@Danielalnajjar

Copy link
Copy Markdown
Contributor

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 contextCompaction lifecycle event. It filters by thread, turn, type, item kind and parent, ordered by sequence DESC LIMIT 1. bb never runs ANALYZE, so there is no sqlite_stat1. Without statistics, SQLite picks the unique events_thread_sequence_idx (thread_id=?) because it already returns rows in ORDER BY order. 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

  • The query: in packages/db/src/data/events.ts, the compaction query in isStoredTurnProviderCompactionRunning reads from events 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's item/started and item/completed rows, then sorts them in a temporary B-tree. On the thread above that is at most 505 rows in any turn, 20 on average.
  • The selected column: it becomes sql<ThreadEventType>, because drizzle will not resolve events.type against a raw-SQL from(). The other pinned queries in this file do the same.
  • The rows returned are the same. INDEXED BY changes only the access path, and the WHERE clause is unchanged. (thread_id, sequence) is unique, so ORDER BY sequence DESC LIMIT 1 has 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.
  • Why this index: I pinned the turn index rather than 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.
  • Order of the two checks: I kept the order Queue messages sent while Pi runs an extension-started compaction #6420 wrote. Checking turn/input/accepted first 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.
  • No schema, migration, wire or protocol change, and no HOST_DAEMON_PROTOCOL_VERSION bump.

Costs and failure mode:

  • A large current turn costs more than it did. The old plan could stop early when the current turn's compaction was near the tip, which is the Pi extension case. The pinned plan always reads and sorts the turn's lifecycle rows. Synthetic, warm cache, with a running compaction at the end of the turn: main 0.01 ms, pinned 0.28 ms at 1,010 lifecycle rows (about twice the largest turn on the thread above), and 5.3 ms at 10,000 rows. In the larger Linux run below, a 60,000-event current turn with its compaction at the tip took 0.010 ms on main and 19 ms pinned warm, and 15 ms and 115 ms cold. The cost is linear in the turn's size and no longer depends on how long the thread is.
  • If the index is ever renamed or dropped, the statement fails at prepare with 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".

    • It seeds a running compaction, a completed one, a nested one, and one in a turn that accepted input. It checks the function returns true only for the first, and false for those and for a turn with no compaction.
    • It asserts that the compaction query's plan seeks events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?), and that neither statement seeks by thread only.
    • With the events.ts change reverted, the return-value assertions pass and the plan assertion fails with Received: "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/db has no lint task.
    • pnpm run typecheck passes.
  • apps/server: pnpm run typecheck passes. pnpm exec vitest run on public-thread-compaction, thread-events, thread-send-dispatch, requested-queue-drain, queue-drain-failure, parent-system-message-dispatch, thread-send-error-recovery and public-thread-offline-followup passed 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 to 916d684ac2: two cases of "resolves an unset HOME and preserves explicit HOME" in install-machine-script.test.ts, and "uses the first and last committer dates from plugin history" in bb-official-generator.test.ts (a +00:00 date suffix where the test expects Z).
    • Both packages typecheck. turbo run build --filter=@bb/db --filter=@bb/server passes, which builds the server and its dependencies; @bb/db itself has no build script. oxlint aborted inside its allocator there, on this head and on main alike, 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 after ANALYZE, where both statements pick the turn index.

  • Lint and format:

    • oxlint -c .oxlintrc.json on both files reports only two bb(no-comments) errors, on lines 477–478 of query-plans.test.ts. They are already on main and outside this change.
    • oxfmt --check on the test file, git diff --check and scripts/check-source-nul.mjs pass.
    • 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 PLAN on a 33 GB, 33M-row bb database (no sqlite_stat1):

    • before: SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)
    • after: SEARCH events USING INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?), USE TEMP B-TREE FOR ORDER BY
  • Synthetic timing, with the script from the issue:

    • Setup: one 350,000-event thread among 1.4M rows, warm page cache, medians of 5 runs.
    • The machine was loaded (one-minute load average about 20 on 18 CPUs), and main's figure moved by up to about 20% between runs.
    Rows Current turn main pinned
    220 B user turn, accepted input 52.1 ms 0.03 ms
    220 B provider-started, no compaction 51.4 ms 0.03 ms
    1 KB user turn, accepted input 180 ms 0.03 ms
    1 KB provider-started, no compaction 210 ms 0.07 ms
    1 KB 10,000 lifecycle rows, no compaction 171 ms 5.0 ms
    1 KB 10,000 lifecycle rows, running compaction at the end 0.01 ms 5.3 ms
  • 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:

    • The database was 8 GB, with 4.8M events of about 1 KB in 13 interleaved threads of 350,000 events each. It was built by the real migrations, with no ANALYZE, and used the production connection's cache and mmap settings.
    • Each scenario ran on its own thread. Warm cells are 20 samples after one prewarm. Cold cells are 8 samples, each after closing the connection and running sync and echo 3 > /proc/sys/vm/drop_caches. The variant order alternated every iteration, and every result was checked against the expected answer.
    • Medians of the statement alone, milliseconds:
    Current turn main warm pinned warm main cold pinned cold
    user turn, accepted input 405 0.007 35,738 21
    provider-started, no compaction 445 0.004 34,839 21
    60,000 lifecycle rows, no compaction 466 20 35,710 146
    60,000 lifecycle rows, running compaction at the end 0.010 19 15 115
    • With four CPU-burner processes running, the medians were similar: 573 ms on main and 0.004 ms pinned warm in the provider-started turn, and 36.7 s and 19 ms cold.
    • Real send route: POST /api/v1/threads/:id/send into 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 returned delivery: "sent".
    • I did not time the pinned query on the production database, because that would mean running queries against its data rather than only explaining them.
  • Send-path sweep: I captured every SELECT on events during 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:

    • getLastStoredTurnRequestEvent stops at the newest turn request.
    • The thread-state lookup uses the partial events_thread_state_thread_sequence_idx, which holds only goal and extension-state events.
  • Not changed here: getStoredTurnRequestEventForTurn, which isManualCompactionActive has called since Add manual context compaction across providers #1152, seeks events_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

AGENT GENERATED

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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-01T13:05:14.833374Z 08a8840 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ymichael
ymichael merged commit b550646 into get-bb:main Nov 2, 2026
30 checks passed
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.

Send admission walks the whole thread history to check for a provider compaction, blocking the server for seconds in long threads

2 participants