Repository navigation
Fix the #1131 cold stall at its source: index the latest-goal lookup, drop the thread-list GROUP BY - #1204
Conversation
…-list GROUP BY The 11-second cold stall reported in #1131 was not the thread-list query. It was listLatestGoalEventRowsByThreadIds: its ORDER BY made the stats-less planner walk events_thread_sequence_idx and fetch every event row of every listed thread, reading essentially the whole events table per sidebar bootstrap. A tiny partial index over goal events plus a pinned rewrite cuts the cold read count from 444,010 to 357 at 26K threads. The thread-list query itself now computes hasPendingInteraction with a correlated EXISTS instead of a pending_interactions join with GROUP BY threads.id, which removes both temp B-trees. Measured effect is small (the cold cost there is scattered row fetches, not the sort), but it deletes machinery and the results are verified row-identical. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🚨 SLOP COP 🚨 · I am SlopCop. I am reviewing this pull request for security, code quality, performance, architecture, and test coverage. I will also test the changed route when the local product supports that test. |
| ), | ||
| sql`${events}.rowid IN ( | ||
| SELECT latest_goal.rowid | ||
| FROM ${events} AS latest_goal INDEXED BY events_goal_thread_sequence_idx |
There was a problem hiding this comment.
🚨 slopcop/review — Add a query-plan regression test for both rewritten hot paths.
The behavior tests prove result equivalence, but they do not protect the performance contract. Assert that this query uses events_goal_thread_sequence_idx twice. Reject events_thread_sequence_idx and a temporary sort. Also confirm pending_interactions_thread_status_created_idx for the correlated EXISTS query.
This comment is non-blocking. The test will protect the exact failure mode that this pull request fixes.
There was a problem hiding this comment.
Added in f3c6eb3 (packages/db/test/query-plans.test.ts): the latest-goal plan must probe events_goal_thread_sequence_idx exactly twice, must not use events_thread_sequence_idx, and must not use a temp B-tree; the thread-list plan must serve the pending probe from pending_interactions_thread_status_created_idx with no GROUP BY temp B-tree. The tests capture the exact prepared SQL rather than the slow-query log, because the log redacts literals and truncates — either would change the plan under EXPLAIN (a redacted literal no longer implies the partial-index predicate).
SawyerHood
left a comment
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5: SQLite now uses a small goal-only index instead of reading every event. The thread list now asks a simple yes-or-no question for pending input.
Findings
- Low, non-blocking: The new performance contract has no query-plan regression test. I left one inline comment with the required checks.
- I found no security, correctness, migration, architecture, duplication, or current performance defect.
Architecture
The repeated goal-type literals are necessary because SQLite must match the partial-index condition during query preparation. A shared helper would add complexity without a clear benefit.
Validation
- All 359 database tests passed at the exact head SHA.
- The Turbo database type check passed.
- SQLite used
events_goal_thread_sequence_idxfor both goal scans. - SQLite used
pending_interactions_thread_status_created_idxfor the pending-input check. - A local server and browser test returned status 200 for both thread-list routes.
- The row-backed response reported one active goal and one pending interaction.
- All required GitHub CI jobs passed.
- The final GPT-5.6 review gate found no blocking defect.
I found no blocking issue. This GitHub review uses comment status only.
Assert that the latest-goal lookup probes the partial goal index for both the candidate list and the per-thread MAX, with no full-size events index and no temp sort, and that the thread-list pending probe stays on the pending_interactions covering index with no GROUP BY temp B-tree. Co-Authored-By: Claude Fable 5 <[email protected]>
## Summary - Chunk active background-task count reads at 16,377 thread IDs. - Derive that size from the 32,766-variable limit, 11 fixed values, and two uses per ID. - Batch every thread-list event lookup through one variable-budget helper. - Add and pin a covering partial index for background-task events. - Add boundary, route, result-equivalence, migration, and query-plan tests. ## Reproduction I ran the issue reproduction before any change. A list of 16,376 IDs completed. A list of 16,377 IDs failed with `SqliteError: too many SQL variables`. After the fix, lists of 16,377, 16,378, and 32,754 IDs completed. The thread-list response also completed with 32,767 active threads. ## Measurements I used the 1.45 GB synthetic database from #1204. It has 30,000 threads and about 595,000 events. It has no background-task events. Thus, these results measure rejection of unrelated events. Correctness tests use real background-task rows. Each cold sample used a fresh process. I evicted the database page cache with `posix_fadvise(DONTNEED)`. I measured reads with `/proc/self/io`. I capped the NVMe device at 1,000 read IOPS. Each value below is the median of three samples. | Thread IDs | Cold reads before | Cold reads after | Cold time before | Cold time after | Warm time before | Warm time after | |---:|---:|---:|---:|---:|---:|---:| | 5,000 | 4,149 | 3 | 3.96 s | 18.7 ms | 29.1 ms | 18.7 ms | | 15,000 | 6,888 | 3 | 6.87 s | 52.7 ms | 75.5 ms | 53.5 ms | The old plan used `events_thread_type_item_kind_sequence_idx` for both task scans. The fixed plan uses `events_background_task_thread_type_item_sequence_idx` as a covering index for both scans. The query has a literal partial-index predicate and two `INDEXED BY` pins. ## Verification - `pnpm exec turbo run test --filter=@bb/db --force`: 370 tests passed. - The focused server route suite passed all 9 tests. - `pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/server`: passed. - A regression test crosses the old active-task variable boundary. - A regression test compares chunked counts with single-query counts. - A route regression builds 32,767 active thread-list entries. - Query tests cross the goal and request-key limits. - A query-plan test confirms both partial-index scans. - Drizzle generated migration 0089 and its snapshot. Fixes #1205.
…ookup, drop the thread-list GROUP BY (get-bb#1204) ## Summary This PR investigates issue get-bb#1131 with measurements. The result changes the diagnosis. The 11-second cold stall did not come from `listThreadsWithPendingInteractionState`. It came from `listLatestGoalEventRowsByThreadIds`, which the same route calls for every listed thread. Its `ORDER BY` made the planner walk `events_thread_sequence_idx` and fetch **every event row of every listed thread**. On a grown database, that read is close to the whole file. This PR fixes that query with one small partial index and a pinned rewrite. Cold reads for that query drop from **444,010 to 357** at 26K threads. The PR also replaces the thread-list `GROUP BY` + join with a correlated `EXISTS`. That removes both temp B-trees, but measurement shows the temp B-trees were never the real cost. ## How I measured - I built a 1.45GB `bb.db` at the reported scale with the real `migrate()`: 30,000 threads, 594,971 events (issue reports ~595K events, 1447MB events table), 29,842 interactions, 25 pending. I inserted rows in global timestamp order across concurrent threads, so `threads` pages interleave with `events` pages like a real grown file. No `ANALYZE`, because production never runs it. - I ran the real Drizzle query functions from `@bb/db` and captured the exact generated SQL and `EXPLAIN QUERY PLAN`. - Cold means evicted page cache: `posix_fadvise(DONTNEED)` on the db/wal/shm files, fresh process, verified with `/proc/self/io` read counters. - The host has a fast NVMe disk. Absolute cold times transfer badly, so I also report read-syscall counts, and I re-ran cold tests inside a cgroup capped at 1000 read IOPS to model a stressed cloud disk. All cold runs are latency-bound: time ≈ reads ÷ IOPS. ## What the 11.2s actually was `bb thread list --json` at 26,459 visible threads, cold: | query in the route | cold reads | cold (NVMe) | cold (1000 IOPS) | warm | |---|---|---|---|---| | `listThreadsWithPendingInteractionState` | 2,044 | 0.30s | 2.2s | 0.18s | | `listLatestGoalEventRowsByThreadIds` (before) | **444,010** | **10.5s** | ~7 min (projected) | 0.77s | | `listLatestGoalEventRowsByThreadIds` (after) | **357** | **0.10s** | 0.29s | 0.10s | The before-numbers reproduce the issue precisely: 10.5s cold matches the reported 11.2s stall, and 0.77s warm matches the reported ~0.5s warm repeats. Why it happened: the query had `ORDER BY thread_id, sequence`. The stats-less planner served that order from `events_thread_sequence_idx` to avoid a sort, then filtered by type per row. That plan walks and fetches every event row (multi-KB payloads included) of every listed thread. The fix has three parts: 1. A partial index `events_goal_thread_sequence_idx ON events (thread_id, sequence) WHERE type IN ('thread/goal/updated', 'thread/goal/cleared')`. Goal events are rare, so the index stays tiny. 2. The query spells the goal types as SQL literals and pins the index with `INDEXED BY`. Both are required: SQLite cannot match a partial index against a bound parameter, and the stats-less planner assumes every index is table-sized, so it never picks the small one on its own (verified: it kept the big index until pinned). 3. No `ORDER BY`. `sequence` is unique per thread, so the query returns at most one row per thread, and both callers sort or ignore order. I verified the new query returns row-identical results against the old SQL on a dataset with 10,579 goal events across 3,000 threads (2,750 result rows, zero differences). ## The thread-list query itself, and the temp B-tree theory The prior observation was correct: the query used temp B-trees for GROUP BY and ORDER BY, and `bb thread list` walked all threads in id-index order (random page order). The `EXISTS` rewrite in this PR removes the join, the GROUP BY, and one temp B-tree, with row-identical results (verified across 31,309 rows in four query shapes). Measured effect, before → after: | shape | rows | cold reads | cold (1000 IOPS) | warm | |---|---|---|---|---| | `bb thread list` (all visible) | 26,459 | 2,044 → 1,959 | 2.16s → 2.05s | 0.18s → 0.17s | | sidebar bootstrap (active, all projects) | 4,950 | 1,771 → 1,767 | 1.76s → 1.75s | 51ms → 47ms | | one project, active | 169 | 352 → 352 | 0.40s → 0.40s | 6ms | | one project, archived | 731 | 973 → 973 | 1.01s → 1.01s | 19ms | The temp B-trees were a signature, not the cost. The cold cost is the row fetches: the query returns every visible thread row, and those rows sit on ~2,000 pages scattered through the file. No index can remove that. I tested the extremes: - A 24-column covering partial index (the entire row duplicated): helps only the single-project shape (352 → 195 reads), the planner does not pick it for the IN-list sidebar shape, and it abandons it once stats exist. Not shipped. - Full `VACUUM` (contiguous pages) plus the ideal sequential scan: cli-list cold still needs 0.85s at 1000 IOPS. bb never full-vacuums an incremental-mode database in steady state, so real files stay fragmented. So for the thread-list query proper, the honest answer to "can an index make cold fast?" is **no**. About 1,700–2,000 scattered cold reads are inherent at this scale (roughly 2s at 1000 IOPS), and the ~50–170ms warm cost is per-row CPU (26K rows: ~63ms inside SQLite, the rest row mapping), which no index changes. ## Relationship to get-bb#1198 (now closed) and get-bb#1207 I checked these claims against the get-bb#1198 branch (`database-read-service.ts`, `database-read-worker-entry.ts`, `start-server.ts`), not from memory. - get-bb#1198 ran the whole route read inside its worker: the worker entry called `listThreadsWithPendingInteractionState` and `toThreadListEntryResponses`, and the latter reaches `listLatestGoalEventRowsByThreadIds`. So get-bb#1198 **would** have moved the 10.5s read off the event loop. The global freeze would stop: static assets and every other route would stay responsive. - get-bb#1198 would **not** have made the thread list fast. The request itself would still have taken the same ~10.5s cold inside the worker. It would not have 503'd: the request timeout default was 30 seconds (`DEFAULT_DATABASE_READ_TIMEOUT_MS = 30_000`, and the only construction site passed no override), which a 10.5s read does not reach. - The accurate division of labor: **get-bb#1198 contained the blast radius of a slow read; this PR removes the dominant slow read.** One masks the symptom, the other fixes the cause. - get-bb#1198 is now closed. The residual synchronous cost that remains after this PR — the inherent thread-list row fetches, roughly 2s cold at 1000 IOPS at 26K threads, tens of milliseconds on a healthy disk with a warm cache — is tracked in get-bb#1207. ## Related findings (not addressed here) - `listActiveBackgroundTaskCountsByThreadIds` (same route) has the same access-path class: ~4,150 cold reads at 5K threads, ~6,888 at 15K. Worse, it binds the thread-id list twice, so at 16,377 or more visible threads (measured boundary; the double-bound list plus fixed parameters exceeds SQLite's 32,766-variable limit) it throws `too many SQL variables` and the thread-list route fails outright. Tracked separately with a reproduction in get-bb#1205. - The route's per-thread queries all scale with visible-thread count. Pagination for `bb thread list` would cap every term. ## Test plan - `pnpm exec turbo run test --filter=@bb/db`: 359/359 pass. The migration-replay suite forced `CREATE INDEX IF NOT EXISTS` (same pattern as 0084/0086), and the index-inventory expectation in `migrate.test.ts` now includes the new index. - `pnpm exec turbo run test --filter=@bb/server`: 1366/1367 pass; the one failure is `internal-skill-trees.test.ts` expecting file mode 0644 under my machine's umask 0002, which also fails on `main` and is unrelated. - Row-identical result verification for both rewritten queries, described above. Refs get-bb#1131 (measurement basis; deliberately not "Fixes" — get-bb#1131 stays open for the maintainer to close once follow-up get-bb#1205 also lands). Residual event-loop work is tracked in get-bb#1207. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <[email protected]>
## Summary - Chunk active background-task count reads at 16,377 thread IDs. - Derive that size from the 32,766-variable limit, 11 fixed values, and two uses per ID. - Batch every thread-list event lookup through one variable-budget helper. - Add and pin a covering partial index for background-task events. - Add boundary, route, result-equivalence, migration, and query-plan tests. ## Reproduction I ran the issue reproduction before any change. A list of 16,376 IDs completed. A list of 16,377 IDs failed with `SqliteError: too many SQL variables`. After the fix, lists of 16,377, 16,378, and 32,754 IDs completed. The thread-list response also completed with 32,767 active threads. ## Measurements I used the 1.45 GB synthetic database from get-bb#1204. It has 30,000 threads and about 595,000 events. It has no background-task events. Thus, these results measure rejection of unrelated events. Correctness tests use real background-task rows. Each cold sample used a fresh process. I evicted the database page cache with `posix_fadvise(DONTNEED)`. I measured reads with `/proc/self/io`. I capped the NVMe device at 1,000 read IOPS. Each value below is the median of three samples. | Thread IDs | Cold reads before | Cold reads after | Cold time before | Cold time after | Warm time before | Warm time after | |---:|---:|---:|---:|---:|---:|---:| | 5,000 | 4,149 | 3 | 3.96 s | 18.7 ms | 29.1 ms | 18.7 ms | | 15,000 | 6,888 | 3 | 6.87 s | 52.7 ms | 75.5 ms | 53.5 ms | The old plan used `events_thread_type_item_kind_sequence_idx` for both task scans. The fixed plan uses `events_background_task_thread_type_item_sequence_idx` as a covering index for both scans. The query has a literal partial-index predicate and two `INDEXED BY` pins. ## Verification - `pnpm exec turbo run test --filter=@bb/db --force`: 370 tests passed. - The focused server route suite passed all 9 tests. - `pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/server`: passed. - A regression test crosses the old active-task variable boundary. - A regression test compares chunked counts with single-query counts. - A route regression builds 32,767 active thread-list entries. - Query tests cross the goal and request-key limits. - A query-plan test confirms both partial-index scans. - Drizzle generated migration 0089 and its snapshot. Fixes get-bb#1205.
## Human comments ## What was wrong `listLatestThreadStateEventRowsByThreadIds` correlates a latest-state `MAX(sequence)` lookup with every outer state-event row in a multi-thread batch. In the observed SQLite plan, threads containing many unrelated extension-state events cause repeated scans and `json_extract` calls, particularly when there is no matching `provider-codex/goal` state. This synchronous read blocks the server event loop during sidebar bootstrap. The issue remains reproducible on `main` at `75308f407660efe0f93ffb9626936e5067b5bb03`; the historical fix in [#1204](#1204) addressed the older latest-goal access path, not this current amplification. ## What changed - `packages/db/src/data/events.ts`: replace the outer state-event scan and correlated `MAX` with a `VALUES` list of requested thread IDs and one descending scalar `rowid` lookup per requested thread. - Retain the existing pinned partial index, type/kind filtering, SQLite-variable batching, ID deduplication, and returned stored-event row fields. - Expand semantic and query-plan coverage for multi-thread histories, unrelated extension kinds, absent states, duplicate/empty inputs, and real results across the SQLite variable-limit boundary. - No new index, schema migration, public API, CLI, or server/daemon wire change. ## How you verified - The multi-thread query-plan regression fails with the original query and passes after the rewrite. - Focused event/query-plan suites: 137 tests passed. - Complete `@bb/db` suite: 568 tests across 48 files passed on the final patch. - `pnpm exec turbo run typecheck --filter=@bb/db`: passed, including the cross-batch fixture. - Formatter and `git diff --check`: passed on all three changed files. - A read-only code review identified a SQLite-version-sensitive plan-detail assertion; it was replaced with stable SQL/index assertions before the final full-suite run. - Synthetic migrated-database benchmark using the exact old SQL and the actual patched source function, Node v22.22.1, 6 threads, unrelated state payloads of 4,141 bytes, three warm runs per size: | State events per thread | Original SQL median | Patched source median | | --- | ---: | ---: | | 100 | 44.644 ms | 1.786 ms | | 250 | 337.071 ms | 3.168 ms | | 500 | 1,332.262 ms | 6.009 ms | The requested kind is absent in this benchmark, forcing the worst-case unrelated-state scan. Result IDs are identical for every run. These are query timings, not end-to-end mobile measurements. Functional legacy-goal/extension-state results are covered by the repository tests. No private database, prompts, tool outputs, credentials, or logs containing user content are included in this change. Commands: ```sh pnpm exec turbo run test --filter=@bb/db -- test/data/events.test.ts test/query-plans.test.ts --maxWorkers=2 pnpm exec turbo run test --filter=@bb/db -- --maxWorkers=2 pnpm exec turbo run typecheck --filter=@bb/db pnpm exec oxfmt --check packages/db/src/data/events.ts packages/db/test/data/events.test.ts packages/db/test/query-plans.test.ts ``` > AGENT GENERATED
Summary
This PR investigates issue #1131 with measurements. The result changes the diagnosis.
The 11-second cold stall did not come from
listThreadsWithPendingInteractionState. It came fromlistLatestGoalEventRowsByThreadIds, which the same route calls for every listed thread. ItsORDER BYmade the planner walkevents_thread_sequence_idxand fetch every event row of every listed thread. On a grown database, that read is close to the whole file.This PR fixes that query with one small partial index and a pinned rewrite. Cold reads for that query drop from 444,010 to 357 at 26K threads. The PR also replaces the thread-list
GROUP BY+ join with a correlatedEXISTS. That removes both temp B-trees, but measurement shows the temp B-trees were never the real cost.How I measured
bb.dbat the reported scale with the realmigrate(): 30,000 threads, 594,971 events (issue reports ~595K events, 1447MB events table), 29,842 interactions, 25 pending. I inserted rows in global timestamp order across concurrent threads, sothreadspages interleave witheventspages like a real grown file. NoANALYZE, because production never runs it.@bb/dband captured the exact generated SQL andEXPLAIN QUERY PLAN.posix_fadvise(DONTNEED)on the db/wal/shm files, fresh process, verified with/proc/self/ioread counters.What the 11.2s actually was
bb thread list --jsonat 26,459 visible threads, cold:listThreadsWithPendingInteractionStatelistLatestGoalEventRowsByThreadIds(before)listLatestGoalEventRowsByThreadIds(after)The before-numbers reproduce the issue precisely: 10.5s cold matches the reported 11.2s stall, and 0.77s warm matches the reported ~0.5s warm repeats.
Why it happened: the query had
ORDER BY thread_id, sequence. The stats-less planner served that order fromevents_thread_sequence_idxto avoid a sort, then filtered by type per row. That plan walks and fetches every event row (multi-KB payloads included) of every listed thread. The fix has three parts:events_goal_thread_sequence_idx ON events (thread_id, sequence) WHERE type IN ('thread/goal/updated', 'thread/goal/cleared'). Goal events are rare, so the index stays tiny.INDEXED BY. Both are required: SQLite cannot match a partial index against a bound parameter, and the stats-less planner assumes every index is table-sized, so it never picks the small one on its own (verified: it kept the big index until pinned).ORDER BY.sequenceis unique per thread, so the query returns at most one row per thread, and both callers sort or ignore order.I verified the new query returns row-identical results against the old SQL on a dataset with 10,579 goal events across 3,000 threads (2,750 result rows, zero differences).
The thread-list query itself, and the temp B-tree theory
The prior observation was correct: the query used temp B-trees for GROUP BY and ORDER BY, and
bb thread listwalked all threads in id-index order (random page order). TheEXISTSrewrite in this PR removes the join, the GROUP BY, and one temp B-tree, with row-identical results (verified across 31,309 rows in four query shapes). Measured effect, before → after:bb thread list(all visible)The temp B-trees were a signature, not the cost. The cold cost is the row fetches: the query returns every visible thread row, and those rows sit on ~2,000 pages scattered through the file. No index can remove that. I tested the extremes:
VACUUM(contiguous pages) plus the ideal sequential scan: cli-list cold still needs 0.85s at 1000 IOPS. bb never full-vacuums an incremental-mode database in steady state, so real files stay fragmented.So for the thread-list query proper, the honest answer to "can an index make cold fast?" is no. About 1,700–2,000 scattered cold reads are inherent at this scale (roughly 2s at 1000 IOPS), and the ~50–170ms warm cost is per-row CPU (26K rows: ~63ms inside SQLite, the rest row mapping), which no index changes.
Relationship to #1198 (now closed) and #1207
I checked these claims against the #1198 branch (
database-read-service.ts,database-read-worker-entry.ts,start-server.ts), not from memory.listThreadsWithPendingInteractionStateandtoThreadListEntryResponses, and the latter reacheslistLatestGoalEventRowsByThreadIds. So Move thread list reads off the event loop #1198 would have moved the 10.5s read off the event loop. The global freeze would stop: static assets and every other route would stay responsive.DEFAULT_DATABASE_READ_TIMEOUT_MS = 30_000, and the only construction site passed no override), which a 10.5s read does not reach.Related findings (not addressed here)
listActiveBackgroundTaskCountsByThreadIds(same route) has the same access-path class: ~4,150 cold reads at 5K threads, ~6,888 at 15K. Worse, it binds the thread-id list twice, so at 16,377 or more visible threads (measured boundary; the double-bound list plus fixed parameters exceeds SQLite's 32,766-variable limit) it throwstoo many SQL variablesand the thread-list route fails outright. Tracked separately with a reproduction in listActiveBackgroundTaskCountsByThreadIds throws 'too many SQL variables' at ≥16,377 visible threads, failing the thread-list route #1205.bb thread listwould cap every term.Test plan
pnpm exec turbo run test --filter=@bb/db: 359/359 pass. The migration-replay suite forcedCREATE INDEX IF NOT EXISTS(same pattern as 0084/0086), and the index-inventory expectation inmigrate.test.tsnow includes the new index.pnpm exec turbo run test --filter=@bb/server: 1366/1367 pass; the one failure isinternal-skill-trees.test.tsexpecting file mode 0644 under my machine's umask 0002, which also fails onmainand is unrelated.Refs #1131 (measurement basis; deliberately not "Fixes" — #1131 stays open for the maintainer to close once follow-up #1205 also lands). Residual event-loop work is tracked in #1207.
🤖 Generated with Claude Code