Skip to content

fix(db): seek background-task and request-outcome events by index - #5655

Merged
ymichael merged 1 commit into
mainfrom
bb/fix-bb-issue-5598-thr_2z29ajq3hn
Oct 16, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/fix-bb-issue-5598-thr_2z29ajq3hn

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

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

A query-plan sweep of every statement the db and server suites run found
four more event lookups that walk a thread's whole history through a
thread-only index seek instead of the existing selective index:

- listLatestBackgroundTaskStateRowsByItemIds (timeline build) now reads
  background-task state through the background-task partial index and
  delegation state through the delegating-item index.
- listLatestOpenBackgroundTaskStateRowsForThread and both open
  background-task listings use a literal backgroundTask kind so their
  completed-task probes seek the background-task partial index; the
  per-thread listing also pins that index for its candidate rows.
- The terminal client turn request check moves to @bb/db as
  hasStoredTerminalClientTurnRequestEvent and filters the two event types
  first, so it seeks the thread/type index.

Every state event of these types carries the matching item kind (the
domain schemas pin it, and all 24k rows in a production database agree),
so returned rows are unchanged. Query-plan regressions fail on the
previous shapes with identical returned rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit f3bab6e into main Oct 16, 2026
30 checks passed
@ymichael
ymichael deleted the bb/fix-bb-issue-5598-thr_2z29ajq3hn branch October 16, 2026 23:57
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
erwinkn added a commit to erwinkn/bb that referenced this pull request Oct 26, 2026
… request-outcome events by index (W542). Literal item_kind filters let SQLite use the partial background-task index; the terminal client turn request check moves into @bb/db and filters by type first. Live-DB copy, Equisafe Infra coordinator (196k events): turn-start open-task query 436 to 1.5 ms, thread stop 863 to 1.3 ms, host listing 1,185 to 84 ms, terminal request check 240 to 11 ms; rows identical. Drop on the 0.47.x rebase.

Co-Authored-By: Claude Opus 5.5 <[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