Skip to content

Run conversation outline and timeline reads in reader worker threads - #7766

Closed
ymichael wants to merge 2 commits into
mainfrom
bb/sqlite-reader-workers-phase-a-kill-tests-6499-thr_e2yjyfcg3d
Closed

ymichael wants to merge 2 commits into
mainfrom
bb/sqlite-reader-workers-phase-a-kill-tests-6499-thr_e2yjyfcg3d

Conversation

@ymichael

@ymichael ymichael commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

The server reads SQLite synchronously on its main thread. Conversation outlines and timeline builds (page reads and live pushes) ran their SQL and projection there, so on a slow or contended disk one large read blocked heartbeats, WebSocket traffic and HTTP routing for seconds. #7753 (0.49.0, 15 GB bb.db) shows event-loop stalls with p99 30.5 s and max 61.7 s; its attributed stall work is mostly these reads (conversation-outline 4,762 s wall, timeline-build 2,804 s), and about 85% of slow-query time is off-CPU (I/O wait). This is item 3 of #6499 (Phase A: reads).

What changed

  • Reader worker pool (apps/server/src/services/threads/read-pool/, apps/server/src/thread-read-worker.ts, new bundle dist/thread-read-worker.js). max(1, min(4, cores/2)) workers, so a 1–2 vCPU host still gets one; a pool created with size 0 runs reads in-process, each with a read-only connection (createReadOnlyConnection in @bb/db) and an 8 MB page cache. Each thread is pinned to one worker by thread ID. A worker that crashes or fails to start has its pending and later reads run on the main thread, logs Thread read worker stopped; running its reads on the main thread, and restarts after 10 s.
  • The whole read moves, not just the build. For GET /threads/:id/conversation-outline, GET /threads/:id/timeline and live timeline pushes, the worker does the thread lookup, settings, maxSeq, outline-sequence check, both route caches, SQL, projection, output shortening and tagging, inside one deferred read transaction. Main sends only the thread ID, its in-memory rewrite generation and provider facts (cached per provider-registry revision), so it does no SQLite on these paths. Main keeps served windows, delta computation and push fan-out. The main-side outline LRU and timeline window cache are deleted; their equivalents live in the workers.
  • Row digests travel with the window. Workers return each top-level row's digest (hash, jsonLength) with the response, and main seeds its digest cache with them. Without this, delta computation, tagging and served-window sizing on main re-stringified and sha256-hashed every structured-cloned row on every push.
  • Live pushes are single-flight per thread (thread-timeline-windows.ts). While a push build is in flight, further events-appended notifications set one pending flag; one follow-up push runs after it finishes. Subscribers and baselines are read after the build returns.
  • Cache invalidation no longer uses PRAGMA data_version. On a reader connection, every main commit changes data_version, which would make every worker cache cold. The outline, selection-memo, projection-fold, ordering-context and latest-state caches now key on the per-thread rewrite generation that main sends with each read. Retained-output expiry and history-compacted/history-rewritten notifications now bump that generation, as the other history mutators already did.
  • The stored conversation outline is deleted. Migration 0158_drop_thread_conversation_outlines drops thread_conversation_outlines; its read and save paths, the rewind delete and its query-cost cases go with it. It existed (Speed up conversation outline reads #2668) to avoid main-thread outline rebuilds after a restart. Workers make that unnecessary, and its key held the process-local rewrite generation, so 83% of stored outlines in a production copy (2,143 of 2,574) could not match after a restart anyway. Its save was the last main-thread cost on the outline path: up to 1.2 s per save on a starved disk.
  • The slow-build log Thread timeline build blocked the event loop is now Slow thread timeline build. Its CPU and context-switch fields are process-wide while the build runs in a worker. Docs: docs/configuration.md, docs/debugging-and-qa.md, docs/timeline-pagination.md.
  • No server/daemon wire changes; HOST_DAEMON_PROTOCOL_VERSION is unchanged. No CLI or SDK surface changes.

Behaviour changes

Change Effect
thread_conversation_outlines dropped The first outline open of an idle thread after a restart is built in a worker instead of read from the table. On a production copy that costs 85–570 ms of worker time for the largest outlines, none of it on main.
Live pushes coalesce while a build is in flight Fewer, larger pushes: 369 vs 1,246 for a 1,636-event turn and 95 vs 493 for a 971-event turn. In both replays every delta applied, nothing arrived out of order, and the final state was identical.
Worker memory 4 idle workers add about 265 MB footprint. Warm (60 large threads, outline plus two windows each, two rounds), the median is +54 MB vs reading on main, because main's own caches stay empty. A 256 MB reader page cache would cost about +640 MB, hence 8 MB.
Writes from another DB connection are not detected by the read caches bb has no other writer; every in-process mutation that rewrites history bumps the rewrite generation. Four tests that simulated rewrites with a second connection now bump the generation the way real mutators do.
Each worker read holds a WAL read snapshot for its duration A long build delays checkpoint progress past its snapshot until it finishes, as timeline-build already did on main.
Log message rename Slow thread timeline build replaces Thread timeline build blocked the event loop.

How you verified

Kill-tests on a production copy

VACUUM INTO copy of a 10 GB production bb.db (9.3 GB, 16-core M4, Node 22.23.1). The harness runs this branch's server code against the copy without starting a server.

K1, same output. All 20 largest threads (outline plus latest timeline window) give deep-equal results in-process and through the bundled worker: 40/40.

K2, transfer cost. Receiving the result on main, at most 1.07% of the build's main-thread time by structured clone (largest outline, 1.25 MB: 0.91 ms vs 84.7 ms) and 0.18% as a JSON string.

K3, starved disk. 20 concurrent outline and timeline loads across the 10 largest threads. Conditions: a fresh APFS clone (cold page cache), the process under taskpolicy -d throttle, and 8 F_FULLFSYNC writers plus 8 F_NOCACHE random readers competing for the disk.

Main event-loop max delay Reads on main Reader workers
Starved disk 19,020 ms 3 ms (no gap over 50 ms in 8.1 s)
Cold cache, no throttle 4,278 ms 6 ms

With the stored-outline save still on main, the pool path was 1,204–1,238 ms, all of it saves; that is why the table is deleted. An earlier run with only the builds in workers was 289–328 ms; all of that was the outline route's small point reads left on main, which is why the whole read moved.

K4, push ordering. Two busy production turns were deleted from a copy and replayed event by event at 2 ms pacing, through today's synchronous push path (from origin/main) and through the queued pool path. Each had two subscribers (20 segments deferred, 8 segments full). In both paths there were 0 failed delta applies and 0 out-of-order pushes, the last push reached the final maxSeq, the final client state equals a fresh read, and the final tags are identical. Main-loop p99 during replay: 3.2–4.3 ms with the pool vs 7.5–8.9 ms on today's path.

Main-thread CPU per live push. Measured with a main-thread --cpu-prof on the K4 replays: inclusive time under runScheduledPush/pushThread, divided by push signals sent. rowDigest is the per-row JSON plus sha256.

Replay main (build on main) This PR before digest seeding This PR
1,636-event turn, per push 1.47–1.49 ms (row hashing 0.01 ms) 0.54–0.55 ms (row hashing 0.44 ms) 0.10–0.11 ms (row hashing 0.01 ms)
971-event turn, per push 2.58 ms (row hashing 0.46 ms) — 0.33 ms (row hashing 0 ms)

main 2 runs, before-seeding 2 runs, this PR 3 runs (1,636-event turn); 1 run each for the 971-event turn. Every run kept 0 failed applies, 0 out-of-order pushes and a final state equal to a fresh read.

K5, memory (footprint, not RSS, because RSS counts the mmapped bb.db). In-process warm median 1,202 MB (5 runs). The pool:

Workers × page cache Warm footprint vs in-process
4 × 8 MB (shipped) 1,256 MB (3 runs) +54 MB
4 × 32 MB 1,439 MB +237 MB
4 × 256 MB ~1,840 MB about +640 MB

Tests

  • thread-read-pool.test.ts:
    • a worker dying mid-read finishes the read on main;
    • a size-0 pool runs reads in-process without starting a worker, and threadReadPoolSize never returns less than 1;
    • main's row digests for a window read through a real worker match the rows main received (it fails when the digests are misaligned);
    • workers that cannot start (real worker, missing DB) run reads on main and log the reason;
    • API errors keep their status and code;
    • a real worker's cached window is kept across an unrelated commit and dropped once main's rewrite generation changes.
  • thread-timeline-push-queue.test.ts: one build in flight per thread; appends during a build coalesce into one ordered follow-up push whose deltas apply and match a fresh read. It fails with single-flight removed (expected 2 to be 1).
  • conversation-outline-performance.test.ts: the worker's outline cache serves a repeat read without reading event rows, and a rename or a rewind re-projects.
  • Updated callers of the async ThreadTimelineWindows.read(threadId, …); the deleted-thread test now asserts a 404 instead of a cache drop.
  • Ran: pnpm exec turbo run typecheck lint:type-aware --filter='...[origin/main]' (20/20); apps/server test/services/threads, test/public, test/system/thread-pruning-invalidation.test.ts, test/app/startup-diagnostics.test.ts (1,039 passed); packages/db test/data/events.test.ts, test/migrate.test.ts (164 passed); tests/integration timeline and lifecycle smoke tests (9 passed). An earlier full @bb/server + @bb/db run on the branch before the table deletion passed (414 + 66 files).

Live (verify-bb, production build)

pnpm start:worktree on a fresh dev data dir:

  • A synthetic 129,079-event thread (buildHistoryFixture) opened from the sidebar in 2.7 s. Its outline listed all 2,001 user messages in order. Clicking Turn 1 in the outline paged back to it.
  • A live Claude Code turn typed into the composer streamed in 37 incremental updates in order, with no duplicates, and matched after reload.
  • 0 Event loop stalled, 0 worker stops and 0 failed pushes in the server log. The built server and source mode also started workers cleanly on a fresh data dir.

Unrelated issues found along the way: buildHistoryFixture writes a turn-scoped item/backgroundTask/completed event that the stored-event parser rejects (older pages of that fixture return 500 on main too), and the verify-bb inventory reports the diagnostics CLI family as unmapped.

Part of #6499; see #7753.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 2 commits November 18, 2026 01:28
The outline and timeline routes and live timeline pushes now run their whole
read (thread lookup, settings, caches, SQL and projection) in a pool of up to
four worker threads, each with a read-only SQLite connection and an 8 MB page
cache. The main thread sends the thread ID, its in-memory rewrite generation
and provider facts, and keeps served windows, deltas and push fan-out. Live
pushes are single-flight per thread and coalesce appends while a build runs.
Reads fall back to the main thread when a worker is unavailable.

Incremental caches key on the rewrite generation instead of PRAGMA
data_version; retained-output expiry and history-compacted/rewritten
notifications now bump it. The stored conversation outline
(thread_conversation_outlines) and its main-thread save are deleted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…worker

Workers return each top-level row's digest with the timeline window, and
main seeds its digest cache with them, so delta computation, tagging and
served-window sizing on main stop re-stringifying and hashing every cloned
row on every push. The pool size never drops below one worker, and a pool
created with size 0 runs reads in-process instead of indexing an empty slot
list.

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