Skip to content

fix(db): seek missing timeline parents by item - #5599

Merged
ymichael merged 1 commit into
get-bb:mainfrom
Danielalnajjar:bb/fix-long-thread-parent-lookup-thr_7ivfcqjr46
Oct 16, 2026
Merged

ymichael merged 1 commit into
get-bb:mainfrom
Danielalnajjar:bb/fix-long-thread-parent-lookup-thr_7ivfcqjr46

Conversation

@Danielalnajjar

@Danielalnajjar Danielalnajjar commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Human comments

I have a long running "Captain" thread. I noticed after a few days I started seeing “Loading latest messages…” for a few seconds each time I switched to it, and BB feels frozen. I had Opus ask Muse Wonder, Astra, Gemini 4, and Fable , and Grok for the best solution and they all seemed to agree it was this and that it would be a general improvement for bb not just a fix for my workflow.

What was wrong

For two or more missing parent IDs, SQLite can choose events_thread_sequence_idx (thread_id=?) to satisfy ORDER BY sequence in listStoredDelegatingItemRowsByItemIds. It then scans a long thread's events to resolve a few IDs, including IDs whose parents are not delegating items. This is a general timeline-path performance bug, not a Captain- or Crew-specific behavior. See #5598 for the standalone repro, observed symptoms, and distinctions from other timeline stalls.

What changed

  • The lookup explicitly uses the existing events_delegating_item_lookup_idx, constraining both thread_id and item_id for multi-ID requests. It keeps the same filters and sequence ordering.
  • Its selection uses the existing SQL row projection required by Drizzle when FROM is a raw indexed table expression. One migrated-DB test checks the emitted plan and exact mixed-kind returned rows with the timeline's numeric output cap.
  • No schema, migration, caller, wire/protocol, CLI, guide, or UI behavior changes. INDEXED BY intentionally couples this query to the already-migrated partial index; a missing or unusable index fails statement preparation. A workload with substantially more matching IDs might still favor a scan; the 28-hit synthetic case below did not show that crossover.

How you verified

  • Red-first: with the test added but the original query, row equality passed and the plan assertion failed on SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?). Green: the patched capped query returns the same full rows and uses events_delegating_item_lookup_idx (thread_id=? AND item_id=?).
  • After rebasing onto 4363ba27d6f942d6b42ae61c8f85800e756b9085: pnpm exec turbo run typecheck test --filter=@bb/db (53 files, 625 tests); pnpm exec turbo run typecheck --filter=@bb/server; pnpm exec turbo run test --filter=@bb/server -- test/services/threads/timeline-parented-pagination.test.ts test/services/threads/timeline-in-turn-window.test.ts (36 tests). All passed. Before the rebase, all 15 server timeline*.test.ts files passed (145 tests).
  • On an isolated exe.dev Ubuntu VM using the installed-app tag desktop-v0.46.0 (4c87fdec7) plus this exact patch: frozen pnpm install, the focused capped query-plan/row test, the full @bb/db typecheck and test suite, @bb/server typecheck, and the 36 parented-timeline tests passed. pnpm start --dryrun --no-in-app-updates built all 51 production tasks without starting a server or creating a database.
  • A one-off, in-memory 177,000-event comparison of the emitted query with and without the hint returned identical rows in identical order. For 28 missing IDs, median lookup time was 44.8 ms without the hint versus 0.012 ms with it; for 28 matching IDs (56 returned rows), 44.0 ms versus 0.081 ms. These warm synthetic timings are not a measurement of Captain or a cold production database.
  • git diff --check passed. The installed bb app and production DB were not changed; Captain's end-to-end timeline timing needs observation after a release, and other timeline costs may remain.

Fixes #5598

AGENT GENERATED
Claude Opus 5.5

Multi-ID missing-parent lookups chose the thread-sequence index to satisfy
ORDER BY and scanned every event of long threads. Force the existing partial
delegating-item index and use the SQL row projection required by Drizzle's
indexed raw FROM, without changing the returned rows or their order.

The query-plan regression uses the migrated database and the timeline's
numeric output cap. It fails on the prior thread scan and passes with
thread-and-item seeks.

Verification: 625 DB tests and 145 server timeline tests passed; DB and
server typechecks passed. The capped focused test was rerun red/green after
the full suites.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T00:25:59.147956Z a9b40c9 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ymichael
ymichael merged commit c00ff8b into get-bb:main Oct 16, 2026
28 checks passed
ymichael added a commit that referenced this pull request Oct 16, 2026
)

## Human comments

## What was wrong

Follow-up to #5598 / #5599. A query-plan sweep of every SELECT run by
the `@bb/db` and `@bb/server` suites found four more `events` lookups
that SQLite answers by walking a thread's whole history through a
`thread_id`-only index seek, even though a selective index already
exists. Production databases have no `sqlite_stat1`, so these test-suite
plans are the production plans. Two of the lookups run on every timeline
build that shows background tasks or delegations.

- `listLatestBackgroundTaskStateRowsByItemIds` filters `item_id IN
(...)` with no kind predicate, so neither the background-task partial
index nor the delegating-item partial index qualifies.
- The completed-task probes in
`listLatestOpenBackgroundTaskStateRowsForThread` and both
`listOpenBackgroundTaskItemRows*` queries have no kind predicate either.
The thread variant's candidate scan also chose the thread-sequence index
over the background-task partial index.
- `hasTerminalClientTurnRequestEvent` ORs two type branches. SQLite does
not split the OR into index seeks, so it walks the thread.

## What changed

- `packages/db/src/data/events.ts`
- `listLatestBackgroundTaskStateRowsByItemIds`: the latest-state
subquery is now a `UNION ALL` of a background-task arm, pinned to
`events_background_task_thread_type_item_sequence_idx`, and a delegation
arm, pinned to `events_delegating_item_lookup_idx`. Each arm uses a
literal kind predicate.
- The completed/settled probes add a literal `item_kind =
'backgroundTask'`. `listOpenBackgroundTaskItemRowsForThread` pins
`events_background_task_thread_type_item_sequence_idx` for its candidate
rows.
- New `hasStoredTerminalClientTurnRequestEvent`, which filters `type IN
('turn/input/accepted', 'client/turn/rejected')` before the OR. It moves
from `apps/server/src/services/threads/thread-lifecycle.ts`, which now
calls it, so it can have a plan regression next to its siblings.
- Returned rows do not change. Every event of these four state types
carries the matching `item_kind`: the domain schemas pin it, and all
24,056 such rows in a long-lived production database agree. The `latest`
MAX subquery in the open-task listings is deliberately left without a
kind filter, because adding one would change results if a tool call and
a background task ever shared an item ID.
- No schema, migration, wire or protocol, CLI, or UI changes.

## How you verified

- New `packages/db/test/query-plans.test.ts` cases for the
background/delegation state lookup, both open-task listings, and the
terminal-request check. The existing open background-task test also
gains a no-thread-only-seek assertion. Against the previous query
shapes, all four fail on plan assertions while their returned-row
assertions pass; with the change they pass.
- `pnpm exec turbo run typecheck lint test --filter=@bb/db
--filter=@bb/server`: 628 db tests and 3,549 server tests passed. Re-ran
db typecheck/lint/test and server typecheck/lint after rebasing onto
`c00ff8bed2`.
- Replayed each emitted statement read-only against a real 143k-event
thread:

| Query | Before | After |
| --- | --- | --- |
| Latest background-task/delegation state by item (timeline) | 94 ms
cold / 4–9 ms warm | <0.1 ms |
| Completed-task IDs for open background tasks (timeline) | 8 ms | <0.1
ms |
| Open background tasks for a thread (thread stop) | 71 ms | <0.1 ms |
| Settled probe per open task, host listing (daemon reconnect) | ~7 ms
each | <0.1 ms |
| Terminal client turn request check (command failure) | 72–78 ms | 4 ms
|

- Manual: `pnpm start:worktree` with a seeded 150k-event thread
containing a running and a finished background task and a delegation in
its latest turn. The timeline returns 200 and shows the latest states.

> 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 Oct 19, 2026
## Human comments

## What was wrong

Confirmed on main at `6a639cfc0d` using a snapshot of real production
threads: timeline projection repeatedly tokenizes identical shell
commands for start/completion events and subsequent rebuilds. Shell
intent parsing accounted for about two-thirds of projection CPU in the
repeatable slow window. The scanner also appended ordinary text one
character at a time, and optional read/search summaries had no
input-size bound. A synthetic two-million-character script with many
short commands took about 97 ms to infer a summary; merely scanning text
faster still took about 90 ms for that shape.

This addresses remaining projection work after #5599 and #5655. It does
not touch #5678's ordering-context implementation or tests.
Event-query/decode costs remain.

## What changed

- Retain a shared LRU cache keyed by exact command text, bounded by
4,096 entries and 2,000,000 total command characters. Empty results are
cached too; callers receive fresh arrays and copies of the flat intent
objects.
- Skip optional shell-summary inference when the unwrapped command
exceeds **2,048 UTF-16 code units**, before cache lookup or scanning.
The complete command remains available and displays as a command rather
than an inferred read/search. No prefix is summarized: a later write
could invalidate an earlier read classification.
- Scan runs of ordinary text using sticky regular expressions for
unquoted, single-quoted and double-quoted text. Existing handling still
processes quotes, escapes, whitespace, separators and redirects. This
also speeds the shared thread-message scanner. The summary cap does not
truncate or disable long `bb thread tell` messages.

The shared implementation serves timeline/CLI consumers. No
configuration, public API, schema, persisted-data, or server/daemon wire
changes. The cache is process-local and clears on restart.

### Why 2K

Measured all 494,340 distinct completed commands in the snapshot;
249,347 currently produce a summary. Counts below are exact, not
sampled:

| Cutoff | Commands that skip inference | Existing summaries removed |
| --- | ---: | ---: |
| 512 characters | 80,330 | 11,267 (4.52%) |
| 1,024 characters | 34,096 | 719 (0.29%) |
| **2,048 characters** | **13,761** | **49 (0.02%)** |
| 4,096 characters | 4,104 | 3 (0.0012%) |

512/1K remove ordinary multi-file searches and batches of file reads.
Inspection of the 2K+ cases found mostly longer scripts whose inferred
label describes only one part of the command. 2K preserves 99.98% of
existing summaries while bounding inference work; 4K doubles the limit
to preserve 46 additional labels. Full command text is retained at every
cutoff.

## How you verified

- Red/green: the 2,049-character timeline fallback test and uncached
scanner CPU regression fail on the cache-only revision and pass after
these changes. Boundary coverage checks inference at 2,048 characters,
fallback at 2,049, full command preservation and displayed titles. Mixed
quoted/escaped runs and long thread-message extraction are covered.
Cache reuse, caller mutation independence, later-write disqualification
and early-write short-circuit coverage remain; performance fixtures stay
below the cap so it cannot hide regressions.
- `pnpm exec turbo run typecheck lint test --filter=@bb/thread-view
--filter=@bb/server`: passed; 495 thread-view tests and 3,550 server
tests passed, 1 server test skipped. Neither package declares a lint
task, so also ran `pnpm exec oxlint` directly on all four changed files.
Oxfmt and `git diff --check` passed.
- Compared the final parser against the original on all **494,340** real
commands: no differences beyond the deliberate >2K fallback. **30,000**
generated quoting/operator cases matched. All **4,596** real commands
matching the thread-message hint retained identical message-extraction
results.
- Final real-data replay: two alternating process rounds per variant
(original main, cache-only, final), 19 historical windows across 16
threads, 10 builds/window. Medians exclude the first build (18
samples/window/variant). Historical sequences are reconstructed from
logged timestamps against the current snapshot, rather than an exact
archive of the original store. Selection/decode caches are cleared for
the first three builds/window.

| Real window | Selected events | Build median, original → final |
Main-thread CPU, original → final | Projection median, original → final
|
| --- | ---: | ---: | ---: | ---: |
| Largest repeatable stall | 7,075 | 217.47 → 150.64 ms (-31%) | 213.88
→ 149.58 ms | 85.87 → 23.94 ms (-72%) |
| Earlier window of the same thread | 6,818 | 186.06 → 142.16 ms (-24%)
| 184.70 → 141.35 ms | 74.48 → 23.06 ms (-69%) |

The cache-only projection medians were 23.26 and 22.88 ms: warm-cache
performance is similar. The additional changes target misses and
oversized inputs. Across 480,579 unique real commands within the new
limit, repeated passes larger than the cache (all misses) used **44%
less parsing CPU** with the final implementation, including its cache
bookkeeping. By input band, CPU improved 1.7× below 512 characters, 2.2×
at 512–1K, and 2.7× at 1K–2K.

Of 380 paired full timeline responses, 360 were byte-identical. The
remaining 20 are repeated builds of one window: a structural comparison
proved the only change was removal of one >2K command's
`activityIntents`; its complete command and every other response field
were unchanged. Cache-only responses all matched the original.

Scripts, snapshot, profiles and reports remain outside the checkout
under the investigation thread's `qa/` storage (`parsing/` contains the
cutoff comparison and final experiments). Production was accessed
read-only to create the snapshot. These are server-builder measurements,
not browser latency; other timeline stages can still stall.

> AGENT GENERATED
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.

Multi-ID timeline parent lookup scans every event in long threads

2 participants