Repository navigation
Time server and plugin SQL in the query cost check, and fail every case on its ceiling - #7934
Merged
ymichael merged 5 commits intoNov 20, 2026
Conversation
…se on its ceiling Server code no longer builds queries: every query in apps/server/src moved into packages/db/src/data, and a server test fails on new ones, so check:query-costs, the query-plan guard and the query-functions-run-in-tests check cover them. The account-pool, automations and workflows stores get cost cases in their own plugin databases, plus a plan audit of the statements those cases run, since forkable plugins cannot load the @bb/db test guard. The ceiling now fails instead of warning, scaled by the calibration, for cases that declare growth too; raised ceilings need a reason. Thread search cases seed message segments so the check sees production's match counts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A LIMIT stops a JSON-filtered lookup early only when a row matches; with no match SQLite reads every row the index leaves. Add missing-key variants for the request-id lookups whose cases always found their key, and declare the four that read every request row of the thread. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ows foreign keys better-sqlite3 enforces foreign keys by default, so production plugin databases check them. With checks on, deleting a batch of expired workflow runs scanned workflow_calls once per cascaded call for replayed_from_call_id children (1.1 s at 3,000 retained runs). Index the two self-referencing foreign keys and workflow_workers.run_id. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/query-cost-check-cover-server-side-sql-and-fail-thr_7qqspk9jtd
branch
from
November 20, 2026 23:31
0b8ebb6 to
2576ae0
Compare
ymichael
deleted the
bb/query-cost-check-cover-server-side-sql-and-fail-thr_7qqspk9jtd
branch
November 20, 2026 23:37
This was referenced Nov 20, 2026
ymichael
added a commit
that referenced
this pull request
Nov 20, 2026
## Human comments ## What was wrong `searchThreadsWithPendingInteractionState` returns at most `limitPerGroup` (≤ 50) threads per group, but to get there it found every matching thread and ranked and counted all of them (`ROW_NUMBER()` and `COUNT(*) OVER (PARTITION BY archived)`). It reached each matching segment's thread through `thread_search_segments`, whose rows hold the message text, so a common word read and sorted roughly 200k text-heavy rows to return 20 threads. Measured on the Nov 20 production copy, FTS itself costs 3.5 ms for `the` (218k segments); the time goes to these row reads and the ranking. In production this was 2,006 ms wall with 186 ms CPU (mostly I/O), and it caused the worst event-loop stall in the logged window (2,061 ms). ## What changed - `packages/db/src/data/threads.ts`: the search query is rewritten. - FTS runs once per word into one materialized set of (segment, word) keys. Every membership test reads that set through a single `IN` expression inside one CTE, so SQLite builds its lookup once (`REUSE LIST SUBQUERY`). Separate per-word sets were rebuilt at every use and made multi-word queries ~3x slower. - Each group walks threads in result order (titles first, then most recent) through a new index and stops when the page is full. The per-thread checks read only the covering indexes on `thread_search_segments`. Full rows are read only for the page's own segments. - When the query's rarest word matches at most 1,000 segments, the walk visits only those segments' threads. This keeps rare queries from walking every thread. 1,000, 5,000 and 10,000 gave the same total time over the 1,000-call set below, so the lowest bound on text-row reads won. - The message shown per thread is picked by `source_seq`, the same result as before: each message segment is keyed by its own event sequence, and titles have a null `source_seq`. - `packages/db/drizzle/0164_thread_search_order_index.sql`: partial index `threads ((archived_at IS NOT NULL), updated_at, id) WHERE deleted_at IS NULL AND visibility = 'visible'` on the small `threads` table. No index on `events`. - **Behaviour change: group totals stop at 100.** `total` counts matching threads up to 100, and each group gains `totalCapped: boolean`, true when more than 100 threads match (`total` is then 100). The field is additive, so existing readers keep working. The app does not show totals (the palette and archived settings read only `results`), and the tasks plugin ignores them. The only place they show is the JSON from `bb thread search --json` / `sdk.threads.search`. I updated the CLI JSON shape (`apps/cli/src/json-shapes.ts`) and `bb-guide-json.md`. The contract change ships in the plugin SDK types, so the SDK is bumped to 0.6.175. - `query-plan-allowlist.ts`: removed the stale `ordered_threads` entry. Added `correlated-subquery` and `nested-loop` entries on `thread_search_segments` for this function, with reasons: the walk is bounded by the page and by 101 counted matches, and `query_tokens` has one row per search word. - `threads-cases.ts`: on the realistic search seed from #7934 (about 48 segments per thread), the case grows 3.4–3.85x across the 16x history world, because the FTS key set holds every matching segment. It keeps a `growsWith` declaration with that reason rather than passing just under the undeclared 4x limit, and drops #7934's raised 250 ms ceiling, so the default ceiling applies. ## How you verified Real data: a private copy of the Nov 20 production database (5,150 threads, 248,531 search segments) with the migration applied. Old and new code ran in the same process on the same file, warm cache. Median of 7 calls, `limitPerGroup=20`: | query | main | this PR | |---|---:|---:| | `the` | 207.1 ms | 36.5 ms | | `fix` | 107.2 ms | 16.3 ms | | `test` | 135.7 ms | 23.0 ms | | `bb` | 113.8 ms | 16.0 ms | | `pr` | 163.6 ms | 25.0 ms | | `a` | 358.3 ms | 86.7 ms | | `e` | 212.9 ms | 41.5 ms | | `thread search` | 97.0 ms | 33.8 ms | | `server perf query` | 82.6 ms | 43.0 ms | | `fix the bug` | 180.4 ms | 89.3 ms | | `search ranking` | 14.0 ms | 21.0 ms | | `kubernetes` (7 segments) | 0.8 ms | 2.4 ms | | `zzzqx` (no match) | 0.1 ms | 1.6 ms | The last three are slower by a few milliseconds. Rare and no-match queries now build the set and probe the rare path. In `search ranking` both words are too common for the rare path but seldom appear together, so the walk visits more threads. One-letter words keep a ~57 ms floor: FTS has no prefix index for one character, so it scans the term list either way. Equivalence: 250 queries (random words and prefixes from real titles and prompts, plus hand-picked edge cases), each at limits 1, 5, 20 and 50, for 1,000 calls in total. Every page was identical to main, matches and snippets included. Every `total` equalled `min(main's total, 100)`, and `totalCapped` was set exactly when main's total was above 100. Total time for the 1,000 calls: 109.1 s on main, 43.5 s on this branch. `check:query-costs --group threads`, after rebasing onto #7934's seed: `searchThreadsWithPendingInteractionState` measures 7.15 → 24.28 ms (3.4x) here, under the default ceiling; #7934 had raised its ceiling to 250 ms on main. Tests: - `packages/db/test/data/thread-search.test.ts` gains two tests. - "stops counting a group's matches past the counted maximum": 101 matches report 100 with `totalCapped: true`; after one is deleted, 100 matches report 100 with `totalCapped: false`. - "matches the same threads whichever word is rare or common": the rare path with the rare word in either position, and the walk when every word is common. During development I bound the word count as a parameter by mistake: SQLite receives it as a float, so `key / K` is no longer exact and the rare path returned nothing. This test fails when that bug is reintroduced. - Migration replay tests rewind the new index through `dropThreadSearchOrderIndex` in `test/helpers/rewind.ts`, like earlier migrations. - Run locally, all passing under the query-plan guard: the full `@bb/db` suite (738), server `public-thread-search` + `request-path-statements` (70), app palette/search/cache-owner (126), cli `json-shapes` + `startup-graph` (10). - `turbo run typecheck` for db, server-contract, sdk, server, app and cli. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 23, 2026
…es experiment (#7864) ## Human comments ## What was wrong Each machine knows its bb server by one URL, the one it was installed with. When that route stops working (for example the home internet drops for a bb connect-enrolled machine sitting on the server's own LAN, or a tailnet goes down), the machine disconnects even though another route to the same server would work. The server also had no stable identity a client could check a route against, and server access was one "connection method" per server (`defaultMachineAccess`) rather than a set of routes. ## What changed Server (behind the new early adopter experiment `serverRoutes`; while it is off, the server advertises `routes: []`, the Local network route does not exist, and daemons behave exactly as on main, including the Tailscale plugin's address being admitted by the Host/Origin guards): - Stable `serverId` (`srv_<hex>`, stored in bb.db so it survives restarts and moves with `bb server move`), returned by `/health`, system config, daemon session open, `bb status --json` and `bb server access list --json`. - Every set-up server access provider is a route; there is no per-route on/off. `serverAccessOrder` replaces `defaultMachineAccess`, and `localNetworkEnabled` (default off) adds the Local network route. Plugin routes are routes while their plugin reports them available and are turned off in the plugin's settings; Manual is a route while `machineServerUrl` is set. Providers declare `routeKind` (`local-network | private-overlay | relay | custom`) for default ranking; bb connect declares `relay` and the Tailscale plugin (#7862) declares `private-overlay`. Kind ranking applies only with `serverRoutes` on; while it is off, providers rank by the user's order, then #7862's earliest-installed-plugin order, then Manual, as the single default route did on main. Providers of one kind keep #7862's earliest-installed-plugin order, not load order. Plugin SDK 0.6.188. `routeKind` is required in the SDK types; registration still accepts a declaration without it, from a plugin built against an older SDK, and treats it as `custom` (marketplace installs bundle with esbuild without type-checking, so such plugins still install); documented under the existing `bb.experimental_serverAccess.register` entry in `docs/api_to_audit.md` and in the Plugin Guide surface. - Per-host grants (`host_server_access_grants`); the install route stays the host's anchor. Enrollment falls back to the next enabled route when one needs setup. - New machines install on the first working route in that order, with Local network last (a laptop's install route should not be a LAN address). A migrated Tailscale default keeps installing on Tailscale even with bb connect on, and ordering alone puts Tailscale first with the experiment on too. - Core Local network provider: extra in-process listeners on the machine's private LAN IPv4s (no restart). Removing it closes the listeners and drops connections already upgraded over them. - Routes appear in system config and the session-open response, and are pushed live with a new `server-routes.replace` WS message. The daemon reports its route with a new `session.route` message; each daemon session stores it. - The Host/Origin guards admit enabled routes' addresses. The admitted set is persisted in `app_settings_values` (`serverAccessOrigins`) and restored in `createApp` before the listener, so route hostnames work from the first request after a restart. An address survives a failed or timed-out availability check and is dropped on a definite answer, when the route is turned off, or when its plugin is disabled or removed. This replaces #7862's copy of the same mechanism. Plugin providers' addresses (Tailscale, bb connect) are admitted whether or not `serverRoutes` is on, as on main. Core's Local network and Manual addresses are admitted only while it is on. `experimental_serverAccess.recheck()` still refreshes the set directly, as #7862 does. - UI and CLI: Settings → Machine access becomes "How devices reach this server" (the routes that are set up, in order; Local network and Manual have a menu with Remove, plugin routes link to their settings; **Add a route** offers the rest), Settings → Machines shows "via <route>", `bb server access list|add|remove|order` (`add`/`remove` cover `local-network` and `direct`), and a Route column in `bb machine list`. - Migration 0167 copies existing grants and `defaultMachineAccess` into the new model but keeps `hosts.server_access_grant_id` and the old setting row for one release, so going back a version works; the anchor grant id is mirrored into the old column. Host daemon: - Candidates are the learned routes in server order plus the install URL. Every dial probes `/health` plus a `serverId` check on all of them in parallel (2 s timeout; route i may win after i × 500 ms), sending each route only its own headers (the bb connect credential goes only to bb connect). - No mid-session switching: it stays on a working route until the connection drops, then picks again. With `resumeDaemonSessions` it keeps its session across the switch. - Learned routes persist in `<data dir>/server-routes.json`, not `config.json`, whose strict schema would make an older launcher refuse the file after a rollback. - Attachment and self-update downloads prefer an encrypted route; the bb connect gate comes from the relay route; machine-auth-proxy follows the active route. Wire changes: `HOST_DAEMON_PROTOCOL_VERSION` 278 → 279 (`serverRoutes` in session open, `route` in the session-open request, `server-routes.replace`, `session.route`). Docs: `docs/multiple-devices.md`, `docs/configuration.md`, `docs/api_to_audit.md`, `bb guide machines`/`customization`, the bb-cli command index, the plugin-authoring machines reference, and the Tailscale plugin's skill and overview. These no longer say "choose Tailscale as the connection method" or `defaultMachineAccess tailscale`. Not in this PR: desktop and mobile route selection (later PRs), the prototype's `x-bb-gate-*` peer-address strip (replaced by a separate auth change), and the better-route check, flap holds and backoff (a later shared-policy PR). ## How you verified Tests added, each failing before its fix: - `apps/host-daemon/src/server-routes.test.ts`: ranking with head start, `serverId` mismatch rejected, per-route headers, failover and return on redial, current route kept when nothing answers, no probing or saving while the server advertises no routes, persistence outside `config.json`. - `apps/host-daemon/src/server-connection.test.ts`: stays on its working route after learning better ones, then fails over and reports `session.route` on each redial. - `apps/server/test/services/machines/server-routes.test.ts`: experiment off advertises nothing and acquires no grants; LAN advertised as soon as it is added; LAN connections dropped when it is removed; new machines install on Local network only when nothing else works; route addresses admitted from the first request after a restart (fresh modules); address kept through a failed check and dropped on a definite answer; Manual's address refused once its URL is cleared; with the experiment off a plugin route's address stays admitted and Manual's is dropped. - `apps/server/test/services/machines/server-access.test.ts`: a declaration without `routeKind` (an older plugin) registers on the real and fake hosts and ranks as `custom` (fails without the registration default); install route prefers relay/custom over private-overlay/local-network with the experiment on; with it off, the user's first route and then the first registered plugin win over the relay (fails without the gate: a Tailscale-first order installed on the relay). #7862's tests stay as they were (address admitted until lost, kept across a restart and a failed check, dropped on plugin disable). Its "defaults to the earliest-installed plugin" test now checks route order and the install route instead of the removed `defaultProviderId`. - `packages/db/test/migrate.test.ts`: migration copies grants and the default without dropping the old column or row. Commands (all green): `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`; `pnpm exec turbo run test` for every changed package (app, cli, demo-server, host-daemon, server, db, domain, host-daemon-contract, plugin-sdk, sdk, server-contract, templates, test-helpers, bb-guide, connect, environment-modal-sandbox, plugin-api-docs); `pnpm exec turbo run test --filter=@bb/integration-tests --force`. Counts below. After rebasing onto main at 76d4358: - typecheck + lint: 167/167 turbo tasks. - Package tests: 33/33 turbo tasks across the changed packages, which now include the Tailscale plugin (server 4,432). Three server tests failed once under full parallel load and passed when rerun: two in `install-machine-script.test.ts` and `plugin-install.test.ts`'s git fallback. db, server and host-daemon were rerun after the final rebase onto #7934, which moves server SQL into `@bb/db` data modules (13/13 tasks). Following #7934, `server-access.ts` writes host columns through `setHostColumns`, and `sql-in-data-modules.test.ts` passes. - After the final rebase onto 76d4358: 21 test tasks for db, server, host-daemon, host-daemon-contract, plugin-sdk, cli, app, Plugin Guide, bb connect, Tailscale and bb-guide. All passed except one plugin-sdk process-kill test that timed out under load and passes alone. - Integration (`--force`, not a cache replay): 31/31 files, 80/80 tests. - `pnpm exec turbo run check:query-costs --filter=@bb/db`: passes under #7923's stricter growth check; cases added for every new query function (`getOrCreateServerId`, `get/setServerAccessOrigins`, the grants table functions, `recordSessionRoute`); no growth warnings from them. - `plugin-instance-lifecycle.test.ts` "runs a provider callback only on the instance that registered it" now tolerates the background availability refresh on plugin change; it still asserts the stale record never reaches the old instance (same adjustment as the Tailscale plugin PR). Live, on an isolated `pnpm start:worktree` instance with a second enrolled daemon ("Client A") and a TCP relay standing in for a breakable Manual route ordered first, Local network second: - Experiment off: Client A connected on its install URL, learned no routes, wrote no `server-routes.json`; Local network was not offered. - Experiment on: Client A learned all three routes live through `server-routes.replace` and stayed on its working route. After a restart it dialed the saved top route (Manual) in 15 ms; `bb machine list` showed Route "Manual". - Relay down at 19:47:26.094, connected via Local network at 19:47:27.605 (about 1.5 s). Settings showed "Client A · via Local network". After the relay came back it stayed on Local network for 75 s+. - Turning Local network off with the Settings toggle moved Client A back to Manual; with `resumeDaemonSessions` on, session `hses_5zcdm8va5c` resumed across the switch. Turning Local network on from Settings reached the connected daemon at once. - Turning the experiment off: the daemon learned `routes: []` and deleted its routes file, Local network disappeared, and the LAN listeners closed. - Restart window (fix for persisted route addresses): with a Manual route on a hostname (`http://127.0.0.1.sslip.io:25900`), the first requests after a server restart returned `403 forbidden_host` on `/health` and `/api/v1/system/config` before the fix, and `200` on the very first request after it. - Install route: with Local network ordered first and Manual enabled, a new manual machine was installed on Manual (`direct`), not Local network. Re-run after the rebase (it changed the daemon dial path: per-route headers now go through main's compressed WebSocket constructor and send queue), on the same setup: - Client A enrolled on Manual (`http://127.0.0.1.sslip.io:25900`) and learned Manual + 2 Local network routes. - Relay down at 23:29:48.528; connected via Local network at 23:29:50.354 (about 1.8 s). It stayed on Local network for 60 s after the relay came back. - With `resumeDaemonSessions` on, session `hses_bmjc944x9h` resumed across a Manual → Local network switch, and its row recorded `local-network`. Turning Local network off moved it back to Manual. Turning it on reached the connected daemon live. - Experiment off while connected on Manual: the daemon learned `routes: []` and deleted `server-routes.json`, Local network disappeared, and the LAN listeners refused connections. - Restart window: the first request after a server restart to the Manual hostname returned 200 for `/health` and `/api/v1/system/config`. Known limit, unchanged by the rebase: if a daemon was *installed* on a Manual hostname while the experiment was on, it cannot reconnect after the experiment is turned off. The hostname gets `403 forbidden_host` again, which is main's behaviour for a hostname without `BB_APP_URL`. It recovered as soon as the experiment was turned back on. Not exercised live: a real bb connect route (the dev server was unpaired) or a real Tailscale route (unit tests cover its admission with the experiment off). Part of #6748 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
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.
Human comments
What was wrong
check:query-costshad three gaps.packages/db/src/data, but 27 files underapps/server/srcbuilt 232 queries themselves. They included thejson_extractstartup-context scan production logged at 100 ms and the turn-end follow-up reads over thread history (the Timeline request-ID lookups scan event history and can block the server #7899 shape).@bb/db's test guard.growsWithdeclaration removed the growth check, and the 250 ms ceiling only warned, so nothing bounded a declared case. Thread search also measured unrealistically cheap. Its seed indexes only two title segments per thread; the production copy (5,150 threads) has about 48, and "tests" matches 40,192 segments in 4,287 threads there. On that copy, search costs 73–170 ms of CPU per call, warm. The check timed it at 52 ms with 10,000 threads, inside every limit. Production logged 2,006 ms of wall time (186 ms of CPU) for one call.What changed
Server SQL moves into
packages/db/src/data. Moving it, rather than extending coverage, was the only option that makes the existing checks apply. The cost check cannot call server services, which needAppDepsand mix orchestration with SQL, while a data function gets timing, plan auditing and the query-functions-run-in-tests check for free.getThread,getEnvironment,getSessionById).INDEXED BYhints are unchanged, and transactions stay where they were. The startup-contextjson_extractscans move unchanged and are left for S6.auth-api-keys.ts,environment-variables.ts,environment-hook-operations.ts,legacy-automations.ts,legacy-deferred-thread-messages.ts.apps/server/test/sql-in-data-modules.test.tsfails when server code importsdrizzle-ormat runtime or builds a query on adb,txor$clientreceiver. OnHEADit reports the 232 sites; on this branch it reports none. It is a test, not a lint rule, becauseapps/serverhas nolinttask: its.oxlintrc.jsonrules (node:fs, no-comments) never run in CI, and enabling them surfaces 335 existing violations.Plugin databases are covered.
PLUGIN_QUERY_MODULES(packages/db/scripts/query-functions.ts) lists the three stores. The detector now also counts public methods of exported classes that query throughthis.db, which covers account-pool'sQuotaStoreandPoolAffinityStore. The core list (used by the CI query-function jobs) is unchanged.The
plugin-databasesgroups add 70 cases. Each world gets a separate database per plugin, opened asplugin-api.tsopens one (better-sqlite3 is built withSQLITE_DEFAULT_FOREIGN_KEYS=1, so foreign keys are enforced), migrated with the plugin's own statements and seeded at about twice a heavy user:The check explains every statement those cases run and fails on the guard's rules for each group's
auditedTables, unless the group'sallowedFindingslists the finding with a reason.The cost workflow now also runs when those modules change, and installs the three plugins' dependencies.
@bb/db#typechecktakes the plugin sources as Turbo inputs, becausepackages/db/tsconfig.jsonrootDiris now../..so the cases can import them.The ceiling fails.
Plugin costs the check found.
deleteTerminalRunsis fixed in this PR. It took 66 → 1,122 ms (17x) at 3,000 retained runs with 20 calls each. Every cascaded call deletion scannedworkflow_callsforreplayed_from_call_idchildren, and every run deletion scannedworkflow_runsforresumed_from_run_idchildren, because neither foreign-key child column had an index. An appended workflows migration adds partial indexes on both columns, plusworkflow_workers(run_id), whose delete was scanning every worker. Afterwards it takes 0.84 → 0.99 ms (1.2x), and the declaration and allowed finding are gone. The tables are small plugin tables, and the migration only adds indexes.data.test.tsnow finds the worker-ownership migration by content, not by its position from the end.listExpiredTerminalRunsstill walks every retained run, declared: 1.74 → 21.8 ms. The new run index halved it from 41 ms, so it no longer needs a raised ceiling.recordWorkerCleanupstill scans every archived worker, declared: 0.46 → 6.8 ms.listRunningAutomationRunsscan of the partial single-flight index is allowed: that index holds at most one row per automation.Missing-key variants for JSON-filtered lookups. A LIMIT stops a lookup that filters
eventsby a JSON value early only when a row matches; with no match SQLite reads every row the index leaves. To find the lookups, I ran every cost case against the small world, recording each executed statement that reads a large table and usesjson_extract/json_type/->>afterWHEREorON. 49 functions qualify.About a dozen are range readers that filter a window they already bound: timeline windows, outline rows, the event copy and the cursor sweeps. A miss changes nothing for them.
17 cases already miss their key, including
listStoredTurnRejectedRowsByClientRequestIds,hasStoredSpawnAgentToolCall,getLatestModelFallbackRowSinceTurnRequest,getLatestCompletedThreadContextClearSequence,hasStoredManualStopInterruptionAfterSequence,findStoredEditMessageOperationRow, the provisioning lookups moved from the server, andisThreadQueueAutoSendPaused. They measure flat (0.01–0.13 ms) because the fixture holds few rows of those event types, so they don't stress a miss.The keyed lookups whose cases always found their key now have a
missing keyvariant. Request ids live only in JSON, and(thread_id, type, sequence)is the tightest existing index (the largest real thread has 3,149 requests), so none can be bounded without a neweventsindex:supersedeQueuedRetriesInTransaction, retried request missingfindLatestEditableUserTurnRequestRow, every request sent by a parent thread (a worker thread)listStoredClientTurnRequestRowsByKeys, request row missinggetStoredTurnRequestEventForTurn, accepted input whose request row is missingfindLatestUnresolvedClientTurnRequestIdAfterSequence, every request resolvedThe unresolved-request lookup grows 15x (to 14 ms) when it searches from sequence 0. Its only caller (
internal/events.ts) searches after the last completed turn, which bounds it, and the variant looks up what the caller looks up.docs/debugging-and-qa.mddocuments the server rule, the plugin coverage and the failing ceiling.How you verified
pnpm exec turbo run check:query-costs --filter=@bb/dbpasses locally with no warnings in 51 s (48 s before). Before the plugin databases were split out, the same run failed on the collision between the automations plugin'sautomationstable and the legacy core table, which is why each plugin gets its own database.deleteThreadEventSuffixInTransaction59 ms, workflows retention 44 ms.check:query-costs --group workflowswith foreign keys enforced, as in production:deleteTerminalRunstakes 1,122 ms before the indexes and 0.99 ms after. A connection opened with better-sqlite3's defaults reportsforeign_keys = 1; thesqlite3CLI reports 0 only because its build defaults differ.pnpm --filter bb-plugin-workflows test:data.test.tspasses. Sevenservice-policy.test.tsrestart and notification tests fail locally with or without this change, and with this thread'sBB_*environment stripped. They depend on timing and pass in CI's plugin shards./tmp/bb-perf-shared/bb-copy.dbread-only.pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/serverpasses, andpnpm exec turbo run lint --filter=@bb/dbpasses.check:query-costs --group events,queued-thread-messagespasses with the missing-key variants.apps/server:sql-in-data-modules,internal/session-owner-runtime-status,perf/request-path-statements, plus about 85 service test files covering the moved queries (restart-resume, provisioning, environment engine and hooks, machine lifecycle, server access, attachments, machine auth, enrollments, legacy exports and others).packages/db:test/query-functions.test.ts, with a new class-method case, and the newtest/data/project-attachments.test.ts. The "query functions run in tests" job found that the movedclaimUnreadyProjectAttachmentDeletion(the attachment write-failure path) had never run in any test.session-owner-runtime-statuscounts prepared statements, and the moved session lookup now uses the cachedgetSessionByIdstatement, so it warms it once before measuring.🤖 Generated with Claude Code