Repository navigation
Resume resolved-item pruning passes and bound each advance to its budget - #7254
Merged
Merged
Conversation
ymichael
marked this pull request as ready for review
November 9, 2026 18:15
ymichael
force-pushed
the
bb/pruning-throughput-thr_vph67q29ek
branch
from
November 9, 2026 18:43
8d99d26 to
92137f6
Compare
The deltas and background-progress cursors used to be deleted at the end of every pass, so the next live step or sweep visit rescanned the thread from sequence 0 and re-probed every surviving first delta. A pass now rests at its upper bound and the next one starts there. It reaches back only to the earliest candidate of an item that gained a completion (deltas) or newer progress or completion (background tasks) since the last pass. Suffix deletes and inserts at or below the high-water mark move the bound back before that sequence. Each pass bound excludes the thread's latest event, so the latest-event guard can no longer leave a discarded candidate behind. Each advance now works for about 20 ms. Candidates are fetched in pages of 64, deletes run in chunks of 16, and usage, turn-diff and rate-limit batches are processed in 16-row chunks with the same deadline. The context-window keeper boundary is computed once per advance instead of once per delete. Replay of the production pruning schedule on 6 snapshot threads (deltas and usage reconstructed into pruned sequence holes, 3 alternating A/B pairs, medians, full drain at the end): - rows scanned: 891k -> 43k for the same 22,550 rows removed - pruning time: 9.4 s -> 2.7 s - with an emulated 0.8 ms per-row delete cost (prod's logged rate): advances over 50 ms 158 -> 2, max 314 -> 68 ms, p99 124 -> 37 ms - surviving rows identical to main after the drain in all 36 thread runs Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/pruning-throughput-thr_vph67q29ek
branch
from
November 9, 2026 19:06
92137f6 to
a21eefe
Compare
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
## 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 #7245.** #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 (#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](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
## Human comments ## What was wrong #7254 capped each pruning advance at a 20 ms wall-clock budget (`THREAD_PRUNING_ADVANCE_WORK_BUDGET_MS`). Several tests still assert how much a single advance removes, and they ran against the real clock. When a runner is slow, the budget runs out after fewer 16-row chunks and the counts come up short. The Windows host packages job has failed on main this way since `bf09c7c5af`: - `thread-pruning.test.ts` › "preserves the current latest row when resuming after truncation": `expected 304 to be 500` (`bf09c7c5af`), `496` (`60f81b3476`), `256` (`11175a0d52`), and `272`, then `128` on #7287's run and its re-run. - `query-plans.test.ts` › "does not parse agentMessage/reasoning completion payloads for retention support" (`60f81b3476`). ## What changed These tests now freeze `performance.now`, so the budget never expires and each advance does its full batch: - `packages/db/test/data/thread-pruning.test.ts`: the whole describe block. - `packages/db/test/query-plans.test.ts`: the three tests that advance resolved-item pruning. - `apps/server/test/system/thread-pruning-sweep.test.ts`: the whole describe block. The two elapsed-budget tests still install their own clocks over it. - `apps/server/test/services/threads/timeline-selection-memo.test.ts`: only inside `advanceSettledThreadPruning`. - `apps/server/test/system/event-pruning.test.ts` and `thread-pruning-invalidation.test.ts`: only in the one test in each that counts live-advance removals. Spies are restored in `afterEach` (or `finally`). `resolved-item-pruning-resume.test.ts` still covers the budget itself with its own fake clock. No production code changes. ## How you verified - **Reproduced the failure locally.** I set `THREAD_PRUNING_ADVANCE_WORK_BUDGET_MS` to 1 ms to stand in for a slow runner. On main this fails the CI test exactly (`expected 16 to be 500`), and 13 tests fail in total: - db: 3 in `thread-pruning.test.ts` and 3 in `query-plans.test.ts`. - server: 4 in `thread-pruning-sweep.test.ts`, 1 in `timeline-selection-memo.test.ts`, 1 in `event-pruning.test.ts` and 1 in `thread-pruning-invalidation.test.ts`. - **At 1 ms with this change:** all of these pass. Across the db and server suites, the only remaining 1 ms failure is `resolved-item-pruning-resume.test.ts` › "stops an advance at its time budget…", which is designed around the real 20 ms value and uses its own fake clock. - **At the real 20 ms budget:** `@bb/db` 700/700 passed (`turbo run test --filter=@bb/db`), and the five server pruning test files 56/56 passed. - `turbo run typecheck --filter=@bb/db --filter=@bb/server` passed. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
3 tasks done
3 tasks done
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
Pruning work grew with the thread, not with what it could prune, and single batches could block the event loop for hundreds of milliseconds.
deltasandbackgroundcursors were deleted when a pass finished, so the next pass (a live step or a settled-sweep visit) re-probed every surviving delta. Most surviving deltas are the first delta of their item, which is never pruned: 19,642 of 19,721 on cdfq9maj8q, and all 10,032 on 59j74ttj6b. The sweep revisits a thread after every turn, so long threads paid a full re-probe each time. Production's kdrbtee92b deltas cursor sat at 505 of 13,030.~/.bb/logs/server.21*.log):What changed
All changes are in
packages/db/src/data.Resting cursors (
resolved-item-pruning.ts)rewindResolvedItemPruningmoves the bound back ondeleteThreadEventSuffixInTransactionand oninsertEventsbackfills at or below the high-water mark (events.ts). Those are the only ways a row can appear at or below the bound; every other insert path allocates above it.aggregatedOutputa string, so it can't make an unprunable delta prunable.Time-bounded advances
THREAD_PRUNING_ADVANCE_WORK_BUDGET_MS). The first candidate or chunk always runs, so every advance makes progress.thread-pruning.ts).Boundary once per advance: the context-window keeper boundary is now computed once per advance and passed in as a keeper (
events.ts).Docs:
docs/events-table-pruning.mddocuments pass bounds, resumption and the time slices.No schema, wire, CLI or SDK changes. Existing version-1 live cursors are replaced on their next advance, which costs one full pass per thread.
How you verified
Replay of the production pruning schedule on 6 snapshot threads: gtbhvapit2 (the top thread in prod's slow-advance log), kdrbtee92b, u738kqjs29, dwzy4aij2h, y6xhxw8t8w and pvd2eqmdcv.
/tmp/tl-audit-db/bb.db."Delete cost" adds 0.8 ms per deleted row through a temporary trigger. That is production's logged rate (218–500 rows in 156–589 ms). Local deletes are much faster, so without it no advance reaches 50 ms in either version.
Per thread, rows scanned to remove the same rows:
Same rows pruned. After the drain, each thread's surviving event ids are identical to main in all 36 thread runs (6 threads × 3 pairs × 2 modes). The replay's timeline check also held: every post-prune read, and the final read, equalled a fresh build.
Remaining slow advances with delete cost. They are the deadline plus one 16-row delete chunk (13 ms at 0.8 ms/row) plus fixed per-advance work. The B3 outlier run (12 over 50 ms, max 197 ms) did the same work as the other runs and coincided with load spikes. I also tried
taskpolicy -bthrottling. It descheduled whole statements for hundreds of ms in both versions, so I don't use it as evidence.Tests. New file
packages/db/test/data/resolved-item-pruning-resume.test.ts:The last three guard the new logic, so they pass on main as well. I checked that they catch it being wrong:
Existing tests changed:
advanceLiveEventPruningdirectly and now passes a deadline.Production DB check after rebasing onto
be3ca2cc37; the commit was later rebased onto03971c75b6(#7284) with only a docs conflict (aVACUUM INTOcopy of the live~/.bb/bb.db, Nov 9; the realadvanceThreadPruningon the live path, two resolved-items passes back to back with nothing new arriving in between):On main, the second pass deletes nothing yet rescans every candidate. The surviving event ids on all four threads hash identically on main and on this branch.
Commands:
pnpm exec turbo run typecheck lint --filter=@bb/db --filter=@bb/serverpnpm exec turbo run test --filter=@bb/db -- test/data/resolved-item-pruning-resume.test.ts test/data/thread-pruning.test.ts test/data/events.test.ts(146 passed, including "deletes exactly the event types listed as prunable")pnpm exec turbo run test --filter=@bb/server -- test/system/thread-pruning-sweep.test.ts test/system/event-pruning.test.ts test/services/threads/timeline-cache.test.ts(30 passed), plustest/system/thread-pruning-invalidation.test.ts(4 passed)Notices. Since #7284, pruning sends no
history-compactednotices. Resumed passes make turn-end live steps remove rows they used to skip, and that no longer triggers refetches. Two notice-batching commits that this PR used to carry were dropped in favor of #7284.Not verified:
🤖 Generated with Claude Code