Repository navigation
Fail the query cost check on undeclared growth, and bound nine history lookups - #7923
Merged
Merged
Conversation
ymichael
force-pushed
the
bb/query-cost-bounded-growth
branch
from
November 20, 2026 19:25
6d95c41 to
6108050
Compare
The check only failed when a query function's cost grew faster than size^2, so a function that reads a thread's whole history to return one row passed at any size. The #7899 lookup measured 4.7x when the world grew 4x and passed, then held a user's event loop for 28 s. Query functions are now expected to stay bounded: growth past size^0.75 (2.8x) on either axis fails unless the case declares growsWith.history or growsWith.turnSize with the reason its cost must grow. Declared growth keeps the old size^1.5 warning and size^2 failure. A declaration that measures within size^0.5 warns so it is removed once the query is bounded. The 36 cases that grow today are declared, each with what grows: 24 return or modify rows the larger world has more of, and 12 read rows they discard. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The query cost check's new growth declarations listed 12 query functions that read history and keep a few rows. Nine now use existing indexes so their cost no longer grows with the thread: - listStoredTurnStartedRowsByTurnIdsUpToSequence and listStoredTurnCompletedRowsByTurnIds seek the requested turns through events_thread_turn_type_item_sequence_idx instead of filtering every started or completed row in the thread. - isThreadAwaitingTurnStartPastDeadline and listTurnStartDeadlineCandidates compare only the newest turn/completed row's created_at to the deadline. - hasStoredProviderTurnCompletedSince reads only completions after the newest one older than the cutoff. - getLastStoredTurnRequestEvent and listStoredTaskTurnRequestEvents seek each request type on events_thread_type_sequence_idx with its own LIMIT and merge, instead of walking every event of an open turn. - listStoredTimelineThreadWindowEventRows reads the thread-scoped index entries (turn_id IS NULL) instead of every row in the window. - supersedeQueuedRetriesInTransaction starts its retry-chain scans at the retried request. getStoredConversationOutlineProjectionState now finds a nested turn's root request by seeking back from its acceptance, but stays declared: starting from nested rows was slower on real threads with many delegation rows. listStoredTurnInputAcceptedRowsByClientRequestIds and listTimelineRootWindowTurnIds stay declared because no existing index can bound them without changing their results. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lowlist entry CI runners measured upsertThreadConversationOutlineRecord at 0.5 → 2.3 ms (4.3x), over the 2 ms floor it stayed under locally. Runners take about 2.8x longer than a local machine, so every case that grows with data and measures at least 0.7 ms locally now declares its growth with the reason. listStoredTurnCompletedRowsByTurnIds now pins the per-turn index, so its weaker-index allowlist entry no longer matches any finding. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The bounded-growth rule compared worlds 4x apart and failed past 2.8x, so queries with a fixed cost plus a growing part measured anywhere from 2x to 3x and runner noise could move them across the line. The 2 ms floor was absolute CPU time, so a CI runner, about 2.8x slower than a laptop, checked cases a laptop never did. The smaller world is now a sixteenth of the larger (625 against 10,000 turns, 94 against 1,500 steps): bounded costs measure about 1x and linear ones about 16x, and the check fails past size^0.5 (4x). Unused declarations warn within size^0.25 (2x). The floor is 2 ms on the reference machine, scaled by how long a fixed SQLite calibration workload takes, so every machine checks the same cases. The check prints the calibration and the five undeclared functions closest to the limit on each axis. Cases whose inputs depended on the world size now pass a fixed input (20 chain leaves, 20 descendant roots, a 1,000-row page), and the cases that grow with the larger step declare why. Co-Authored-By: Claude Opus 5.5 <[email protected]>
It returns a span for every item the case passes, and the case passes each command of the long last turn, so it measured 2.8x and 3.0x against the 4x limit in two local runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
One of three CI runs on the same commit failed: findProviderEnvironmentContainingPath measured 0.49 → 3.02 ms (6.2x) and crossed a 2.90 ms floor that the other runs, calibrated at 5.4 and 6.1 ms, never reached. The case grows, but it was never declared because it stayed under the floor locally. - Every case is timed at least three times, so sub-millisecond cases no longer report a single noisy sample. - Calibration runs after the worlds are built and keeps the fastest of three. - A sweep with a 0.25 ms floor found every undeclared case that grows. Nine now declare why. deleteThreadScopedPruningCursors filtered on scope, the second primary-key column, and scanned every cursor; it now deletes by the indexed thread_id, which the scope check constraint makes equivalent. - Unused declarations warn only within size^0.125 (1.4x), so cases that only partly grow stop warning on noisy runners. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- isStoredTurnProviderCompactionRunning seeks the turn's latest root compaction start and completion on events_thread_type_item_kind_sequence_idx instead of reading every item start and completion in the turn. - isStoredTurnContextCompactionOnly asks whether a root compaction exists and whether any other root item exists, so a normal turn stops at its first non-compaction item instead of listing every completed item's kind. - listLatestTurnFinalAgentMessageEventRows walks root agent replies newest first; the first reply of a turn is its final one, and the walk then jumps below the turn's start. One cached prepared statement per step returns the reply with its turn's start, replacing a per-reply NOT EXISTS over the turn. On a production database copy (40 largest threads, 7,289 root turns) old and new returned identical results for every call; worst-case times went from 3.72 to 0.60 ms, 1.30 to 0.44 ms, and 9.40 to 2.05 ms (limit 50). getUnfinishedCommandItemData stays declared: finding a started command with no completion has to check each command started in the turn, since nothing records open items. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/query-cost-bounded-growth
branch
from
November 20, 2026 20:44
a9a74b9 to
d917ec6
Compare
This was referenced Nov 20, 2026
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-coststimes every exported query function in a small and a 4x larger world (thread history, and turn size), but it only failed past size^2 (16x) and only warned past size^1.5 (8x). Linear growth passed at any size. The #7899 lookup read every request event in a thread and parsed its JSON to keep one row. It measured 1.8 → 8.5 ms (4.7x) in this check and passed, then took 26.5 s on a 6.8 GB database. The query-plan guard missed it too, becauseSEARCH events USING INDEX (thread_id=? AND type=?)hides the per-rowjson_extractfilter. Applying a stricter rule showed 12 more query functions with the same shape: they read history and keep a few rows.What changed
The check
growsWith: { history | turnSize: "<reason>" }. Declared growth keeps the old limits: warn past size^1.5, fail past size^2. An empty reason fails the coverage check.docs/debugging-and-qa.md.Queries bounded with existing indexes (no new indexes on
events)listStoredTurnStartedRowsByTurnIdsUpToSequenceandlistStoredTurnCompletedRowsByTurnIdsseek the requested turns onevents_thread_turn_type_item_sequence_idx. Before, they filtered every started or completed row in the thread.isThreadAwaitingTurnStartPastDeadlineandlistTurnStartDeadlineCandidatescompare only the newestturn/completedrow'screated_atto the deadline. This relies on appended rows'created_atrising withsequence. Fork copies keep older timestamps, but they are appended before any of the fork's own rows, and the copy aborts if anything else is appended.hasStoredProviderTurnCompletedSincereads only the completions after the newest one older than the cutoff.getLastStoredTurnRequestEventandlistStoredTaskTurnRequestEventsseek each request type onevents_thread_type_sequence_idxwith its ownLIMIT, then merge. Before, anORover the types made SQLite walk every event of an open turn.listStoredTimelineThreadWindowEventRowsreads the thread-scoped (turn_id IS NULL) index entries, which carrysequence, instead of every row in the window.supersedeQueuedRetriesInTransactionstarts its retry-chain scans at the retried request.deleteThreadScopedPruningCursorsdeletes by the indexedthread_id. Before, it filtered onscope, the second primary-key column, and scanned every cursor. The table's check constraint makes the two filters select the same rows.isStoredTurnProviderCompactionRunningseeks the turn's latest root compaction start and completion onevents_thread_type_item_kind_sequence_idx. Before, it read every item start and completion in the turn.isStoredTurnContextCompactionOnlychecks two things: whether a root compaction exists, and whether any other root item exists. A normal turn stops at its first non-compaction item. Before, it listed every completed item's kind.listLatestTurnFinalAgentMessageEventRowswalks root agent replies newest-first. A turn's first reply in that walk is its final one, and the walk then jumps below the turn's start. Each step is one cached prepared statement that returns the reply along with its turn's start. Before, every reply ran aNOT EXISTSover its whole turn.Still declared, with the reason in the case
getStoredConversationOutlineProjectionState: its nested turn's root-request lookup now seeks back from the acceptance instead of JSON-scanning every request. The outer scan stays as it was. I tried starting from the nested rows, using the partial parented-row index. That doubled its time on real threads: one thread has 46,791 delegation rows and no nested turns. No index singles out nestedturn/startedrows.listStoredTurnInputAcceptedRowsByClientRequestIds: no index keysclientRequestId. A request that was accepted beforeafterSequence, or never accepted, has to read every later acceptance. Stopping at the first match would change edit-message's "accepted into exactly one turn" check.getUnfinishedCommandItemData: to find a started command with no completion, it has to check each command started in the turn, because nothing records open items. It reads only command rows, through the item-kind index, and runs only when a daemon restarts mid-turn.listTimelineRootWindowTurnIds: it must find every turn with rows in the window. A turn's late rows can land after later turns start, so only reading the window finds them.51 cases are declared. Apart from the 4 above, each one returns, writes or deletes rows the larger world has more of.
How you verified
pnpm exec turbo run typecheck --filter=@bb/dbandpnpm exec turbo run test --filter=@bb/serverpass. All 729@bb/dbtests pass, with the query-plan guard on.New
packages/db/test/data/bounded-history-lookups.test.ts(7 tests) pins the behaviour each rewrite keeps. The tests pass against both theorigin/mainqueries and the rewritten ones.Full
check:query-costswith the pre-Bound the client turn request lookup to the acceptance that consumed it #7920listStoredClientTurnRequestRowsByKeysput back exits 1 on that function. On this branch it exits 0 with no warnings.Stability: the cost job ran four times on CI on the final changes (the PR run plus two dispatched runs on
6d95c41, then the PR run after the rebase). All passed. The closest undeclared case in any run was 3.15x against the 4x limit, and most were at or below 2.2x. The calibrated floors ranged from 2.5 to 3.4 ms. Before these changes, one of three runs on the same commit failed.Real data: a
VACUUM INTOcopy of a production bb.db (8.8 GB). I ran theorigin/mainand rewritten queries on its 40 largest threads (largest: 131,244 events). Results were identical for every function and thread. Median of 5 runs:listStoredTimelineThreadWindowEventRowslistStoredTaskTurnRequestEventsgetStoredConversationOutlineProjectionStatelistStoredTurnCompletedRowsByTurnIdslistStoredTurnStartedRowsByTurnIdsUpToSequencehasStoredProviderTurnCompletedSincegetLastStoredTurnRequestEventisThreadAwaitingTurnStartPastDeadlinelistTurnStartDeadlineCandidatesReal data, turn helpers: on the same copy (40 largest threads, 7,289 root turns), the
origin/mainand rewritten versions returned identical results for every call. Worst-case times:isStoredTurnProviderCompactionRunningisStoredTurnContextCompactionOnlylistLatestTurnFinalAgentMessageEventRows(limit 50)My first version of the final-reply walk was slower on real data (87 → 228 ms total at limit 50), because it rebuilt two queries per turn. The prepared-statement version fixed that.
This database has no queued retries, so
supersedeQueuedRetriesInTransactionis covered by the cost check andqueued-retry-history.test.tsinstead.Refs #7899
🤖 Generated with Claude Code