Skip to content

Cache the read queries the warm-read check still listed - #8490

Merged
ymichael merged 1 commit into
mainfrom
cache-warm-read-queries
Dec 1, 2026
Merged

ymichael merged 1 commit into
mainfrom
cache-warm-read-queries

Conversation

@ymichael

@ymichael ymichael commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

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 Cache prepared statements for timeline window readers #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

The thread list, thread detail, head state, outline, count, child summary,
prompt history and execution-default reads compiled their SQL on every
call. They now bind values as placeholders and reuse one prepared
statement per connection, keyed by shape where options change the SQL.
Thread and event type lists bind as one JSON array through json_each.

The warm-read check drops its "not cached yet" list. Tests that counted
prepare calls as a proxy for query executions now count executions, and
the query-plan test guard looks statement methods up at call time so
execution recording sees cached statements.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 34901bf into main Dec 1, 2026
35 checks passed
@ymichael
ymichael deleted the cache-warm-read-queries branch December 1, 2026 19:19
ymichael added a commit that referenced this pull request Dec 2, 2026
…#8572)

## Human comments

## What was wrong

#8497 listed five timeline readers in `packages/db/src/data/events.ts`
that rebuilt their Drizzle query and called SQLite `prepare()` on every
call. Two of them, `listTodoSnapshotEventRowsForThread` and
`getLatestModelFallbackRowSinceTurnRequest`, were already cached on main
by #8490. The other three were not: `isTimelineCursorSequencePresent`,
`listTimelineInterruptionRows` and `listTimelineWindowHintsDescending`.
Each call paid for compiling the SQL again, and SQLite prepared the
statement again.

## What changed

- The three readers now build their query once per connection through
`prepareCachedQuery`, with placeholders for their fixed scalar
arguments. This is the same pattern their sibling readers use.
- `listTimelineWindowHintsDescending` changes from a raw `db.all(sql…)`
to the query builder. It keeps the same `INDEXED BY
events_thread_type_sequence_idx`, the same predicates and the same
`DESC` order and limit.
- The three readers accept `DbQueryConnection`, so calls inside a
transaction use the same cache.
- `EXPLAIN QUERY PLAN` is unchanged. All three still search their
original index, and none of them builds a temp B-tree.

## How you verified

- Added the three readers to the case table in
`packages/db/test/data/events-preparation.test.ts`. The table checks
correct results for fresh bindings and inside transactions, with zero
`prepare()` calls after warm-up. All three new cases fail on main and
pass with this change.
- `pnpm exec turbo run typecheck test --filter=@bb/db`: 822 tests pass.
- `pnpm exec turbo run typecheck --filter=@bb/server` passes. The server
timeline, request-path-statements and thread-derived-cache-equivalence
tests pass: 32 files, 298 tests.
- The issue's repro script reports 0 prepares per call for all five
readers. Before this change, three of them reported 1 per call.
- Real data: the events of a 52,700-event thread copied from a
production `bb.db`, with 2,000 warm calls per reader. Old and new code
return identical results.

  | Reader | main | this PR |
  |---|---|---|
  | `isTimelineCursorSequencePresent` | 46.7 µs | 6.4 µs |
  | `listTimelineInterruptionRows` | 142.1 µs | 58.8 µs |
  | `listTimelineWindowHintsDescending` | 26.5 µs | 24.6 µs |

Fixes #8497

> 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.

1 participant