Skip to content

Project each finished timeline unit once and re-project only the open tail - #6980

Closed
ymichael wants to merge 1 commit into
mainfrom
bb/project-each-finished-timeline-unit-once-in-memo-thr_envvcje6te
Closed

ymichael wants to merge 1 commit into
mainfrom
bb/project-each-finished-timeline-unit-once-in-memo-thr_envvcje6te

Conversation

@ymichael

@ymichael ymichael commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

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; replaces timeline-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.
  • Background tasks belong to the turn that started them. A task that never reported progress has its completion projected by the unit that started it. The unit where the completion arrives only closes its open tool group there, so long-running tasks do not join the turns they outlive. Tasks that report progress stay joined until they finish, as in the prototype.
  • The latest page's running commands and workflows come from the window's units. Tasks started before the window are read the way main reads them: each open task's latest state row, plus its turn's start and completion. The prototype projected the whole unit that started each running task instead. That made one cold read here 3× slower (hvmnv3jvfv: two dev servers started 1,200 events back), and it differed from main for below-head snapshots.
  • An idle thread's unfinished tool rows take the time of the thread's latest interruption. Main read every interruption in the epoch, so this time comes from one indexed query and is part of the unit cache key for non-active threads.
  • 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:
    • The 1,500-event budget floor advances by the number of appended events.
    • Head-state rows (goal, plan/todos, extension state) are re-read only when an appended event can change them.
    • The ordering boundary is re-read only after appended ordering or parented rows.
    • The hasOlderSegments probe is cached for an unchanged window start.
    • Appended background-task progress or completions fall back to a full scan.
  • timeline.ts: buildThreadTimelineInternal keeps 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: added projectThreadTimelineUnit and buildThreadTimelineFromUnits. foreignBackgroundTaskSeqs and threadInterruptedAt are new projection options. Extend the latest timeline window on push instead of re-selecting it #6964's allocation fixes are unchanged.
  • One response field changes. timelinePage.olderRowsSourceSeqEnd now 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 in docs/timeline-pagination.md, along with the new projection-units section.
  • No wire, protocol, CLI or setting changes.

Known limits:

  • A thread inside one very long open turn still re-projects that whole turn on every push. On hvmnv3jvfv push 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 late item/completed joins 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 for olderRowUpdates, 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 thread active, and re-inserts the events one at a time. After each event it reads the latest window with the previous tag through createThreadTimelineWindows().read, the same buildWindow and delta path the push uses. Each read's CPU time is measured with process.cpuUsage, and GC with a PerformanceObserver. Main and branch runs were interleaved on a shared machine.

Rows are identical to main.

  • Pages: all 300 threads × idle/active × default/nested/inline × latest plus up to 5 older pages, 2,502 responses. Rows are identical on all of them. 54 responses differ only in olderRowsSourceSeqEnd, where main reported a row ending before the window start. Against main with only the olderRowsSourceSeqEnd rule applied, all 2,502 responses are byte-identical.
  • Pushes: 12 threads × 300 pushes, 3,600 window tags. All are byte-identical to main with the rule applied. Against main, 646 differ only in that field.
  • Warm vs cold: 1,400 replayed steps. Each step's incremental build was compared with a build on a fresh connection, with 0 differences. The randomized timeline projector test 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):

main this PR
Read CPU, total 19.2 / 19.1 s 8.5 / 9.1 s (−54%)
Read CPU p50 / p95 3.9 / 15.8 ms, 3.8 / 14.5 ms 1.5 / 6.4 ms, 1.7 / 7.0 ms
Read CPU max 65 / 73 ms 30 / 19 ms
GC count 1,083 / 1,086 411 / 401 (−62%)
Major GCs 6 / 6 5 / 2
GC pause 627 / 643 ms 229 / 810 ms

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 gtbhvapit2 2.1 → 0.8 s and m42a25h7y3 1.8 → 0.6 s. hvmnv3jvfv is unchanged, as described above.

Thread opens:

  • Cold first read of the latest page, all 300 threads, fresh process, 3 rounds: per-thread best totals 3,671 → 3,275 ms (−11%). The sweep flagged 7 threads as more than 1 ms slower. Focused repeated runs show 6 of them within noise (e.g. ci4wag9p6h 13.5 vs 13.4 ms, yvsvx8anai 19.0 vs 19.4 ms). The exception is rmskncan3a, above.
  • Warm reopen of 12 heavy threads, with a fresh response cache and in-process caches warm: 188–202 ms → 11–14 ms per round of 12 opens. After a 300-thread cold pass, which exceeds the 64-thread cap, the first reopen round is 221 vs 205 ms.
  • Scroll-back over 133 older pages of the 60 largest threads, fresh process: 2,482 → 2,085 ms. Per page, p50 16.6 → 14.1 ms and max 153 → 132 ms.

Browser scroll/jump check. I ran pnpm start:worktree for 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 on rmskncan3a before 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 on gtbhvapit2).

Tests:

  • New tests:
    • a late background-task completion projected with its starting turn, warm equal to cold;
    • an idle thread's unfinished command finishing at the latest interruption (fails without the new option);
    • query-plan coverage for the new queries.
  • Main's open-task query test and its lagging-snapshot expectations are restored.
  • Locally: pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/db --filter=@bb/thread-view passes. Targeted vitest runs pass: server timeline-* and public-thread-timeline-* plus public-thread-diagnostic-events (233 tests), db events and query-plans (153), and all of thread-view (510). CI runs the full suites.

AGENT GENERATED

🤖 Generated with Claude Code

… 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]>
@ymichael

ymichael commented Nov 4, 2026

Copy link
Copy Markdown
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.

AGENT GENERATED

@ymichael ymichael closed this 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]>
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