Skip to content

Guard warm reads against extra SQLite prepares - #8463

Merged
ymichael merged 2 commits into
get-bb:mainfrom
lanjak:fix-8445-warm-prepare-guard
Dec 1, 2026
Merged

ymichael merged 2 commits into
get-bb:mainfrom
lanjak:fix-8445-warm-prepare-guard

Conversation

@lanjak

@lanjak lanjak commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

apps/server/test/perf/request-path-statements.test.ts counted 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

  • The test records which function compiles each SQL text. It names the closest frame outside the test, read when the statement is prepared, in every mode.
  • New rule: each of the 22 read requests runs twice, and the second run must not compile SQL that the first run already compiled. A failure names the function and the SQL, for example packages/db/src/data/queued-thread-messages.ts#prepareListQueuedThreadMessages: select ….
  • Two named lists, with one reason per entry:
    • VARYING_SHAPE_QUERIES: SQL whose text follows its input. These are the queryBatch callbacks in events.ts, queued-thread-messages.ts and retained-event-outputs.ts, where the IN (…) 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.
  • A final test fails when a listed entry no longer recompiles, so both lists only shrink.
  • The 12 write requests are marked writes: true and are not covered yet. Running them through the rule flags about 80 more uncached functions.
  • The growth tests are unchanged.

How you verified

  • On main, with listQueuedThreadMessages switched to an uncached query, the existing test passes. With this change, queued messages and prompt history fail and name prepareListQueuedThreadMessages.
  • With a stale entry added to UNCACHED_READ_QUERIES, the list check fails and names the entry.
  • The full file passes, 91/91. It also passes with BB_QUERY_PLAN_EXECUTED set and with BB_QUERY_PLAN_REPORT set, and with BB_QUERY_PLAN_EXECUTED set the regression fails with the same message. The query-plan guard is installed by the setup file before this module patches prepare, so its frames never become the caller.
  • pnpm exec turbo run typecheck lint lint:type-aware --filter=@bb/server passes.

Fixes #8445

AGENT GENERATED

lanjak and others added 2 commits December 1, 2026 10:25
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
ymichael force-pushed the fix-8445-warm-prepare-guard branch from 629bd4d to fab193b Compare December 1, 2026 18:38
@ymichael
ymichael merged commit 20b6e1c into get-bb:main Dec 1, 2026
30 checks passed
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]>
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.

db/perf: add a warm-connection duplicate prepare() guard to catch uncached fixed-shape Drizzle queries automatically

2 participants