Skip to content

Make timeline pushes cost closer to the rows that changed - #7244

Merged
ymichael merged 4 commits into
mainfrom
bb/timeline-s4-hit-path-window-sized-costs-thr_jn4p352bnn
Nov 9, 2026
Merged

ymichael merged 4 commits into
mainfrom
bb/timeline-s4-hit-path-window-sized-costs-thr_jn4p352bnn

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

With the selection memo and projection fold both hitting, a push for one new event still ran several passes over the whole latest window (timeline perf audit, REPORT #5). On the snapshot threads the biggest were:

  • Settled delegations. Their child rows were built and mapped bottom-up, then thrown away by deferSettledTimelineRow (572 of 634 rows on kdrbtee92b).
  • Sent-message detection. parseThreadTellCommand scanned every command's text several times per build (2 MB per pass on u738kqjs29, about 14% of a push).
  • Interrupted turns. Once any turn in the window had been interrupted, every fold finish ran structuredClone on the whole projection state, because pendingFinalizationByTurnId is never cleared (6 of 150 sampled active threads, 1–1.8 ms per push).
  • Decoding and byte counts. Every row was decoded and its bytes counted again.
  • Byte-budget pagination. It ran JSON.stringify on every leaf, then on every returned segment.
  • Tag and delta. Every row object was fresh each build, so the tag and delta hashed and stringified all of them again.

What changed

  • thread-view. buildThreadTimelineFromEvents takes a new omitSettledDelegationChildRows option. The server sets it when deferContent is on, and settled delegations then skip building their child rows. Emptiness is still checked lazily, so the output keeps the exact null vs [] that deferral produced.
  • thread-view. parseThreadTellCommand results are cached by command string, bounded the same way as shellIntentCache (16k entries, 8M chars), and every call returns a fresh object.
  • thread-view. copyProjectionStateForFinish deep-copies only when interrupted-turn finalization would actually change something: a running call, or a pending message or cell scoped to that turn. interruptedTurnFinalizationChangesState implements the check.
  • server.
    • timeline-selection-decode.ts / timeline-selection-memo.ts: when a selection extends the previous one, it reuses the decoded prefix and its byte count. The decoded rows live on the selection memo entry whose rows they decode, so they have exactly the memo's bounds (16 entries, 4 idle, 16M data chars) and go away wherever the memo drops an entry: thread delete, rewrite generation or data_version change, context-clear epoch change, and eviction.
    • timeline-content-pagination.ts / timeline-pagination.ts: JSON byte counts are cached per row object, and array and parent sizes are derived from their parts (exact for any UTF-8).
    • timeline-window-reuse.ts: unchanged latest-window rows, and window fields like todos and provider commands, are reused from the previous build when they serialize identically, key order included. The tag, delta and cache accounting then only touch rows that changed. getOrBuild now passes the stale response to the builder for this.
    • timeline-selection-memo.ts: the previous build's pageable rows, which the next build reuses rows from, live on the selection memo entry, one set per deferContent/includeNestedRows variant. Their JSON bytes count toward the memo's 16M budget along with the selection's data chars, and they go away wherever the memo drops an entry. Only rows whose JSON size pagination already measured are kept, so the size costs nothing extra (e515883).
  • server, after rebasing onto Share timeline window builds across page shapes and key caches correctly #7245. Share timeline window builds across page shapes and key caches correctly #7245's projection cache shares built rows between windows and keyed them only by includeNestedRows. Deferred reads now leave out settled delegations' child rows, so a CLI read after an app read could reuse the app's rows and lose a subagent's children. timeline-projection-cache.ts now keys rows by includeNestedRows and omitSettledDelegationChildRows. The first non-deferred read after an app read builds its own rows; the projection is still shared. In the selection memo, a selection shared by several entries counts its data once, and kept pageable rows count per entry. An entry that adopts a sibling's selection starts with no kept rows instead of sharing the sibling's map.
  • No contract change. No wire, CLI, SDK or plugin surface changes. Output is byte-identical to main.

Not changed:

  • Push pacing still waits the last build's duration (capped at 1 s). Cheaper builds shorten it directly.
  • Remaining u738kqjs29 cost. Most of its remaining push cost is the fold finish over completed turn t3 (7.4k events). The window loads t3 only as context and the page doesn't return it. Removing that needs page-bounded reads (Latest timeline page decodes every event of an open turn on each build, bypassing timelineWindowEventBudget #4674 / S6), not hit-path work.
  • kdrbtee92b grouping-context SQL. About 10% of its push is still getTimelineGroupingContext running again whenever child (parented) events are appended.

How you verified

Before/after. Harness push scenario: warm latest read with afterTag after appending one item/started. In-process on a clone of the Nov 7 snapshot. 4 alternating main/branch pairs × 12 appends, load average 14–19 (other slices were benchmarking at the same time). Median of per-run medians:

thread main ms branch ms Δ
kdrbtee92b (active) 4.0 (3.5–4.4) 2.8 (2.8–3.0) −30%
u738kqjs29 (forced active) 15.4 (14.3–16.2) 9.8 (9.4–10.6) −36%
8nnix6m53a (forced active) 5.9 3.0 −48%
gyi25h9awq (forced active) 10.6 4.7 −56%
wg5iwwrezi (forced active) 10.9 4.3 −61%
txqr3djnmd (forced active, interrupted turn) 8.0 2.5 −69%
mwktgwihcc (forced active, interrupted turn) 8.1 3.2 −60%

An earlier round of 3 pairs at load average 37–58 showed the same direction, with −16% to −61% and much wider spread.

Memory. The first version of this PR kept decoded selections in a separate per-connection cache: 4 per thread for 64 threads, bounded by count only, never dropped on thread delete, rewrite or idle. It retained rows the memo and the stored-event decode cache had already released. They now live on the memo entries (49f4151). Retained heapUsed after one instance reads the app, phone, CLI and nested windows of each thread, after a forced GC, on a clone of the snapshot:

scenario main c381f52 49f4151
12 harness threads +63 MB +321 MB (261 MB in the decoded-selection cache) +67 MB
12 harness + 293 most recent threads +109 MB +295 MB +108 MB
12 harness threads, forced active – – +74 MB

Push and warm timings for 49f4151 vs c381f52: harness push + warm, 9 alternating pairs × 12 appends (3 of them reversed-order, 3 interleaved), load average 7–9. Median of per-run medians:

case c381f52 49f4151
warm push, kdrbtee92b 2.5 ms 2.4 ms
warm push, u738kqjs29 (forced active) 8.8 ms 9.1 ms (last 3 interleaved pairs: 8.8 vs 8.8)
cold after append, kdrbtee92b / u738kqjs29 33.4 / 207.8 ms 34.0 / 207.4 ms
warm cache hit, all 12 threads 0.0–0.1 ms 0.0–0.1 ms

Rows read, decoded and folded per push are identical, and event-json-decode stays under 0.1 ms on both, so the prefix is still reused.

Memory, kept pageable rows (e515883). Before this commit the reused rows sat in a separate per-connection map of the last 32 windows. The bound was a count, and nothing dropped a thread's windows on rewrite, compaction or memo eviction. Same measurement as above. In brackets: heap freed by dropping the kept rows once the windows instance is gone.

read set 49f4151 e515883
12 harness threads +66.5 MB (5.9) +66.5 MB (1.0)
305 threads (12 harness + 300 most recent) +108.3 MB (3.2) +108.4 MB (1.2)
the same 305, harness threads read last +128.6 MB (5.9) +112.4 MB (1.0)
318 threads, the 17 largest read last +149.1 MB (14.4) +140.3 MB (0.0)

On this branch alone the old map stayed small in the default read order, because the last 32 windows read were small threads. With the larger merged integration branch (#7250) it measured 33 MB at 305 threads.

The first version of this commit charged every pageable row. That stringified the older context rows pagination never measures, and it doubled u738kqjs29's first CLI, nested and summary reads after an app read (27 → 57 ms). Keeping only measured rows removed that cost.

Timings for e515883 vs 49f4151: harness cold, warm, variants, capacity and push. Push threads were kdrbtee92b plus u738kqjs29, wg5iwwrezi and txqr3djnmd forced active, 12 appends, 5 repeats. 4 alternating pairs, each started at load below 8 (4.3–6.3). Median of per-run medians:

case 49f4151 e515883
warm push, kdrbtee92b / txqr3djnmd / wg5iwwrezi / u738kqjs29 1.9 / 2.05 / 3.55 / 8.6 ms 1.9 / 2.1 / 3.6 / 8.15 ms
cold after append, u738kqjs29 205.8 ms (202.5–212.5) 210.8 ms (206.6–220.3)
cold app latest, sum of 12 threads 567.7 ms 570.7 ms
first variant read after app, sum of 48 782.8 ms 788.5 ms
u738kqjs29 CLI log after app 26.85 ms 27.15 ms
capacity reopen 19.3 ms 19.35 ms
warm cache hit, all 12 threads 0.0–0.1 ms 0.0–0.1 ms

Every rows-read, decoded, bytes and response-bytes metric is identical between the two.

Parity. Responses were hashed on main and on the branch over a read-only clone of the snapshot:

  • All 947 threads with ≥1,000 events, six window variants each: app latest, phone (segmentLimit 8), CLI, nested, nested+deferred, summaryOnly.
  • Up to three older pages per thread.
  • A 13-step incremental replay on 112 threads (the 12 harness threads plus 100 sampled), app and CLI params. Each step compares warm memo, fold and row-reuse builds against a cold build at the same maxSeq, and also hashes the delta from the previous step.

Result: 9,723 / 9,723 hashes identical to main, and warm equals cold at every replay step. Retained-output availability, which depends on Date.now(), was normalized before hashing. Re-run on 49f4151 with the same script on a fresh clone: 9,723 / 9,723 identical to main and to c381f52, warm equals cold at every replay step.

e515883 vs 49f4151, using the integration's parity and append-replay scripts on fresh clones:

  • 162 threads × 8 variants, older pages, turn details and outlines: 4,652 forward-order and 2,462 reverse-order hashes, all identical.
  • Append replay over 64 thread-runs: 1,024 steps and 5,120 deltas, 0 warm-vs-cold mismatches on both.

Tests added. I ran the structuredClone test against the old condition, where it fails. The others test code paths that don't exist on main, so they weren't run there.

  • thread-view/test/settled-delegation-child-rows.test.ts: omitted child rows equal deferring the full rows, including nested, childless and pending delegations.
  • thread-view/test/event-projection-fold.test.ts: fold matches cold after every event for an interrupted turn with nothing pending, and finishing does not call structuredClone.
  • thread-view/test/tool-call-parsing*.test.ts: cached results are independent objects, repeated parses are reused, and the existing linearity benchmarks now use unique commands so the cache can't mask them.
  • server/test/services/threads/timeline-selection-decode.test.ts: prefix reuse and byte count. The memo entry carries the decoded rows and a reused selection extends them. Decoded rows are dropped on history rewrite and thread forget, and when the memo evicts the entry for its data-char budget or its entry cap.
  • server/test/services/threads/timeline-selection-decode.test.ts, kept pageable rows (e515883). A build reuses no row objects after the memo forgets the thread. Kept rows count toward the memo budget, so a second thread of the same size evicts the first. Both tests fail on 49f4151, where the rebuilt rows are still the old objects.
  • server/test/services/threads/timeline-window-reuse.test.ts: unchanged rows keep identity across an append and serialize like a fresh build; reuse only happens on exact JSON equality, including key order.
  • server/test/services/threads/timeline-content-pagination.test.ts: derived byte counts equal Buffer.byteLength(JSON.stringify(rows)) for nested multibyte rows.
  • server/test/services/threads/timeline-window-sharing.test.ts: the CLI window built after the app window keeps a settled subagent's child rows. It fails without the cache-key change ([null] instead of [1]). The existing sharing test now expects a row rebuild for each new row shape (includeNestedRows × deferContent).

Commands run.

  • e515883: turbo run typecheck lint --filter=@bb/server, plus vitest on test/services/threads and test/provider-corpus (34 files, 293 tests pass, 1 skipped). All with env -u BB_ACCOUNT_POOL_PARENT_URL -u BB_SERVER_URL -u BB_CLI.
  • pnpm exec turbo run typecheck test --filter=@bb/server --filter=@bb/thread-view --filter=@bb/provider-parity
  • 49f4151: turbo run typecheck lint --filter=@bb/server, plus vitest on test/services/threads/timeline*, thread-events, conversation-outline*, test/provider-corpus, event-pruning and internal-event-append-ownership (25 files, 241 tests pass, 1 skipped)

After rebasing onto main at 226d128 (#7245, #7238, #7254, #7284): turbo run typecheck lint --filter=@bb/server, turbo run typecheck test --filter=@bb/thread-view --filter=@bb/provider-parity, and vitest on test/services/threads and test/provider-corpus (38 files, 312 tests pass, 1 skipped). Push harness, 4 threads × 12 appends, rebased branch vs main at be3ca2c: warm push −37% to −64%, identical response bytes (load average 12–38, so the exact numbers are noisy).

Refs #4674 (does not fix it)

AGENT GENERATED

🤖 Generated with Claude Code

ymichael added a commit that referenced this pull request Nov 7, 2026
S4's decoded-selection cache kept up to 4 decoded selections per thread for
64 threads per connection, bounded by count only, and nothing dropped them on
thread delete, history rewrite or idle. It retained row data the selection
memo and the stored-event decode cache had already let go: reading the 12
harness threads in 4 page shapes kept 261 MB alive in it.

The decoded rows now live on the selection memo entry whose rows they decode.
A memo hit hands the entry's decoded rows to the build as the prefix to
extend, and the build stores the extended result back on the new entry. The
decoded cache therefore has exactly the memo's bounds (16 entries, 4 idle,
16M data chars) and is forgotten wherever the memo forgets an entry: thread
delete, rewrite generation or data_version change, context-clear epoch change
and eviction. The separate per-thread map and its prefix scan are gone.

Retained heap after reading app, phone, CLI and nested windows (forced GC):

  scenario                     main     #7244 c381f52   this
  12 harness threads           +63 MB   +321 MB            +67 MB
  12 harness + 293 recent      +109 MB  +295 MB            +108 MB

Warm push after one appended event (harness push scenario, 9 alternating
pairs x 12 appends, median of per-run medians): kdrbtee92b 2.5 -> 2.4 ms,
u738kqjs29 (active) 8.8 -> 9.1 ms; the last 3 interleaved pairs were 8.8 vs
8.8 ms. Rows read, decoded and folded per push are identical. Warm cache-hit
reads stay at 0.0-0.1 ms on all 12 threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael marked this pull request as ready for review November 9, 2026 18:05
ymichael added a commit that referenced this pull request Nov 9, 2026
S4's decoded-selection cache kept up to 4 decoded selections per thread for
64 threads per connection, bounded by count only, and nothing dropped them on
thread delete, history rewrite or idle. It retained row data the selection
memo and the stored-event decode cache had already let go: reading the 12
harness threads in 4 page shapes kept 261 MB alive in it.

The decoded rows now live on the selection memo entry whose rows they decode.
A memo hit hands the entry's decoded rows to the build as the prefix to
extend, and the build stores the extended result back on the new entry. The
decoded cache therefore has exactly the memo's bounds (16 entries, 4 idle,
16M data chars) and is forgotten wherever the memo forgets an entry: thread
delete, rewrite generation or data_version change, context-clear epoch change
and eviction. The separate per-thread map and its prefix scan are gone.

Retained heap after reading app, phone, CLI and nested windows (forced GC):

  scenario                     main     #7244 c381f52   this
  12 harness threads           +63 MB   +321 MB            +67 MB
  12 harness + 293 recent      +109 MB  +295 MB            +108 MB

Warm push after one appended event (harness push scenario, 9 alternating
pairs x 12 appends, median of per-run medians): kdrbtee92b 2.5 -> 2.4 ms,
u738kqjs29 (active) 8.8 -> 9.1 ms; the last 3 interleaved pairs were 8.8 vs
8.8 ms. Rows read, decoded and folded per push are identical. Warm cache-hit
reads stay at 0.0-0.1 ms on all 12 threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/timeline-s4-hit-path-window-sized-costs-thr_jn4p352bnn branch 2 times, most recently from 1e4176d to 3a5f841 Compare November 9, 2026 18:57
ymichael and others added 4 commits November 9, 2026 11:30
A push for one new event still re-ran several whole-window passes after the
selection memo and projection fold hit. This removes the biggest of them
without changing any output byte:

- Settled delegations: with deferContent the server dropped their child rows
  after building and mapping them. thread-view now skips building them
  (omitSettledDelegationChildRows) and only checks whether any child row
  exists, so the result stays null vs [] exact.
- bb thread tell detection: parseThreadTellCommand scanned every command
  (2 MB on u738kqjs29) several times per build. Results are now cached by
  command string, bounded like the shell intent cache.
- Interrupted turns: once any turn in the window was interrupted, every fold
  finish structuredClone'd the whole projection state. It now deep-copies only
  when interrupted-turn finalization would change something (a running call
  or a pending message in that turn).
- Decode: a selection that extends the previous one reuses its decoded
  prefix and byte count instead of re-decoding every row.
- Pagination byte budget: per-leaf and per-page JSON.stringify is replaced by
  byte counts cached per row object; unchanged latest-window rows and window
  fields are reused from the previous build when they serialize identically,
  so the tag, delta and byte counts only touch rows that changed.

Warm push after one appended event, in-process harness push scenario,
4 alternating base/fix pairs x 12 appends, load avg 14-19:

  thread                base ms  fix ms
  kdrbtee92b               4.0     2.8
  u738kqjs29 (active)     15.4     9.8
  8nnix6m53a (active)      5.9     3.0
  gyi25h9awq (active)     10.6     4.7
  wg5iwwrezi (active)     10.9     4.3
  txqr3djnmd (active)      8.0     2.5
  mwktgwihcc (active)      8.1     3.2

Parity: latest, phone, CLI, nested, nested+deferred, summaryOnly and three
older pages for all 947 snapshot threads with >=1,000 events, plus a
13-step warm-vs-cold replay with deltas on 112 threads, hash identical to
main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
S4's decoded-selection cache kept up to 4 decoded selections per thread for
64 threads per connection, bounded by count only, and nothing dropped them on
thread delete, history rewrite or idle. It retained row data the selection
memo and the stored-event decode cache had already let go: reading the 12
harness threads in 4 page shapes kept 261 MB alive in it.

The decoded rows now live on the selection memo entry whose rows they decode.
A memo hit hands the entry's decoded rows to the build as the prefix to
extend, and the build stores the extended result back on the new entry. The
decoded cache therefore has exactly the memo's bounds (16 entries, 4 idle,
16M data chars) and is forgotten wherever the memo forgets an entry: thread
delete, rewrite generation or data_version change, context-clear epoch change
and eviction. The separate per-thread map and its prefix scan are gone.

Retained heap after reading app, phone, CLI and nested windows (forced GC):

  scenario                     main     #7244 c381f52   this
  12 harness threads           +63 MB   +321 MB            +67 MB
  12 harness + 293 recent      +109 MB  +295 MB            +108 MB

Warm push after one appended event (harness push scenario, 9 alternating
pairs x 12 appends, median of per-run medians): kdrbtee92b 2.5 -> 2.4 ms,
u738kqjs29 (active) 8.8 -> 9.1 ms; the last 3 interleaved pairs were 8.8 vs
8.8 ms. Rows read, decoded and folded per push are identical. Warm cache-hit
reads stay at 0.0-0.1 ms on all 12 threads.

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

The latest-window row reuse kept the pageable rows of the last 32 windows
per connection in a separate map. The bound was a count, not a size, and
the map never dropped a thread's windows on history rewrite, compaction or
memo eviction.

The kept rows now live on the selection memo entry for their selection,
one set per (deferContent, includeNestedRows) variant. Their JSON bytes
count toward the memo's 16M budget along with the selection's data chars.
They go away wherever the memo drops an entry: forget on rewrite or
compaction, context-clear epoch change and eviction. A rewritten
generation doesn't carry them over. After pagination, only rows whose JSON
size pagination already measured are kept. Those are the only rows reuse
helps, and their size costs nothing extra. Charging every pageable row
instead stringified the older context rows pagination never touches,
which doubled u738kqjs29's first CLI read after an app read
(27 -> 57 ms).

Retained heapUsed after reading app, phone, CLI and nested windows of each
thread (forced GC; kept rows = heap freed by dropping them once the
windows instance is gone):

  read set                          49f4151        this
  12 harness threads                +66.5 MB (5.9)    +66.5 MB (1.0)
  305 threads                       +108.3 MB (3.2)   +108.4 MB (1.2)
  305, harness threads read last    +128.6 MB (5.9)   +112.4 MB (1.0)
  318, 17 largest threads last      +149.1 MB (14.4)  +140.3 MB (0.0)

Responses are identical to 49f4151: 4,652 forward and 2,462
reverse-order hashes over 162 threads, and 0 warm-vs-cold mismatches over
1,024 append-replay steps. Harness timings, 4 alternating pairs, are within
1% in total, and every rows-read and bytes metric is identical.

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

The projection cache from #7245 keyed built rows by includeNestedRows only.
Deferred reads now omit settled delegation children, so a CLI read after an
app read could reuse rows with those children missing. The cache now keys
rows by both flags; this test reads the app window and then the CLI window
and checks the subagent's children survive.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/timeline-s4-hit-path-window-sized-costs-thr_jn4p352bnn branch from 3a5f841 to efe7e8a Compare November 9, 2026 19:32
@ymichael
ymichael merged commit 9c900d4 into main Nov 9, 2026
51 checks passed
@ymichael
ymichael deleted the bb/timeline-s4-hit-path-window-sized-costs-thr_jn4p352bnn branch November 9, 2026 19:45
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