Skip to content

Cache prepared statements for timeline window readers - #8453

Merged
ymichael merged 2 commits into
mainfrom
slopcop/issue-8439
Dec 1, 2026
Merged

ymichael merged 2 commits into
mainfrom
slopcop/issue-8439

Conversation

@bb-slop-cop

@bb-slop-cop bb-slop-cop Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

Six of the timeline window readers in packages/db/src/data/events.ts built a fresh Drizzle query on every call, so each thread open and scroll-back recompiled their SQL and re-prepared the SQLite statement on the server's main thread: the budget floor, root turns, thread window, notices (#8439), plus the byte-budget floor and turn rows. Only advanceTimelineWindowBudgetFloorSequence and listStoredTimelineWindowEventRows reused a cached statement.

What changed

  • The budget floor, root turns, thread window and notices readers use prepareCachedQueryVariant, the same path as their two cached siblings (and Cache prepared statements for queue inspections #8367's queue queries). Thread ID, sequence bounds and the budget offset are bound parameters. The cache key holds only the shape dimensions: output limit, whether there is an upper bound, the diagnostic filter, and the excluded types.
  • findStoredTimelineWindowByteBudgetFloor and listStoredTimelineTurnEventRows reuse a cached raw better-sqlite3 statement (prepareCachedRawStatement). That keeps the byte floor streaming rows and stopping early, and keeps turn rows' unmapped reads. Turn IDs bind as one JSON array through json_each instead of a per-length IN (?, …) list. The plan is unchanged: SEARCH events USING INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=?).
  • The readers share one storedTimelineWindowPlaceholderConditions helper.
  • The regression tests live in events-preparation.test.ts, next to the other cached-read tests.

No wire, CLI, schema or stored-data changes.

How you verified

  • The issue's repro script on main: 10 warm calls cause 10 statement preparations for each of the four readers. On this branch: 0.

  • Real data: a VACUUM INTO snapshot of a production bb.db (3.8 GB), on the 30 threads with the most events. Main's and this branch's events.ts were loaded in one process and alternated per batch (CPU time, median of 20–30 batches). Rows are identical for every thread.

    Reader main branch saved
    budget floor (1,500-event budget) 903µs 806µs 97µs
    budget floor ("has older" check) 136µs 40µs 97µs
    root turns 755µs 645µs 110µs
    thread window 320µs 138µs 182µs
    notices 289µs 79µs 210µs
    byte-budget floor 1,389µs 1,263µs 126µs
    turn rows (1–37 turns) 5,965µs 4,806µs 1,159µs

    A real buildThreadTimelineWithProfile latest page plus one older page prepares 22.9 statements on the first commit versus 33.6 on main. Whole-build wall-clock times on that host were dominated by unrelated load, so this PR reports per-reader CPU time.

  • Tests: for each of the six readers, a test reads several window shapes, a second thread and narrower bounds, then asserts identical results with zero sqlToQuery compilations and zero prepare calls. A second test checks that output-limit variants stay apart in the row readers. Two mutations fail these tests: inlining the bound values into the cached byte floor, and dropping the output limit from the turn-rows key.

  • pnpm exec turbo run typecheck lint lint:type-aware test --filter=@bb/db: typecheck and lint pass, and 788 tests pass. Locally, queued-message-state.test.ts and queued-thread-messages.test.ts fail the query-plan guard on isThreadQueueAutoSendPaused. That code is untouched, and the failure also happens with main's events.ts.

  • pnpm exec turbo run test --filter=@bb/server -- test/services/threads/: 385 tests pass. issue-2677-repro.test.ts fails locally on the same queue query-plan guard, also with main's events.ts.

Fixes #8439

AGENT GENERATED

🤖 Generated with Claude Code

findStoredTimelineWindowByteBudgetFloor and listStoredTimelineTurnEventRows
still compiled and prepared their SQL on every timeline build. Both now
reuse a per-connection raw better-sqlite3 statement, so the byte-budget
floor keeps streaming rows and stopping early, and turn rows keep their
unmapped reads. Turn IDs bind as one JSON array through json_each, which
keeps the events_thread_turn_type_item_sequence_idx (thread_id, turn_id)
plan and replaces the per-length IN lists.

The timeline readers share one placeholder-condition helper, and the
cache tests move into events-preparation.test.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 49b9239 into main Dec 1, 2026
36 checks passed
@ymichael
ymichael deleted the slopcop/issue-8439 branch December 1, 2026 05:34
scowalt pushed a commit to scowalt/bb that referenced this pull request Dec 1, 2026
## Human comments

## What was wrong

Six of the timeline window readers in `packages/db/src/data/events.ts`
built a fresh Drizzle query on every call, so each thread open and
scroll-back recompiled their SQL and re-prepared the SQLite statement on
the server's main thread: the budget floor, root turns, thread window,
notices (get-bb#8439), plus the byte-budget floor and turn rows. Only
`advanceTimelineWindowBudgetFloorSequence` and
`listStoredTimelineWindowEventRows` reused a cached statement.

## What changed

- The budget floor, root turns, thread window and notices readers use
`prepareCachedQueryVariant`, the same path as their two cached siblings
(and get-bb#8367's queue queries). Thread ID, sequence bounds and the budget
offset are bound parameters. The cache key holds only the shape
dimensions: output limit, whether there is an upper bound, the
diagnostic filter, and the excluded types.
- `findStoredTimelineWindowByteBudgetFloor` and
`listStoredTimelineTurnEventRows` reuse a cached raw better-sqlite3
statement (`prepareCachedRawStatement`). That keeps the byte floor
streaming rows and stopping early, and keeps turn rows' unmapped reads.
Turn IDs bind as one JSON array through `json_each` instead of a
per-length `IN (?, …)` list. The plan is unchanged: `SEARCH events USING
INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND
turn_id=?)`.
- The readers share one `storedTimelineWindowPlaceholderConditions`
helper.
- The regression tests live in `events-preparation.test.ts`, next to the
other cached-read tests.

No wire, CLI, schema or stored-data changes.

## How you verified

- The issue's repro script on main: 10 warm calls cause 10 statement
preparations for each of the four readers. On this branch: 0.
- Real data: a `VACUUM INTO` snapshot of a production `bb.db` (3.8 GB),
on the 30 threads with the most events. Main's and this branch's
`events.ts` were loaded in one process and alternated per batch (CPU
time, median of 20–30 batches). Rows are identical for every thread.

  | Reader | main | branch | saved |
  |---|---|---|---|
  | budget floor (1,500-event budget) | 903µs | 806µs | 97µs |
  | budget floor ("has older" check) | 136µs | 40µs | 97µs |
  | root turns | 755µs | 645µs | 110µs |
  | thread window | 320µs | 138µs | 182µs |
  | notices | 289µs | 79µs | 210µs |
  | byte-budget floor | 1,389µs | 1,263µs | 126µs |
  | turn rows (1–37 turns) | 5,965µs | 4,806µs | 1,159µs |

A real `buildThreadTimelineWithProfile` latest page plus one older page
prepares 22.9 statements on the first commit versus 33.6 on main.
Whole-build wall-clock times on that host were dominated by unrelated
load, so this PR reports per-reader CPU time.
- Tests: for each of the six readers, a test reads several window
shapes, a second thread and narrower bounds, then asserts identical
results with zero `sqlToQuery` compilations and zero `prepare` calls. A
second test checks that output-limit variants stay apart in the row
readers. Two mutations fail these tests: inlining the bound values into
the cached byte floor, and dropping the output limit from the turn-rows
key.
- `pnpm exec turbo run typecheck lint lint:type-aware test
--filter=@bb/db`: typecheck and lint pass, and 788 tests pass. Locally,
`queued-message-state.test.ts` and `queued-thread-messages.test.ts` fail
the query-plan guard on `isThreadQueueAutoSendPaused`. That code is
untouched, and the failure also happens with main's `events.ts`.
- `pnpm exec turbo run test --filter=@bb/server --
test/services/threads/`: 385 tests pass. `issue-2677-repro.test.ts`
fails locally on the same queue query-plan guard, also with main's
`events.ts`.

Fixes get-bb#8439

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: SawyerHood <[email protected]>
Co-authored-by: Michael Yong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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: 4 of 6 timeline window queries in events.ts were left uncached and recompile Drizzle SQL on every thread open and scroll

2 participants