Repository navigation
Conversation
… tail Every push to a watched thread, and every reopen, re-projected the whole latest timeline window from raw events. The server now projects a thread in closed units (no running turn, unfinished item or pending request at the cut, nothing later referring back), keeps the rows of finished units in memory per thread, and re-projects only the open tail. Background-task completions belong to the unit that started the task, so long-running tasks do not join the turns they outlive. A small latest-window memo keeps #6964's push-path savings for the budget floor, head state and ordering boundary. This replaces timeline-selection-memo.ts. olderRowsSourceSeqEnd now counts only omitted rows that reach into the page window. Rows match main on 2,502 pages of the scrubbed subset and 3,600 replayed pushes; push read CPU 19.1 s -> 8.8 s, GC count -62%. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Collaborator
Author
|
Closing in favour of #7012. Michael chose one read path: main's sparse selection, projected once, with pushes feeding only appended events into kept projector state, instead of this PR's separate unit-based read path. #7012 is byte-identical to main on all page parity and pushed windows (subset.db and heavy.db) and cuts the median push by about a third.
|
ymichael
added a commit
that referenced
this pull request
Nov 4, 2026
## Human comments ## What was wrong Every push to a watched thread rebuilt most of the latest window. #6964 made the sparse selection incremental (the selection memo extends the window with appended events), but: - `buildThreadTimelineFromEvents` still folded every event of the selection: tool-argument and shell parsing, assistant and reasoning text, the per-event state machine. Profiling main's push path with a replay of real events put that fold at 27–32% of push CPU. - The memo re-selected from the database far more often than needed. A replay analysis in @thread:thr_932ndnsbdg found memo misses at 64–69% of push CPU (22 heavy threads, 2,000 events each), and the fresh selection was identical to the extended one in almost every case: - children of a parent with no tool-call rows (Claude Code background tasks parented to a shell command), 19–40% of push CPU, and 60–85% on three threads; - turn starts, acceptances and completions, plus background task starts and completions, about 3–6% each; - every read of a thread that was not active (7.5%), plus the first read after it became active again (6.2%); - tool calls without children (1–2%). - Every turn boundary recomputed the ordering context behind turn grouping by scanning all request and turn rows since the context epoch. - A moved window start (a new request, or the event budget passing a request) re-ran the whole selection against the database, although the new window is part of the old one. ## What changed One read path (main's sparse selection and memo), extended in place where a fresh read would give the same rows. **Kept projection** (`@bb/thread-view` `build-event-projection.ts`, `build-thread-timeline.ts`, server `timeline-projection-fold.ts`): - The per-event loop body of `buildFlatProjectionData` is now `foldProjectionEvent`. It moved unchanged (`continue` → `return`), so the diff is large but mechanical. New `startEventProjectionFold` / `resumeEventProjectionFold` / `finishEventProjectionFold`: - The fold's lookups over the whole selection are built from `client/turn/requested`, `client/turn/rejected`, `turn/input/accepted` and `turn/started` only. `resumeEventProjectionFold` refuses those event types and out-of-order events, so a resumed fold always has the lookups a fresh fold would. - Finishing (flush the active tool cell, finalize interrupted turns, enrich background-agent models) mutates state, so it runs on a copy: - For an active thread with no interrupted turn in the window, the copy shares message objects and copies only the containers finishing touches and the workflow messages it enriches. - Otherwise the copy is a `structuredClone`. - For active threads the build keeps the fold per selection key (16 windows). The next build resumes it only if the new selection starts with exactly the row objects it folded. Any other selection projects from scratch, exactly as main, and keeps that fold. **Selection memo extensions** (`timeline-selection-memo.ts`). Each appended row is checked against the rows a fresh selection would add, with targeted queries. Any doubt selects afresh. 1. *Parent rules.* A child of a parent id is accepted when the parent is visible, or when it has no `toolCall`/`delegation` rows (the result is remembered per entry). A new tool call is accepted when it has no earlier children. 2. *Turn and background-task events, idle threads.* Turn starts, acceptances and completions, and background task starts and completions, now extend the memo: - A newly fetched turn must have no earlier rows, and its `turn/started` row must already be selected. - An acceptance's request rows must be selected, and the request must have no other acceptance. - A background task completion must not drop rows: there are no earlier progress rows, and its started row is kept by the window, its turn or its parent. - The memo no longer forgets threads that are not active (selection never depended on status). At most 4 of its 16 entries can belong to non-active threads, so browsing idle threads cannot evict active ones. - `history-rewritten` and `history-compacted` notifications now drop the thread's memo entries and folds. 3. *Incremental ordering context* (`timeline-context-order.ts`). The ordering context keeps its request and turn rows per thread and epoch and reads only rows after the last read; the derivation over those rows is unchanged. The memo reads request ids and acceptances from it. 4. *Trim on window-start moves.* New requests extend the memo too (unique request id, no earlier acceptance or rejection) and update the cached window hints. - When the start moves forward, `selectStandardTimelineEventRows` reruns over a row source backed by the kept rows plus the appended rows instead of the database. These cover thread window rows, root window turns, turn rows, children and context rows. Queries that are cheap and unbounded (head state, background task state, interruptions, request lookups) still go to the database. - The source throws a fallback (and the build re-selects from the database) whenever a query would need a turn or children it never fetched, or a parent row it does not hold. - In the randomized memo test this path ran 227 times across 25 seeds without a fallback, and every result equaled a cold build. Not changed: the decode cache size, and no sticky window. There is no wire, protocol, CLI or settings change, and no change for older pages. Docs: `docs/timeline-pagination.md` describes the extended selection, the trim and the kept projection. ## How you verified Data: the scrubbed `subset.db` (300 threads) and `heavy.db` (all 353 production threads with 2,000+ events, 1.89M events), as migrated clones; never a copy of `~/.bb/bb.db`. Main is this PR's base, d060de8. The replay harness: - removes each thread's last 300 events and re-inserts them one at a time; - flips the thread's status the way the server does (active on a request or root turn start, idle or error on root turn completion); - reads the latest window with the previous tag through `createThreadTimelineWindows().read`, which is the push's `buildWindow` + delta path. It replays 12 subset threads and 17 heavy threads (the 12 heaviest plus the five @thread:thr_932ndnsbdg threads with the most misses). Timings ran at background priority on a shared machine, with stages interleaved, so compare ratios rather than absolute times. **Output is identical to main** (final code): - Page parity: every thread × idle/active × default/nested/inline × latest + 5 older pages. That is 2,502 responses (subset) and 7,050 (heavy), **byte-identical to main on all 9,552**. - Push replay: **every pushed window's tag is identical to main**, 3,600/3,600 (subset) and 5,100/5,100 (heavy). - Warm (kept selection and fold) == cold (fresh connection, all caches cleared) **after every event**: 3,600 checks on subset and 5,100 on heavy, **0 mismatches**. **Push CPU per fix** (cumulative; total push read CPU, median and p95 per push, GC collections; rounds 1 / 2): | stage | subset CPU | subset p50 / p95 | heavy CPU | heavy p50 / p95 | GC (subset / heavy) | |---|---|---|---|---|---| | main | 112.8 / 116.4 s | 24.1 / 91.9 ms | 252.7 / 263.4 s | 24.9 / 132.9 ms | 1,105 / 2,822 | | kept projection | 90.8 / 91.9 s | 14.5 / 90.2 ms | 219.2 / 219.8 s | 16.5 / 132.1 ms | 771 / 2,331 | | + 1 parent rules | 90.4 / 90.7 s | 14.7 / 91.1 ms | 180.2 / 180.2 s | 16.6 / 115.2 ms | 763 / 1,820 | | + 2 turn/task events, idle threads | 72.2 / 68.9 s | 14.1 / 49.0 ms | 125.2 / 124.1 s | 15.9 / 74.9 ms | 594 / 1,174 | | + 3 incremental ordering context | 69.9 / 69.4 s | 13.9 / 44.7 ms | 112.0 / 111.1 s | 15.5 / 54.3 ms | 582 / 1,180 | | + 4 trim on start moves | **64.7 / 59.7 s** | **13.7 / 40.2 ms** | **106.6 / 104.3 s** | **14.9 / 51.0 ms** | **549 / 1,096** | All told, against main: push CPU is **−43% / −49%** on subset and **−58% / −60%** on heavy (rounds 1 / 2), p95 push is **−56%** (subset) and **−62%** (heavy), and GC collections are **−50%** and **−61%**. The intermediate stages were measured as patches of the final code that turn later fixes off: - stage 1 keeps turn and background-task events as selection-changing, keeps the memo active-only, and rescans the ordering context; - stage 2 rescans the ordering context. Per thread (round 1, push CPU over 300 events, main → final): | thread | main | kept projection | +1 | +2 | +3 | +4 | |---|---|---|---|---|---|---| | `thr_m46b55x3yc` (orphan-parent background tasks) | 17.0 s | 12.8 | 12.0 | 4.9 | 4.9 | 4.5 | | `thr_d5ej4e2gtv` (short turns) | 16.9 s | 16.3 | 16.9 | 11.3 | 7.8 | 7.5 | | `thr_9ighpmg7u5` (short turns) | 10.1 s | 9.7 | 9.8 | 8.5 | 4.1 | 3.4 | | `thr_gcuc46ug4j` | 14.8 s | 9.8 | 10.2 | 9.1 | 8.8 | 8.4 | | `thr_ymhw6pktq4` | 5.9 s | 5.6 | 5.4 | 3.9 | 3.9 | 3.5 | In this 300-event replay, parent rules alone help less than @thread:thr_932ndnsbdg's 2,000-event estimate suggests: on those threads, most orphan-parent pushes also start or complete a background task, which needs fix 2. **Thread opens** (best of 2, all threads, cold = fresh connection): subset 20.7 s main vs 20.9 s, heavy 45.3 s vs 44.6 s. Warm reopens of the replay threads: subset 1,052 vs 1,061 ms, heavy 2,207 vs 2,241 ms. **Tests.** - `event-projection-fold.test.ts`: a fold resumed from every point equals a cold build after every appended event, and resume refuses lookup events. - Selection memo tests: - The randomized warm == cold test now also generates background tasks parented to commands and tool calls, plus subagent turns. Locally it ran with 25 seeds; CI runs 5. - Cases for parents without rows and for childless tool calls. - The idle-entry cap. - Locally at low priority: `pnpm exec turbo run typecheck --filter=@bb/server`, plus vitest for `test/services/threads/`, `timeline-streaming-memo`, `timeline-pagination-correctness`, `public-thread-timeline-*` and `public-thread-diagnostic-events` (340 tests). CI runs the full suites. Supersedes #6980 (in-memory units on a separate read path). > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[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.
Human comments
What was wrong
Every push to a watched thread, and every reopen, re-projected the whole latest timeline window from raw events, although almost all of it is finished history that cannot change. #6964 made the window selection incremental on push, but each push still decoded and projected every event of every turn touching the window. After #6964 the push path was still about 75% of the server's busy CPU during live turns (
runScheduledPush → pushThread → buildWindow → buildThreadTimeline).What changed
The server now projects a thread in closed units and keeps the rows of finished units in memory. This is a rebuild on current main of the in-memory part of the thr_37bttnej8k prototype (2c78bb1d60 and 06a5c350d0). Its SQLite storage (e9bff75248) is left for a later PR.
timeline-units.ts: cut analysis. A unit is a contiguous sequence range that nothing later refers to and that leaves nothing open: no running turn, unfinished item or pending request. Projecting each unit on its own and joining the results gives the same rows as projecting the whole history.timeline-projector.ts(new; replacestimeline-selection-memo.ts): a per-thread log, held per DB connection. It keeps the projected rows of finished units per display surface and the events of the open tail. A read decodes only the events appended since the previous read and re-projects only the tail. A later event that refers into a finished unit merges that unit back into the tail. Rewrites, compaction and deletes drop the thread. The cap is 64 threads and about 96M characters of event data.hvmnv3jvfv: two dev servers started 1,200 events back), and it differed from main for below-head snapshots.timeline-latest-window-memo.ts: keeps Extend the latest timeline window on push instead of re-selecting it #6964's savings on the push path for reads at the thread's head:hasOlderSegmentsprobe is cached for an unchanged window start.timeline.ts:buildThreadTimelineInternalkeeps window bounds, ordering, previews, deferral and pagination. It drops the sparse selection and its window fix-up queries (net −177 lines).@bb/db: added the range read, earliest-reference, unfinished-turn/task, background-task ownership, latest-interruption, appended-event summary and budget-floor-advance queries, with query-plan tests. Removed five selection-only queries.@bb/thread-view: addedprojectThreadTimelineUnitandbuildThreadTimelineFromUnits.foreignBackgroundTaskSeqsandthreadInterruptedAtare new projection options. Extend the latest timeline window on push instead of re-selecting it #6964's allocation fixes are unchanged.timelinePage.olderRowsSourceSeqEndnow counts only omitted rows that reach into the page's window. Before, it also counted rows ending before the window start, which main's sparse selection happened to project, so the value depended on how far back a build read. The client merge already treats every row that ends before the window start as older, so those values never changed a merge. Documented indocs/timeline-pagination.md, along with the new projection-units section.Known limits:
hvmnv3jvfvpush CPU is unchanged. Incremental projection inside a turn is a follow-up.rmskncan3a's first read is 5.7 ms slower (24.4 → 30.1 ms, median of 20). Its Codex long-running commands complete several turns after they started, and each lateitem/completedjoins those turns into one unit, so a cold read projects 2,253 events where main projected 1,642. Detaching late command completions the way background tasks are detached would fix it. That needs owner-unit projection forolderRowUpdates, so I left it out of this PR.How you verified
All measurements use the scrubbed subset (
thr_n6cyn6sk25/perf/data/subset.db, migrated clone, 300 threads with events). Main is c914310 in a separate checkout. #6964's replay harness storage was deleted when its thread was archived, so I rebuilt it from the PR description. It deletes each thread's last 300 events, marks the threadactive, and re-inserts the events one at a time. After each event it reads the latest window with the previous tag throughcreateThreadTimelineWindows().read, the samebuildWindowand delta path the push uses. Each read's CPU time is measured withprocess.cpuUsage, and GC with aPerformanceObserver. Main and branch runs were interleaved on a shared machine.Rows are identical to main.
olderRowsSourceSeqEnd, where main reported a row ending before the window start. Against main with only theolderRowsSourceSeqEndrule applied, all 2,502 responses are byte-identical.timeline projectortest also compares warm and cold builds across streaming, rewrites, prunes, context clears and interruptions. Its cold side now also clears the new window memo.Push CPU and GC (12 threads × 300 events, 2 runs each):
One branch run's GC pause includes a slow major GC under machine load. Its CPU time and GC count match the other run. Per-thread push CPU fell on 10 of 12 threads, for example
gtbhvapit22.1 → 0.8 s andm42a25h7y31.8 → 0.6 s.hvmnv3jvfvis unchanged, as described above.Thread opens:
ci4wag9p6h13.5 vs 13.4 ms,yvsvx8anai19.0 vs 19.4 ms). The exception isrmskncan3a, above.Browser scroll/jump check. I ran
pnpm start:worktreefor main and for this branch, each on its own data dir seeded with the subset. The subset has no account credential, and neither server dialed Connect. In headless Chromium, each of 6 heavy threads got 40 upward wheel steps (25 onrmskncan3abefore reaching the top). After each step I measured the anchor row's position as older pages loaded. Both builds had 0 jumps, 0 px drift and the same number of older-page loads (22 ongtbhvapit2).Tests:
pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/db --filter=@bb/thread-viewpasses. Targeted vitest runs pass: servertimeline-*andpublic-thread-timeline-*pluspublic-thread-diagnostic-events(233 tests), dbeventsandquery-plans(153), and all of thread-view (510). CI runs the full suites.🤖 Generated with Claude Code