Repository navigation
Conversation
…ecting it Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
deleted the
bb/extend-timeline-window-incrementally-on-push-thr_mwktgwihcc
branch
November 3, 2026 23:36
This was referenced Nov 4, 2026
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
GC is 14% of the production server's busy CPU, and most of the churn comes from rebuilding the latest timeline window for subscribers on every appended event (
runScheduledPush → pushThread → buildWindow → buildThreadTimeline; see the memory investigation report in thr_g29j32rnzg). The latest-window selection memo could only extend a window with bare streaming deltas (item/*/delta,*/progresswith no item kind). Any other event, including everyitem/started/item/completedand every subagent row, missed the memo.selectStandardTimelineEventRowsthen re-read the whole window from SQLite (a fresh string for each row'sdata) and re-decoded it. Even on a memo hit, the event-budget floor was re-found by scanningeventBudget(1,500) rows backwards on every push. Two projection hot spots amplified the rebuild:unwrapQuotedShellArgbuilt double-quoted shell commands one character at a time with+=, which on a Codex thread was 59% of all push allocation, andprojectAssistantAndReasoningEventallocated four argument objects and two closures for every event, text or not.What changed
timeline-selection-memo.ts: the memo now extends the selection with any appended row that the full selection would simply add. Those rows are fetched with the same window query and filters (listStoredTimelineWindowEventRows). An appended row is a plain extension when its turn was already fetched and, if it is parented or atoolCall, its delegating item is already visible. The memo still falls back to a full select for rows that change the selection: turn boundaries, client requests and acceptances, interruptions, head state (goal, extension state, todos, plans), background tasks and delegations, and rows of unseen turns or parents. Appended parented rows refreshorderingBoundarySequencethroughgetTimelineGroupingContext, the path the full select uses.@bb/dbadvanceTimelineWindowBudgetFloorSequence: on a memo hit, the budget floor moves up by the number of budget-counted appended rows. It scans only those rows instead of 1,500. Supersession by background-task progress cannot happen on this path, because those rows always fall back.timeline.ts: the per-row byte count used for build profiling is cached per row object, which memo-extended windows reuse.@bb/thread-view:unwrapQuotedShellArgslices between escapes instead of concatenating per character (fuzzed against the old implementation on 900k inputs: identical output).projectAssistantAndReasoningEventbuilds the buffered-text arguments only when the event carries text, and joins reasoning text only when deltas exist. Both callees already returnedfalsefor missing text.How you verified
Pushed output is byte-identical. A replay harness ran the real
createThreadTimelineWindowspush path against a copy of the scrubbed production subset (thr_n6cyn6sk25subset.db). It removed each thread's last 300 events, re-inserted them one at a time and captured every pushed payload. Across 12 real threads (Codex and Claude Code, heavy subagent and background-task threads), all 3,600 pushes hashed identically on main and on this branch. The randomizedlatest timeline selection memotest also passes (warm build equals a cold build after every step across streaming, out-of-order deltas, rewrites, prunes and context clears, with eventBudget 20, so the floor advance is exercised). New cases cover a subagent child row and a completed delegating item being reused.Warm-versus-cold replay sweep on real data. For threads in the scrubbed subset, I removed each thread's last 2,000 events and re-inserted them one at a time, with the thread
active. After every event I compared the memo-extended build with a fresh build on a second connection with every cross-build cache cleared, byte for byte, response and profile row counts. That is the same check the randomized test makes. Every fifth event also ran theincludeDiagnosticOperationsvariant. The sweep ran in six low-priority processes and was stopped early to avoid holding the PR for hours. Covered so far: 8 heavy threads replayed in full (4.5k–35k events of history; 7 Claude Code, 1 Codex; 16k subagent rows and 668 background-task rows among their events) and 3 small threads from a smoke run. That is 19,688 comparisons, 90.7% of them served by the extended memo, with 0 divergences. Comparisons on the threads still in progress when the sweep stopped are not counted.Real server, before/after. I ran
pnpm start:worktree(production build, real host daemon) on a cloned dev data dir of the subset, with a headless browser subscribed to four heavy threads:m42a25h7y3,dthjzpqr3u,gtbhvapit2andyvsvx8anai, which have 4.5k–57k events of history. The first 500 events of a long real turn on each thread (2,000 events in total) were re-posted through the daemon's/internal/session/eventsroute at 25 ms intervals. Three threads stayedactivethroughout, as live threads do in production;yvsvx8anaistayed idle. Server CPU profile, a GCPerformanceObserverand process CPU time were captured during the replay. Main and branch were interleaved, each on a fresh clone. Main round 1 ran under a load spike (load average ~20) and is excluded.runScheduledPush)The final served timelines match across all runs once ingest timestamps and wall-clock durations ("Thought for 2s" vs "800ms") are normalized. The exception is
gtbhvapit2, whose server-created plugin-form interaction ids (pint_*) are random and differ between two runs of main as well.Thread opens and switches unchanged. I opened 12 heavy threads (thread, timeline and outline requests) cold, then warm twice, on the same instances. Server CPU: cold 1,050–1,060 ms on main vs 1,000–1,050 ms here; warm 270 ms vs 270–290 ms; second warm 240–250 ms vs 250–260 ms. Wall-clock sums are also within noise (cold 904–1,007 vs 866–923 ms).
Harness totals (12 threads × 300 pushes): push CPU 54.6 s → 28.1 s, GC pause 2.8 s → 0.9 s, GC count 3,170 → 1,347. On the heaviest Codex thread, allocation over 300 pushes fell from 5.06 GB (after the memo change, before the parse fix) to 2.07 GB.
Locally:
pnpm exec turbo run typecheck lint --filter=@bb/server --filter=@bb/db --filter=@bb/thread-viewpasses. Targeted tests pass: thread-viewtool-call-parsing, dbevents, and servertimeline-selection-memo,timeline-event-budget,public-thread-diagnostic-events,public-thread-timeline-pushandpublic-thread-timeline-delta. CI runs the full suites.