Repository navigation
Avoid repeated request scans during retry supersession - #7474
Merged
Merged
Conversation
3 tasks done
ymichael
added a commit
that referenced
this pull request
Nov 14, 2026
Wall-clock timing let other work on a busy runner inflate one side of a comparison, and a 2x step left little room between linear (2x) and the 3x limit. The cost check now times each call by its thread's CPU time, grows both axes 4x (2,500 to 10,000 turns, 375 to 1,500 steps), and fails when cost grows faster than size^1.5 (8x). Measured across all 461 cases: - With every core saturated, no case went above size^1.33; that was 1.21 or less outside one turn-axis case. Wall time at the old 2x step crossed the limit at that load. - Quadratics still fail: the old listGarbageCollectablePluginArtifacts at size^2.12, and the old listLatestClosedSessionsForHosts at size^1.66. The pre-#7474 retry check is still killed after 5 s of wall time. Three seeds keep a floor of projects, schedules and path plugins so their smaller world keeps the mix the cases need. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 14, 2026
Across 21 CI runs of the cost job on 9cb13b1, all passed, but listTimelineOrderingContext measured between size^1.24 and size^1.50, with the worst run exactly on the old size^1.5 limit. The same query measures size^1.09 to 1.18 in a Linux container and locally. Memory-heavy queries scale worse on shared runners under neighbouring load, and repeated measurement within a job cannot remove that. The check now blocks only on signals noise cannot produce: - growth faster than size^2 (16x on the 4x step); - a call killed after 5 s, or a case that throws. It reports GitHub Actions warnings for growth past size^1.5 and for time over a ceiling. The exact request-path statement-count test stays blocking. Checked against known regressions: - the old listGarbageCollectablePluginArtifacts fails at size^2.10; - the pre-#7474 retry query fails when it is killed; - the old listLatestClosedSessionsForHosts warns at size^1.60. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 14, 2026
## Human comments ## What was wrong The slow query in #7473 (fixed by #7474) passed the query-plan checks because every step used an index. Its cost was a correlated subquery that reread every request in the thread for each accepted turn, which is quadratic in history. Nothing measured how query cost grows with data, and nothing ran query functions against a large database. The checks this PR adds found more of the same: two more quadratic queries (one runs on every thread list), a quadratic usage-pruning pass, a per-daemon-batch lookup that read every thread on the host, and several linear-in-history lookups. They also found a coverage hole: 69 exported query functions, including thread search and the sidebar listings, were invisible to every query-function check because they query through a private helper. ## What changed ### Detection 1. **Plan rules** (`packages/db/src/query-plan-audit.ts`, `query-plan-guard.ts`). Plan rules run in every `@bb/db` and `@bb/server` test, and in dev servers with `BB_QUERY_PLAN_AUDIT`. - `correlated-subquery` flags a search on a large table that runs once per outer row. That covers correlated subqueries and `EXISTS` subqueries that SQLite turns into joins, when the search key grows with history. A search on a unique key, or on a bounded column (`turn_id`, `item_id`, `parent_tool_call_id`), is accepted. - `nested-loop` flags an unindexed loop over a CTE or subquery that runs once per history row of a large table. That was the shape of the old `getFirstParentedTimelineBoundarySequence` join. `json_each` and other virtual tables are ignored. - Expression-index terms (`<expr>=?`) now count as equality terms. Without this, the guard called faster expression-index plans "weaker". - On the full `@bb/db` and `@bb/server` suites, the new rules flag 15 callers. All are fixed or allowlisted with a measured reason. 2. **Coverage now includes wrappers** (`packages/db/scripts/query-functions.ts`). - A query function is now an exported function that queries directly, or calls a function in the same file that does. That raises the count from 360 to 429. - The same list drives the "query functions run in tests" checks, and all 429 run in tests. `test/query-functions.test.ts` covers the helper-following. 3. **Cost check across every data file, on two growth axes** (`check:query-costs`). - **Thread history:** 2,500 vs 10,000 turns, with 100-step long turns. - **Turn size:** 500 turns with 375-step vs 1,500-step long turns. One thread also has an open long turn, and 25 cases target it: active-turn checks, unfinished commands, the live timeline window, item spans and lifecycle, buffered deltas, and appending into the open turn. - Every case runs on both axes, and a failure names the axis. - Each axis grows 4× between its smaller and larger world. - **Base thread:** a 10,000-turn thread written through the real event write path. - **Seeded tables:** one case group per area seeds its own tables at about twice the largest real install, and grows them with the same scale: - `threads`: 10,000 threads, search segments, tabs, outlines, 50,000 prompt history entries, pruning work. - `hosts-environments`: 50 hosts, 1,000 sessions, 4,000 environments, 15,000 terminal sessions, projects, attachments. - `plugins`: 100 plugins, artifacts, snapshots, 5,000 storage rows, marketplaces. - `settings-maintenance`: interactions, retained outputs, sweeps, legacy rows for the migrations. - **Timing:** each call is timed by CPU time, not wall time, so other work on a busy runner doesn't count against it. That's the thread's CPU time on macOS and the process's on Linux, where a thread's CPU time only advances at scheduler ticks. - **Blocking rules (CI fails):** only signals timing noise can't produce. - **Quadratic growth:** cost grows faster than size^2 (more than 16×) when the data grows 4×, once the full-scale time reaches 2 ms. - **Kill:** a single call runs past 5 s of wall time. - **Error:** a case throws. - **Warnings (GitHub Actions annotations, not failing):** growth past size^1.5 (8×), and full-scale time over a case's ceiling (250 ms by default). A case that crosses size^1.5 is measured up to 8 times before it's reported. - **Why two tiers:** - Over 21 CI runs on one commit, `listTimelineOrderingContext` measured between size^1.24 and size^1.50. It measures size^1.09–1.18 in a Linux container and locally. Memory-heavy queries scale worse on shared runners, and repeating the measurement within a job doesn't remove that. - Quadratics measure about size^2: the old plugin GC query at 2.10, so it blocks. The old closed-sessions query measures 1.60, so it only warns. - The exact request-path statement-count test stays blocking. - It also fails when any exported query function has no case. - It covers 436 query functions in 461 cases, and takes about 45 s locally. - **Fixture timestamps:** events are spread 30 s apart over each thread's history, ending an hour before the build. Predicates on `created_at`, such as the turn-start deadline sweep's, therefore behave as they do on a real long thread rather than seeing every event as brand new. - **New flags:** - `--group <names>` runs a subset. - `--db <copy>` migrates a `VACUUM INTO` copy of a real database, seeds the full-scale world into it, and checks the ceiling and kill rules against real data shapes. It refuses `~/.bb/bb.db`. 4. **Server `events` queries moved into `@bb/db`.** - The server used to build SQL against `events` directly in three files. That covered the edit path, thread-start staleness, provisioning cancellation and the turn-start deadline sweep. It now goes through `@bb/db`, so the cost check and the "query functions run in tests" check cover it. - Five call sites reuse existing data functions. - Seven are new: `findStoredEditMessageOperationRow`, `findLatestEditableUserTurnRequestRow`, `hasStoredThreadInterruptedSince`, `hasStoredProviderTurnCompletedSince`, `hasStoredCancelledThreadProvisioning`, `listTurnStartDeadlineCandidates` and `isThreadAwaitingTurnStartPastDeadline`. - No server code queries `events` directly any more. The remaining server queries run against small tables (environments, machines, projects, sessions), where the plan guard is enough. 5. **Statement counts and response size on request paths** (`apps/server/test/perf/request-path-statements.test.ts`). - It runs on both axes: history (100 vs 200 turns) and turn size (750 vs 1,500 steps). - Paths against the running thread include detail, timeline open, outline, context, head state, turn details, a timeline delta while the open turn streams, daemon ingestion into it, send and stop. - A response-size check fails when a response grows more than 1.5× (plus 4 KiB) when the data doubles. - The test runs two servers. The larger has twice the history (100 vs 200 turns) and twice as many other threads (20 vs 40). - It counts statements per path at the better-sqlite3 layer, with full SQL and `IN (...)` lists collapsed. A path fails if any statement runs more often in the larger server. - It covers 24 paths, including thread list, search and count, timeline, outline, turn details, events, prompt history, read/unread, pin, daemon event ingestion, send with a queued retry, edit, stop, fork and periodic sweeps. - Fork and the sweeps are declared linear (copying every event, and budgeted per-thread work) and may grow at most 2.5×. - Counts are exact, so the result doesn't depend on machine speed. 6. **CI.** The `Query Plan Audit` workflow also runs on PRs that change `packages/db`. It has two jobs: - the plan report: stale allowlist entries and untested query functions; - the cost check. ### Fixes the checks found No new indexes and no migration: every fix uses an index that already exists. | Query | Problem | Fix | Before → after (full scale) | |---|---|---|---| | `listGarbageCollectablePluginArtifacts` | artifacts × snapshots: correlated `NOT EXISTS` over unindexed columns, joined with `OR` | non-correlated `NOT IN` sets, built once per query | 81.8 ms, 4.2× growth → 1.15 ms, linear | | `listLatestClosedSessionsForHosts` (every thread list) | rewalked the global closed-session index for every session row | one lookup per host through the existing `host_daemon_sessions_host_status_idx` | 2.34 ms, 3.5× growth → 0.13 ms, flat | | Usage snapshot pruning | the delete for each 16-row chunk walked every usage row of the type | the delete seeks the candidate ids through the primary key | quadratic per thread pass → bounded per chunk | | `listThreadEnvironmentAssignmentsOnHost` (every daemon event batch) | read every thread on the host (with 50 ids, SQLite drove the join from the host) | looks up the batch's thread ids | grew with the threads on the host; now bounded by the batch size | | `getFirstParentedTimelineBoundarySequence` | requests × delegation spans | each span's first matching request through a range seek | 2.9× growth → under 1 ms | | `getStoredTurnRequestEventForTurn` | `json_extract` over every request in the thread | searches backwards from the accepted input's sequence | 7.6 ms → 0.08 ms | | `findLatestUnresolvedClientTurnRequestIdAfterSequence` | scanned the whole thread per pending request | starts at the request's sequence on the type index | 12.8 ms → 0.06 ms | | `listCommandItemDataByItemIds` | scanned the whole thread | seeks by item through the item-lifecycle index | 11 ms → 0.02 ms | | Edit message | loaded every user request with `.all()` | reads one candidate at a time; the acceptance lookup starts at the request's sequence | linear → one row in the common case | | Latest timeline page with a long open turn (found by the turn-size axis) | the page reported every older row of the open turn as `olderRowUpdates`, and every streamed delta re-sent them | reports rows from the first returned leaf when the window cuts inside a segment | delta 266 KB (750 steps) → 1.55 MB (1,500 steps) became 2.3 KB at both sizes; cold open 2.6 MB → 1.03 MB | | `listTimelineOrderingContext` (cold timeline open) | drizzle mapping, and the `json_each` check on every request | raw rows, a fast path for the first input part, JSON columns only where used | 106 ms → 41 ms (still linear by design) | `listEvents` returned a whole thread and only tests called it, so it moved to `@bb/db/testing`. These lookups are linear, unchanged from main, and inside every limit: | Query | Full scale | |---|---| | `listStoredClientTurnRequestRowsByKeys` | 6.7 ms | | `hasStoredTerminalClientTurnRequestEvent` | 3.4 ms | | `listStoredTurnInputAcceptedRowsByClientRequestIds` | 3.2 ms | They have no position to start from. An expression index on the request id would make them flat, but building it reads every events row (12–21 s on a 4.35M-event database), so it isn't worth a migration. ### Known linear costs (measured, under the ceiling) | Query | Full-scale time | Where it runs | |---|---|---| | Conversation outline readers | about 106 ms (117 ms on the real copy) | cold outline cache and `bb thread show` message views | | Thread search | about 48 ms synthetic, 99 ms on the real copy | grows with matching threads | | Cold timeline ordering | about 41 ms | cold timeline open | | `advanceLiveEventPruning` resume | about 30 ms | background sweep; grows with how far the cursor is behind | | The turn-start deadline sweep | per active thread | sweep | `docs/debugging-and-qa.md` documents all the checks. ## How you verified **The checks fail on known-bad queries and responses:** - **Pre-#7474 query:** with #7474 reverted locally, the supersede case is killed after 5 s. - **Span join:** the old query grew 2.9× (10.9 → 31.6 ms) before its fix. - **Plugin artifact GC and closed sessions:** they failed at 4.2× and 3.5× before their fixes. Closed sessions also failed at 3.4× until the query was pinned to the host index. - **Edit path:** with fixture checkpoints removed, the request-path test fails (819 → 1,519 statements). - **Plan rules:** unit tests flag the #7473 SQL and the old span join, and accept the fixed forms. **Full runs on the final branch:** - `check:query-costs`: 436 query functions in 461 cases, all within limits on both axes, in 43 s locally at load 16–23. - Noise margin for the cost check: - Five quiet runs and one with every core saturated (load ~30) all passed. - The highest healthy exponent was 1.33, against the 1.5 limit. With wall time and a 2× step, the same load pushed linear queries past the limit. - `check:query-costs --db` on a fresh `VACUUM INTO` copy of a real 8.8 GB database (4.6M events after seeding): all 429 within limits. The copy was deleted afterwards. - `BB_QUERY_PLAN_REPORT` across all `@bb/db` and `@bb/server` tests, then `check:query-plan-report`: "matches the allowlist (309 findings) and runs all 436 query functions". - The request-path and timeline-pagination tests pass (86). With the pagination fix reverted, the response-size check fails on live timeline open and on the streaming delta. **Targeted tests:** - `@bb/db`: events, threads, sessions, hosts, plugin persistence, thread pruning, queued messages, query plans, plan audit and guard, history fixture, query functions, migrations. - `@bb/server`: perf, event pruning, internal events, edit, restart-resume, runtime display, plugin services. One `builtin-plugins` test failed once under load and passed when rerun on its own. **Static checks:** typecheck and lint for `@bb/db` and `@bb/server`, `oxfmt --check`, and the provider-literal ratchet. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This was referenced Nov 15, 2026
Merged
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.
🚨 SLOP COP 🚨 ·
new-issue-autopilotHuman comments
What was wrong
Retry supersession performed a correlated request-history lookup for each accepted input. When an overtaken retry had no accepted input, an immediate write transaction synchronously repeated JSON scans across the thread history. A newly authored database/API regression reproduced the stall on trusted main in two clean checkouts.
Report: https://get-bb.github.io/reports/issues/7473.html
What changed
Use uncorrelated membership in eligible root/direct-retry request IDs while retaining the accepted-event filters, limit, queue eligibility, and transitions. Add a real migrated-SQLite latency regression plus seven queue-disposition cases, including duplicate request IDs, null/missing acceptance IDs, and thread isolation.
The change stays in the existing queued-message database subsystem: 240 changed text lines (237 additions + 3 deletions), across two files. No dependencies, generated files, migrations, stored-data changes, public protocols, or CLI/API changes.
How you verified
7794941da1b6e2baf017e5f7ab65b5f223fcaf54.pnpm exec turbo run test --filter=@bb/db -- test/data/queued-retry-history.test.ts test/data/queued-thread-messages.test.ts test/data/queued-message-waits.test.ts test/query-plans.test.ts --silent=false— 126 passed.pnpm exec turbo run test --filter=@bb/server -- test/threads/turn-failed-retry.test.ts— 22 passed.pnpm exec turbo run typecheck lint:type-aware --filter=@bb/dbandgit diff --check— passed; no binary changes.The reproduction is synthetic database/API evidence, not a verification of the historical production duration or HTTP/UI latency.
Fixes #7473