Repository navigation
Queue messages sent while Pi runs an extension-started compaction - #6420
Merged
Merged
Conversation
Pi rejects prompt RPCs while a manual compaction (extension ctx.compact() or RPC compact) runs. bb only queues sends during compactions it started itself, so a message sent while a Pi extension compacts an idle thread failed with "Cannot submit a prompt while compaction is in progress". The Pi bridge now tracks Pi manual compactions from compaction_start/compaction_end. A prompt that arrives during one is accepted at once and dispatched when compaction ends. A prompt Pi rejects for that reason is retried after compaction ends. Closing the session fails the queued prompt.
A Pi extension that calls ctx.compact() after a run settles opens its own bb turn holding a contextCompaction item. isManualCompactionActive only recognised a bb-issued /compact turn, so a message sent during that compaction was steered into the compaction turn. Pi rejected it with "Cannot submit a prompt while compaction is in progress", the compaction turn was marked failed and the thread ended in error. isManualCompactionActive now also treats an active turn that started a contextCompaction item and accepted no client input as a manual compaction. Sends go to the existing thread-busy queue and are delivered when the compaction turn completes.
isStoredTurnProviderCompaction matched any contextCompaction item/started in the active turn, including a compaction that had already completed and one nested under a child agent's tool call. It now reads the latest root contextCompaction lifecycle event in the turn and only reports a running compaction when that event is item/started, and is renamed isStoredTurnProviderCompactionRunning. Control tests cover a completed item, a nested item and a turn that accepted client input. The bridge test now drives the real bridge against the fake Pi instead of reaching into PiRpcSession private fields. The fake Pi rejects prompts while it compacts, as Pi does, and can run an extension-style manual compaction on settle, either announced before agent_settled or only after it rejects a prompt. The tests cover a prompt held until compaction ends, a prompt retried after Pi rejected it, and a held prompt dropped when the thread is released. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
pushed a commit
that referenced
this pull request
Nov 2, 2026
## 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. #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 #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 #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 #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 #6420, and the issue describes it. Fixes #6786 > AGENT GENERATED 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
Replaces #6380 by @steveafrost, which can't be reopened because its branch was force-pushed after it closed. His two commits keep him as author. The branch is rebased on main, with one follow-up commit on top.
What was wrong
A Pi extension can start a compaction itself with
ctx.compact(), for example when a run settles. While that compaction runs, Pi rejects every prompt with "Cannot submit a prompt while compaction is in progress". bb sent the message anyway: the turn failed, the thread ended inerror, and the message was lost.It happened in two ways:
agent_settledhandler before the bridge receivesagent_settled, so the compaction starts inside the user's turn, and that turn then closes. The server sees an idle thread and sends the next message as a new turn. The bridge passed it straight to Pi, which rejected it./compactthat bb had issued itself (isManualCompactionActivechecks the active turn's bb request). It steered the message into the compaction turn, Pi rejected it, and the turn failed.Fixes #6379
What changed
plugins/provider-pi/src/bridge/rpc-session.ts), fixes case 1:compaction_startandcompaction_end.compaction_start) is retried after compaction ends, up to 8 times.isManualCompactionActivealso returns true while the active turn is a provider-started compaction that is still running. That means a rootcontextCompactionitem that was started and has not completed, in a turn that accepted no client input.thread-busyqueue path and go out when the turn completes, as they do during a bb/compact.isStoredTurnProviderCompactionRunninginpackages/db/src/data/events.ts.No wire or protocol changes.
How you verified
ctx.compact()onagent_settledand holds compaction for 20s.error.bridge.manual-compaction-queue.test.ts):public-thread-compaction.test.ts):turbo run test:bb-plugin-provider-pipasses 323 (7 skipped).@bb/dbpasses 634.@bb/serversuite passes 3696. One builtin-plugin build test failed under load in that run and passes on its own; it's unrelated to this change.turbo run typecheckpasses for@bb/server,@bb/dbandbb-plugin-provider-pi.🤖 Generated with Claude Code