Skip to content

Thread search: single partitioned FTS scan, prefix index and bounded snippets (B25, B26) - #1887

Merged
SawyerHood merged 3 commits into
bb/mobile-perf/workspace-status-and-pr-cachefrom
bb/mobile-perf/search-fts
Aug 19, 2026
Merged

SawyerHood merged 3 commits into
bb/mobile-perf/workspace-status-and-pr-cachefrom
bb/mobile-perf/search-fts

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 19, 2026 •

Copy link
Copy Markdown
Collaborator

What was wrong

searchThreadsWithPendingInteractionState ran the full ranking pipeline twice per request, once for active and once for archived threads. Every token MATCH and the any-token hydration MATCH executed 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

  • New custom Drizzle migration 0101_thread_search_prefix_fts recreates thread_search_segments_fts with prefix = '2 3', rebuilds rows and triggers (same mechanism as 0040). Snapshot and journal regenerated with drizzle-kit generate --custom.
  • packages/db/src/data/threads.ts: one SQL statement ranks threads that contain every token, partitions ROW_NUMBER/COUNT(*) by archived state, keeps the top limitPerGroup per group, then joins the any-token MATCH once 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.
  • Message matches are cut to a ~160-char snippet around the first highlight (40 chars of lead, word-boundary snapping bounded to 40 chars, surrogate-safe, "…" on each cut side). Highlight ranges are rebased onto the snippet. Titles stay whole so the sidebar can pair them with the display title.
  • Contract comment on threadSearchMatchSchema.text documents 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.
  • New/updated tests in 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_master shows prefix = '2 3'. Migration backfill test now replays 0039/0040/0101.
  • EXPLAIN QUERY PLAN on the new statement: two SCAN 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).

  • Prerequisite (layer below): bb/mobile-perf/workspace-status-and-pr-cache (Dedupe and briefly cache workspace status and pull-request reads (B7, B8) #1886).
  • Next layer: bb/mobile-perf/timeline-delta-ring-and-output-cap (Timeline delta snapshot ring and pending-turn tool output preview cap (B19, B20) #1888).
  • Audit findings addressed: see title IDs. Review: approved-with-fixes; 1 review fix commit(s).
  • Deliberately not done here: B25 optional group= query param: not added. It does not simplify the code (the partitioned scan already collapses the double MATCH) and would add contract, SD
  • Wire/contract: No server<->daemon wire changes (HOST_DAEMON_PROTOCOL_VERSION unchanged). Public API response shape for GET /threads/search is unchanged; semantics changed: matches[].text for message kinds is now a bounded snippet (with leading/trailing "…" when cut) and highlightRanges are offsets into that snippet; each thread returns at most one message match plus its title/title_fallback matches (previous

AGENT GENERATED: by Claude Opus 5

@SawyerHood SawyerHood changed the title bb/mobile perf/search fts Thread search: single partitioned FTS scan, prefix index and bounded snippets (B25, B26) Aug 19, 2026
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/search-fts branch from 4d8b1ac to 270b71c Compare August 19, 2026 07:50
@SawyerHood
SawyerHood marked this pull request as ready for review August 19, 2026 08:04
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/search-fts branch from 270b71c to 4eaf77a Compare August 19, 2026 15:59
SawyerHood and others added 3 commits August 19, 2026 16:03
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]>
@SawyerHood
SawyerHood force-pushed the bb/mobile-perf/search-fts branch from 4eaf77a to 94747b4 Compare August 19, 2026 16:13
@SawyerHood
SawyerHood merged commit a74dcd9 into main Aug 19, 2026
14 of 23 checks passed
@SawyerHood
SawyerHood deleted the bb/mobile-perf/search-fts branch August 19, 2026 16:23
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]>
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