Repository navigation
Stop pruning from making apps refetch, and keep older cursors valid after pruning - #7284
Merged
Merged
Conversation
…s pruning keeps Pruning only deletes rows the timeline never displays: usage, turn-diff and rate-limit snapshots beyond the kept ones, deltas of completed items, and superseded background-task progress. A viewer's loaded timeline is still correct afterwards, so live steps and the settled sweep no longer send history-compacted. The rewrite generation still advances for prunes that can move a window's budget floor, so every server-side timeline cache rebuilds on its next read. The notice also covered one failure: a window whose range has no client/turn/requested row starts at its event-budget floor, which could be a rate-limit row or a delta. Pruning that row made the window's older cursor fail with "Timeline pagination cursor is no longer available". Such a window now starts at the first row at or after the floor whose type pruning never deletes (PRUNABLE_THREAD_EVENT_TYPES), so a cursor a client holds survives pruning. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
…get (#7254) ## 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. - **Every resolved-items pass started at sequence 0.** The thread-scoped `deltas` and `background` cursors 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. - **Batches were bounded by row count, not time.** The sweep processed up to 500 rows per advance and the live path up to 32. Production logged 146 "Slow thread pruning advance" records in 27 h (`~/.bb/logs/server.21*.log`): - resolved-items advances: median 113–181 ms, worst 639 ms, typically about 470 rows scanned against 80 removed; - usage deletes of 218–500 rows: median 156 ms, worst 589 ms. - **The usage delete re-read the context-window boundary on every call.** That query has no index and parses JSON over the thread's context-window rows. ## What changed All changes are in `packages/db/src/data`. **Resting cursors** (`resolved-item-pruning.ts`) - When a pass finishes, its cursor stays at the pass's upper bound (version 2 rows) instead of being deleted. - The next pass starts at that bound. 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. Those rows can only arrive above the old bound. - Everything else below the bound was already pruned or can never be: the first delta of an item, or a delta without a turn or item. - `rewindResolvedItemPruning` moves the bound back on `deleteThreadEventSuffixInTransaction` and on `insertEvents` backfills 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. - I checked the only event-data rewrite, completed-output migration. It keeps `aggregatedOutput` a string, so it can't make an unprunable delta prunable. - A pass's upper bound is now the thread's latest event minus one. The latest-event delete guard therefore can't skip a discarded candidate that a resumed pass would never revisit. **Time-bounded advances** - Each advance works for about 20 ms (`THREAD_PRUNING_ADVANCE_WORK_BUDGET_MS`). The first candidate or chunk always runs, so every advance makes progress. - Resolved-items candidates are fetched in pages of 64 and deleted in chunks of 16. - Usage, turn-diff and rate-limit batches go in 16-row chunks with the same deadline (`thread-pruning.ts`). - The batch caps (500 sweep, 32 live) and the per-candidate probe budget are unchanged. **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.md` documents 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. - Rows pruned in production were reconstructed from sequence holes. Inside text items they became deltas, splitting the item's real final text; outside items they became usage snapshots. - The rows were re-appended in order, and the real code ran on prod's schedule: live steps (≥30 s and ≥250 sequences), idle prunes at turn end, and settled sweep runs. At the end, the sweep was repeated until a full visit removed nothing. - Each run used a fresh APFS clone. The replay ran in-process with the snapshot at `/tmp/tl-audit-db/bb.db`. - I ran 3 alternating A/B pairs per mode; the table shows medians. Load average was about 8–21. "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. | | main | this PR | |---|---|---| | rows scanned (6 threads) | 891,011 | 43,004 | | rows removed | 22,550 | 22,550 | | advances | 3,805 | 2,098 | | total pruning time | 9.45 s | 2.71 s | | median advance | 3.1 ms | 0.57 ms | | with delete cost: advances > 50 ms | 158 [158, 156, 159] | 2 [2, 1, 12] | | with delete cost: max advance | 314 ms [332, 314, 312] | 68 ms [68, 60, 197] | | with delete cost: p99 advance | 124 ms | 37 ms | | with delete cost: total pruning time | 28.4 s | 23.7 s | Per thread, rows scanned to remove the same rows: | thread | main | this PR | |---|---|---| | gtbhvapit2 | 168,155 | 10,092 | | dwzy4aij2h | 295,692 | 8,867 | | y6xhxw8t8w | 164,380 | 7,067 | | kdrbtee92b | 69,577 | 5,779 | | u738kqjs29 | 60,647 | 7,734 | | pvd2eqmdcv | 15,808 | 3,465 | **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 -b` throttling. 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`: - **Resume:** a second pass scans only the 3 new deltas. Fails on main, which rescans from sequence 0. - **Time budget:** with a mocked clock, an advance stops at its budget, and the pass removes exactly the rows an unbudgeted pass removes. Fails on main. - **Late completion:** deltas a finished pass already went past are pruned once their item's completion arrives. - **Suffix delete:** rows that reuse sequence numbers after a suffix delete are scanned again. - **Randomized equivalence, 8 seeds:** random histories of deltas, completions with and without output, background progress and completion, suffix deletes, and live and sweep advances. Each history runs against this PR and against a reference that discards finished cursors, which is main's rescan-from-zero behavior. Both must keep identical rows after every drain. The last three guard the new logic, so they pass on main as well. I checked that they catch it being wrong: - removing the rewind fails the suffix test and all 8 seeds; - removing the reach-back fails the late-completion test and all 8 seeds. Existing tests changed: - One db test treated "cursor row deleted" as "pass finished"; it now checks for a cursor at rest. - One sweep test counted all cursor rows; it now counts the global ones, since resting per-thread cursors persist until the thread is archived or deleted. - One test calls `advanceLiveEventPruning` directly and now passes a deadline. **Production DB check after rebasing onto `be3ca2cc37`; the commit was later rebased onto `03971c75b6` (#7284) with only a docs conflict** (a `VACUUM INTO` copy of the live `~/.bb/bb.db`, Nov 9; the real `advanceThreadPruning` on the live path, two resolved-items passes back to back with nothing new arriving in between): | thread | main: pass 2 scanned | this PR: pass 2 scanned | this PR: pass 1 max advance | |---|---|---|---| | cdfq9maj8q | 62,944 | 0 | 8.9 ms | | 59j74ttj6b | 32,068 | 0 | 4.7 ms | | gtbhvapit2 | 25,152 | 0 | 32.4 ms | | 9h3n4aiax8 | 21,322 | 0 | 5.2 ms | 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/server` - `pnpm 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), plus `test/system/thread-pruning-invalidation.test.ts` (4 passed) - CI runs the full suites. **Notices.** Since #7284, pruning sends no `history-compacted` notices. 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:** - No live server. The 50 ms bound was measured under an emulated delete cost, not real cold pages or preemption. Wall time per advance can still exceed the budget when the process is descheduled mid-statement. - The background-progress probe still pages through all later progress rows of the thread (its query has no item filter). It's correct, but slow on threads with many concurrent tasks. I left it unchanged. - Each thread with a pruned pass now keeps up to two small cursor rows. > 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 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 17, 2026
…long running turns into budget-sized pages A timeline page read every turn it touched from the start of history. thr_u738kqjs29's 17-row latest page read a 7,407-event turn (7,662 rows, 13.4 MB) because a background task in the window had a parent in that turn, and a long running turn with no user message inside it was a single page however long it ran (#4674). A turn whose rows render flat (a running turn, or any turn under the flat display) that has more than 256 events outside the window is now read only inside the window, plus the complete events of items that cross the window edges (including items still open at the window start), delegation parents, children of delegations the page owns, and the turn's lifecycle, accepted-input, compaction and provider rows. Finished turns under the collapsed display, and turns with at most 256 events outside the window, are still read whole in one query. When no request row fits the event budget inside a running turn, the window starts on a half-budget grid, moved back to the start of the item it lands in. The cut is always a request, turn or item lifecycle row, which pruning never deletes, so held older cursors stay valid after #7284's pruning. timelinePage.olderRowsSourceSeqEnd stays the value a whole read of the turn would report: the page adds the windowed turn's latest event before the window whose row does not reach into it, following only parents that nest their children (a background task a command launched is not nested in the command row). Batched queries render once and run directly when they fit under the SQLite variable limit. This carries the flat-turn half of #7247 onto current main, without its stored turn plans or durable rewrite generation, and adds no schema change. Refs #4674 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
After #7246, pruning still sent
history-compactedwhenever it deleted rate-limit snapshots, deltas or background-task progress. Each notice makes every open app refetch the thread's timeline and turn details. That happened mid-turn on long turns and once or twice after every turn end. The refetch doesn't change what's on screen: pruning only deletes rows the timeline never displays. A completed item renders from itsitem/completed, not its deltas, and usage, turn-diff and rate-limit state come from the kept snapshots. The only effect is that a fresh window can reach further back, because the deleted rows counted toward the 1,500-row event budget.The notice also hid one real failure. When a window's range has no
client/turn/requestedrow,selectTimelineWindowStartstarts it at the event-budget floor, which can be any counted row, including a rate-limit row or a delta. The window's older cursor anchors on that row. Once pruning deleted it, "load older" failed with400 Timeline pagination cursor is no longer available(timeline.ts,isTimelineCursorSequencePresent). The notice made the app reload and pick up a fresh cursor before that could happen.What changed
packages/db/src/data/thread-pruning.ts:PRUNABLE_THREAD_EVENT_TYPESlists every type pruning deletes.findUnprunableThreadEventSequencereturns the first row at or after a sequence whose type is not in that list (range scan onevents_thread_sequence_idx).advanceThreadPruningno longer returnsrewroteHistory; it still advances the rewrite generation for rate-limit, delta and background-progress prunes.apps/server/src/services/threads/timeline-selection-memo.tsandtimeline.ts: when a window has no request row to start at,selectTimelineWindowStartnow starts it at the first unprunable row at or after the budget floor, falling back to the floor itself. Request rows and the epoch start were already unprunable. So pruning can't invalidate an older cursor a client holds.apps/server/src/services/system/event-pruning.tsandthread-pruning-sweep.ts: live steps and the settled sweep no longer sendhistory-compacted. The sweep's per-pass notice bookkeeping from Stop pruning from invalidating timelines it cannot change #7246 is gone. Server-side timeline caches (response cache revision, selection memo, projection folds, grouping contexts, outline) are keyed by the rewrite generation, so they rebuild on the next read without the notice. Viewers of an active thread still get the compacted rows on their next push.docs/events-table-pruning.md: "Cache invalidation and cursors" replaces the notification section.history-compactedkeeps its meaning; completed-output migration and retained-output expiry still send it, because those change displayed output. No wire, CLI or SDK changes.How you verified
Tests
thread-pruning-invalidation.test.ts, new: keeps a window's older cursor usable after pruning deletes the rows around it. A turn with no request row whose budget floor lands on a rate-limit row. The sweep prunes rate limits, then the older page is read with the cursor from before the prune. On main it fails withTimeline pagination cursor is no longer available; here it returns the older rows, and no notice is sent.packages/db/test/data/thread-pruning.test.ts, new: deletes exactly the event types listed as prunable. Seeds every prunable kind plus the item lifecycle rows around them, drains every policy and requires the set of deleted types to equalPRUNABLE_THREAD_EVENT_TYPES. Removingitem/reasoning/textDeltafrom the list fails it. It also checksfindUnprunableThreadEventSequenceskips prunable rows.Commands:
pnpm exec turbo run typecheck lint --filter=@bb/server --filter=@bb/dbtest/system,test/services/threads,public-thread-timeline-delta,periodic-sweeps,hub: 657 passedtest/data: 477 passedLive (
pnpm start:worktree, Codex, a 60-command turn of 509 rows, WebSocket subscriber onthread-detailplus a 1 s poller on the events table):history-compactedAfter pruning,
GET /api/v1/threads/:id/timelinereturns the full turn, including the final "done".Not verified: the app was not driven in a browser; the refetch reduction is inferred from the notice count.
🤖 Generated with Claude Code