Repository navigation
Guard warm reads against extra SQLite prepares - #8463
Merged
Merged
Conversation
Replace the per-path prepare counts with a rule: a repeated read must not compile SQL text it already compiled. A failure names the data function and the SQL. Queries whose SQL varies with batch size or search terms, and the read queries not cached yet, sit on two named lists with a reason each; a listed entry that stops recompiling fails the suite so the lists only shrink. Write paths are not covered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
fix-8445-warm-prepare-guard
branch
from
December 1, 2026 18:38
629bd4d to
fab193b
Compare
ymichael
added a commit
that referenced
this pull request
Dec 1, 2026
## Human comments ## What was wrong #8463 added a warm-read check to `apps/server/test/perf/request-path-statements.test.ts`, and it listed 13 read functions that compile their SQL again on every call. Each builds a fresh Drizzle query, so every thread list, thread detail, head state, conversation outline, thread count, child summary, prompt history and default-execution-options request recompiles the SQL and prepares a new SQLite statement on the server's main thread. ## What changed - `packages/db/src/data/events.ts`, `threads.ts`, `prompt-history.ts`, `project-execution-defaults.ts`: the 13 reads bind their values as placeholders and reuse one prepared statement per connection through `prepareCachedQuery`. - Reads whose SQL depends on options use `prepareCachedQueryVariant`, with a key that holds every option that changes the SQL and nothing else: `countThreads`, `listThreadsWithPendingInteractionState`, `listStoredEventRows`, and the root and full conversation outline rows. - `listStoredEventRows` keeps `type = ?` for a single type, so the merge path's `ORDER BY … LIMIT` still walks the index. - Variable-length lists bind as one JSON array through `json_each`, like #8453's turn IDs. This covers thread IDs in the thread list and several event types in `listStoredEventRows`. The query plans keep the same index searches (shown below). - `countThreadsWhere` and `listThreadsWhere` are gone. Their four callers each have a fixed-shape statement. - `request-path-statements.test.ts` drops the "not cached yet" list. Every read path now compiles each fixed query once; the varying-shape list is unchanged. - **Tests that counted `prepare` calls as "the query ran":** a cached statement is never prepared again, so those counts go to zero. - Two such tests failed with this change. Others assert zero reads and would have kept passing without checking anything once their query got cached. - The new `apps/server/test/helpers/statement-executions.ts` records statement executions, cached or not. - The outline, thread-data, derived-cache, runtime-status and grouping-context tests now use it. The grouping-context test now also sees the cached `PRAGMA data_version` check that runs on that path. - `packages/db/src/query-plan-test-guard.ts`: its per-statement wrappers look up `all`/`get`/`run`/`iterate` on the prototype at call time instead of binding them at prepare time. Without this, execution recording would miss statements prepared before it started, and only on platforms where the guard is installed (it is a no-op on Windows). No wire, CLI, schema or stored-data changes. ## How you verified - **Real data.** A `VACUUM INTO` copy of a production `bb.db` (1,297 threads, 1.19M events). Main's and this branch's versions of the four data files ran in alternating processes, three runs each. The numbers are median warm CPU per call, over the 30 busiest threads, 30 largest parents and every project. Every reader returned identical rows on main and on the branch, in all six runs. | Read | main | branch | |---|---:|---:| | thread list (project, limit 100) | 307µs | 114µs | | thread list by 20 ids | 308µs | 108µs | | conversation outline rows | 270µs | 81µs | | conversation outline latest sequence | 179µs | 39µs | | model fallback (head state) | 128µs | 33µs | | turn lifecycle rows (timeline) | 93µs | 31µs | | oldest events page (100 rows) | 386µs | 332µs | | prompt history | 87µs | 42µs | | child threads / live children / hidden sources | 73–95µs | 2–22µs | | lifecycle dependents | 65µs | 1µs | | todo snapshot | 67µs | 10µs | | running threads | 42µs | 5µs | | thread count (all / project / grouped) | 32–39µs | 8–12µs | | project execution defaults | 30µs | 1µs | - **Query plans** on the same copy. `type IN (SELECT value FROM json_each(?))` keeps `SEARCH events USING COVERING INDEX events_thread_type_sequence_idx (thread_id=? AND type=?)`. `id IN (SELECT value FROM json_each(?))` keeps `SEARCH threads USING INDEX sqlite_autoindex_threads_1 (id=?)`. - **New `packages/db/test/data/read-preparation.test.ts`** covers 23 reads and shapes. Each one first reads an empty subject, which warms the cache, then reads a populated subject, then alternates between them, and asserts the expected rows with no new `prepare` calls. Two mutations fail it: - binding a thread ID into a cached `listStoredEventRows` statement: 5 failures; - leaving the type filter out of its variant key: 2 failures. - The warm-read check passes with the "not cached yet" list removed. - `pnpm exec turbo run typecheck lint lint:type-aware test --filter=@bb/db`: 819 tests pass. - `pnpm exec turbo run typecheck lint lint:type-aware --filter=@bb/server` passes. - A full `@bb/server` run before the test migration failed only the two prepare-counting tests and one builtin-plugin hot-reload test. That last test passes on its own. All five migrated files pass. > 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
apps/server/test/perf/request-path-statements.test.tscounted the SQL statements each request runs. A query that loses its prepared-statement cache runs the same statements but compiles its SQL again on every request, so the count stays the same and the regression passes (#8445).What changed
packages/db/src/data/queued-thread-messages.ts#prepareListQueuedThreadMessages: select ….VARYING_SHAPE_QUERIES: SQL whose text follows its input. These are thequeryBatchcallbacks inevents.ts,queued-thread-messages.tsandretained-event-outputs.ts, where theIN (…)size follows the batch, plus the two thread-search queries, which follow the search terms and matched threads.UNCACHED_READ_QUERIES: 13 read queries that are not cached yet.writes: trueand are not covered yet. Running them through the rule flags about 80 more uncached functions.How you verified
listQueuedThreadMessagesswitched to an uncached query, the existing test passes. With this change,queued messagesandprompt historyfail and nameprepareListQueuedThreadMessages.UNCACHED_READ_QUERIES, the list check fails and names the entry.BB_QUERY_PLAN_EXECUTEDset and withBB_QUERY_PLAN_REPORTset, and withBB_QUERY_PLAN_EXECUTEDset the regression fails with the same message. The query-plan guard is installed by the setup file before this module patchesprepare, so its frames never become the caller.pnpm exec turbo run typecheck lint lint:type-aware --filter=@bb/serverpasses.Fixes #8445