Repository navigation
Thread search: single partitioned FTS scan, prefix index and bounded snippets (B25, B26) - #1887
Merged
SawyerHood merged 3 commits intoAug 19, 2026
Conversation
SawyerHood
force-pushed
the
bb/mobile-perf/search-fts
branch
from
August 19, 2026 07:50
4d8b1ac to
270b71c
Compare
SawyerHood
marked this pull request as ready for review
August 19, 2026 08:04
SawyerHood
force-pushed
the
bb/mobile-perf/search-fts
branch
from
August 19, 2026 15:59
270b71c to
4eaf77a
Compare
Thread search issues prefix queries ("tok"*) for every token, but the
thread_search_segments_fts table had no prefix index, so FTS5 had to
expand each prefix against the full term list on every keystroke.
Recreate the virtual table with prefix='2 3' through a custom Drizzle
migration (0101, generated with drizzle-kit generate --custom, snapshot
regenerated) and rebuild its rows and triggers, matching the mechanism
0040 used for the rowid rebuild.
Co-Authored-By: Claude <[email protected]>
searchThreadsWithPendingInteractionState ran the whole ranking pipeline twice, once for active and once for archived threads, so every token MATCH plus the any-token hydration MATCH executed twice per request. It also returned up to three full message bodies per thread while the sidebar renders a single truncated line, which inflated the response for threads with long assistant messages. Rank threads once, partition the row numbers and totals by archived state, and hydrate matches for both groups in the same statement (N+1 FTS scans instead of 2N+2). Keep only the matching title segments plus the single best-ranked message segment per thread, and cut message text to a ~160-char snippet around the first highlight with the highlight ranges rebased onto the snippet and an ellipsis on each cut side. The response shape is unchanged; the contract comment documents the snippet semantics. Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
SawyerHood
force-pushed
the
bb/mobile-perf/search-fts
branch
from
August 19, 2026 16:13
4eaf77a to
94747b4
Compare
SawyerHood
added a commit
that referenced
this pull request
Aug 19, 2026
… B8) (#1886) ## What was wrong `GET /environments/:id/status` and `GET /environments/:id/pull-request` forwarded every request to the host daemon. Each status probe spawns 4-5 git subprocesses (measured 240-344 ms); each pull-request probe spawns `gh pr view`. A thread open, sidebar rows and a phone returning to the foreground ask for the same environment inside the same second, and the client refetches status on every `work-status-changed` batch. One editing turn produced a stream of duplicate probes on the host (audit findings B7, B8). ## What changed - New `WorkspaceReadCaches` (`apps/server/src/services/environments/workspace-read-cache.ts`) on `AppDeps`: a per-environment in-flight dedupe plus a short TTL cache, 3 s for `workspace.status`, 10 s for `workspace.pull_request`. - The two read routes go through the cache. Overlapping reads share one daemon RPC. Repeated reads inside the TTL are served from memory. The response shape is unchanged. - Freshness follows the daemon events the client already refetches on. Any environment change except record-only `metadata-changed` / `thread-storage-changed` drops the cached value and detaches any in-flight probe for that environment (a probe that started before the change may have read the pre-change tree). Host connect/disconnect drops that host's entries. `metadata-changed` is ignored because the status probe itself records the observed branch mid-flight. - Cache keys include the workspace context and the merge-base branch, so a re-provisioned environment or a different merge base never reads a stale entry. Mutation routes (commit, squash-merge, PR actions) keep probing directly. - No server/daemon wire change. ## How you verified - `apps/server/src/services/environments/workspace-read-cache.test.ts`: in-flight sharing, TTL expiry with a fake clock, key separation, no caching of rejections, in-flight detachment on invalidation (late result does not overwrite), host-scoped invalidation, both caches dropped on `work-status-changed` / `git-refs-changed`, kept across `metadata-changed` / `thread-storage-changed`, dropped on host events. - `apps/server/test/environments/workspace-read-cache-routes.test.ts`: two concurrent status GETs produce one `workspace.status` daemon command; a third GET is served without a daemon round trip; `?mergeBaseBranch=` is a separate probe; `work-status-changed` forces a fresh probe. Same for `/pull-request` with `git-refs-changed`. These fail before the change (the third request blocks on an unanswered second daemon command). - `pnpm exec turbo run typecheck --filter=@bb/server` passes; related suites (`test/public`, `test/hosts`, `test/internal`, `test/environments`, `test/ai/commit-message.test.ts`, `src/services/environments`) pass except one pre-existing umask-dependent assertion in `internal-skill-trees.test.ts` (file mode 0664 vs 0644, unrelated). Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue). ## Stack context Layer 7 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins first, big rocks last). - Prerequisite (layer below): `bb/mobile-perf/list-models-cache` (#1885). - Next layer: `bb/mobile-perf/search-fts` (#1887). - Audit findings addressed: see title IDs. Review: approved. - Reviewer notes / follow-ups: B8 client half (drop PR key from the work-status-changed handler, refetchOnWindowFocus:true, ~30 s pending-checks poll) is not in this package by design; until it lands, agent edit | Remote-only PR changes (e.g. `gh pr create` from a shell with no local ref change) can be up to 10 s stale; unsubscribed environments up to 3 s stale for status. Both are within wh | apps/server/src/routes/environments.ts has a pre-existing prettier drift (assertCanMarkPullRequestReady / assertCanConvertPullRequestToDraft) that predates this branch; not touched - Wire/contract: None. No server<->daemon message, command, result, or HOST_DAEMON_PROTOCOL_VERSION change. HTTP responses for /status and /pull-request are byte-identical in shape; only freshness/dedupe changed. New internal AppDeps member `workspaceReadCaches` (server-only). > AGENT GENERATED: by Claude Code (claude-mangosteen-eap) Co-authored-by: Claude <[email protected]>
SawyerHood
added a commit
that referenced
this pull request
Aug 19, 2026
… (B19, B20) (#1888) ## What was wrong - Timeline delta cache (`timeline-latest-rows-cache.ts`) held one snapshot per params key. Two viewers of a streaming thread (desktop + phone) poll out of phase. The faster client advances the snapshot; the slower one never finds the revision it echoes and gets the full window on every batch (audit B19). - The latest timeline page ships the running turn's full command/tool outputs inline (up to 32 K each). One running thread measured 434 KB raw with 264 KB of output across 138 command rows, all rendered collapsed. Every poll re-shipped and re-parsed it (audit B20). ## What changed - Server (B19): each params key keeps a ring of 4 recent revisions keyed by `maxSeq`. `GET /threads/:id/timeline?afterSequence=N` looks up revision N and only falls back to a full window when N left the ring. Repeat sets of the same revision only refresh recency. - Server (B20): new `timeline-output-preview.ts`. In the default window (no `includeNestedRows`), a top-level command/tool output longer than 4 000 chars becomes a 2 000-char head + omitted marker + 1 000-char tail, and the row carries `outputPreview: { totalChars }`. `includeNestedRows=true` (CLI verbose log, SDK callers) still gets full inline output. The existing turn-summary-details route scoped to the row's `turnId` + `sourceSeqStart..sourceSeqEnd` returns the whole output (works for running turns and after the turn completes). - Contract: optional `outputPreview` on command/tool rows; `includeNestedRows` doc; regenerated plugin SDK bundled d.ts and templates embed. - Client: `useTimelineWorkRowFullOutput` + `CommandWorkRowBody`/`ToolWorkRowBody` in `TimelineRowDetails.tsx`. Expanded rows render the preview at once and load the whole output through turn-summary-details once the row is not pending (a running row's range still moves; its preview tail is the live part). A short note explains the state and offers Retry on failure; nothing extra renders once the full output is loaded or the row was never previewed. ## How you verified - New tests (fail before, pass after): - `apps/server/test/public/public-thread-timeline-delta.test.ts`: two interleaved clients both receive mergeable deltas; a revision that left the ring falls back to a full window. - `apps/server/test/public/public-thread-timeline-output-preview.test.ts`: preview cap + `outputPreview` marker; small outputs untouched; `includeNestedRows=true` full output; row-scoped turn-summary-details returns full output for a running turn and after `turn/completed`. - `apps/app/src/components/thread/timeline/TimelineRowDetails.output-preview.test.tsx`: expanded finished row calls `sdk.threads.timelineTurnSummaryDetails` with the row's turnId/range and renders the full output; a pending row keeps the live preview and does not fetch; a failed load shows the preview with Retry. - `pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/app --filter=@bb/server-contract --filter=@bb/templates --filter=@bb/thread-view --filter=@bb/sdk --filter=@bb/cli`: 8/8 successful. - `pnpm exec turbo run lint --filter=@bb/server --filter=@bb/app --filter=@bb/server-contract`: 0 errors; @bb/app warning count unchanged from baseline (147). - Targeted vitest: server (delta + preview + timeline-in-turn-window + public-thread-data + output-truncation + conversation-outline-performance) all pass; app (output-preview, ThreadTimelineRows.actions, render-stability, controller.merge) 52/52; full suites of @bb/server-contract, @get-bb/plugin-sdk, @bb/templates pass. Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue). ## Stack context Layer 9 of 22 in the `bb/mobile-perf/*` stack (bottom → top: quick wins first, big rocks last). - Prerequisite (layer below): `bb/mobile-perf/search-fts` (#1887). - Next layer: `bb/mobile-perf/http-caching-and-hub-gating` (#1889). - Audit findings addressed: see title IDs. Review: approved-with-fixes; 1 review fix commit(s). - Reviewer notes / follow-ups: Follow-up (not a defect of this package): only top-level command/tool rows are previewed. A pending delegation's childRows and file-change diffs/stdout in the running turn still sh | Follow-up (edge UX): a row that stays `pending` while the thread is no longer running (e.g. an interrupted item that never got its item/completed before the turn closed) keeps the - Wire/contract: HTTP client<->server contract only (no server<->daemon wire change; HOST_DAEMON_PROTOCOL_VERSION not bumped). packages/server-contract: new optional `outputPreview?: { totalChars: number }` on `timelineCommandWorkRowSchema` and `timelineToolWorkRowSchema` (new export `timelineOutputPreviewSchema` / `TimelineOutputPreview`); `includeNestedRows` query doc updated. Behavior change on GET /threads/:id > AGENT GENERATED: by Claude Code (claude-mangosteen-eap) --------- Co-authored-by: Claude <[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.
What was wrong
searchThreadsWithPendingInteractionStateran the full ranking pipeline twice per request, once for active and once for archived threads. Every tokenMATCHand the any-token hydrationMATCHexecuted twice (2N+2 FTS scans for N tokens). The FTS5 table had no prefix index, so each"tok"*prefix query expanded against the full term list on every keystroke. The response carried up to three full message bodies per thread while the sidebar renders one truncated line (B25, B26 in the mobile perf sweep).What changed
0101_thread_search_prefix_ftsrecreatesthread_search_segments_ftswithprefix = '2 3', rebuilds rows and triggers (same mechanism as 0040). Snapshot and journal regenerated withdrizzle-kit generate --custom.packages/db/src/data/threads.ts: one SQL statement ranks threads that contain every token, partitionsROW_NUMBER/COUNT(*)by archived state, keeps the toplimitPerGroupper group, then joins the any-tokenMATCHonce to pull the matching title segments plus the single best message segment per thread. Rows are split by group in JS. Total FTS scans: N+1.threadSearchMatchSchema.textdocuments the snippet semantics. Response shape is unchanged; the client (ThreadSearchResultRow) already picks one message match and one title match.How you verified
pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/server-contract --filter=@bb/server: pass.pnpm exec turbo run test --filter=@bb/db: 29 files, 396 tests pass (includes migration journal/snapshot chain checks and query-plan tests).pnpm exec turbo run test --filter=@bb/server -- test/public/public-thread-search.test.ts: pass.packages/db/test/data/thread-search.test.ts(in-memory SQLite + migrate): one message match per thread; title + title_fallback + one message per thread; per-group limit and totals from one call with mixed active/archived; snippet bounds, ellipses, word-boundary lead, rebased ranges slice to the token; short text returned whole; long unbroken tail keeps hard cut;sqlite_mastershowsprefix = '2 3'. Migration backfill test now replays 0039/0040/0101.EXPLAIN QUERY PLANon the new statement: twoSCAN thread_search_segments_fts VIRTUAL TABLE INDEX(single token), rowid PK lookups for segments, PK lookup for threads, automatic index for the limited-threads join.Fixes: part of the mobile / iOS Safari performance program (verified sweep report in the bb thread; no single issue).
Stack context
Layer 8 of 22 in the
bb/mobile-perf/*stack (bottom → top: quick wins first, big rocks last).bb/mobile-perf/workspace-status-and-pr-cache(Dedupe and briefly cache workspace status and pull-request reads (B7, B8) #1886).bb/mobile-perf/timeline-delta-ring-and-output-cap(Timeline delta snapshot ring and pending-turn tool output preview cap (B19, B20) #1888).group=query param: not added. It does not simplify the code (the partitioned scan already collapses the double MATCH) and would add contract, SDmatches[].textfor message kinds is now a bounded snippet (with leading/trailing "…" when cut) andhighlightRangesare offsets into that snippet; each thread returns at most one message match plus its title/title_fallback matches (previous