Skip to content

Bound thread search by the page, not the match count - #7937

Merged
ymichael merged 3 commits into
mainfrom
bb/bound-thread-search-by-the-page-not-the-match-co-thr_xw9jr49act
Nov 20, 2026
Merged

ymichael merged 3 commits into
mainfrom
bb/bound-thread-search-by-the-page-not-the-match-co-thr_xw9jr49act

Conversation

@ymichael

@ymichael ymichael commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

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 Time server and plugin SQL in the query cost check, and fail every case on its ceiling #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 Time server and plugin SQL in the query cost check, and fail every case on its ceiling #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

@ymichael
ymichael force-pushed the bb/bound-thread-search-by-the-page-not-the-match-co-thr_xw9jr49act branch from 2739d9d to ae196cf Compare November 20, 2026 23:32
ymichael and others added 3 commits November 20, 2026 15:41
Thread search ranked and counted every matching thread, and reached each
match by reading its full thread_search_segments row (text inline), so a
common word read and sorted thousands of threads to return twenty.

Search now builds one in-memory set of the query's matching segments from
FTS, then walks threads in result order through a new partial index on
threads ((archived_at IS NOT NULL), updated_at, id) and stops when the page
is full. Per-thread checks probe the set from the covering segment indexes,
so only the page's own segments are read in full. When the rarest word
matches at most 1,000 segments, the walk visits only those segments'
threads. Group totals are counted up to 100; the response gains
totalCapped, true when more threads match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rebased query-cost seed indexes about 48 segments per thread, and
search grows 3.4-3.85x across the history worlds: the FTS key set holds
every matching segment. Declaring it keeps the default ceiling in force
instead of passing just under the undeclared 4x limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/bound-thread-search-by-the-page-not-the-match-co-thr_xw9jr49act branch from ae196cf to 1a4abf2 Compare November 20, 2026 23:44
@ymichael
ymichael merged commit 05d2735 into main Nov 20, 2026
55 checks passed
@ymichael
ymichael deleted the bb/bound-thread-search-by-the-page-not-the-match-co-thr_xw9jr49act branch November 20, 2026 23:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant