Repository navigation
Stop pruning from invalidating timelines it cannot change - #7246
Merged
Merged
Conversation
ymichael
marked this pull request as ready for review
November 9, 2026 18:04
Usage and turn-diff snapshot prunes no longer advance the thread's rewrite generation or send history-compacted: timeline, outline and turn-detail reads never load those rows beyond the kept snapshots. The settled sweep now sends one history-compacted per thread pass instead of one per ten-second run, and the timeline response cache keys on the rewrite generation so reads between runs still match a fresh build. A history rewrite on one thread now forgets only that thread's grouping contexts instead of clearing them for every thread. Replay of the production pruning schedule on 5 busy snapshot threads (163 turn ends, deltas and usage rows reconstructed into pruned sequence holes, 3 alternating A/B pairs, medians): - history-compacted notices: 344 -> 121 (2.1 -> 0.74 per turn end) - rewrite-generation bumps: 275 -> 156 - served timeline build time: 133 s -> 63 s; refetch builds 44 s -> 12 s - u738kqjs29: 30 -> 9 notices, build time 78.8 s -> 32.5 s - every post-prune read equalled a fresh build in both variants Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/timeline-s3-pruning-invalidation-thr_vph67q29ek
branch
from
November 9, 2026 18:34
06e80f4 to
c4dfd23
Compare
ymichael
deleted the
bb/timeline-s3-pruning-invalidation-thr_vph67q29ek
branch
November 9, 2026 18:39
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
…fter pruning (#7284) ## Human comments ## What was wrong After #7246, pruning still sent `history-compacted` whenever 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 its `item/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/requested` row, `selectTimelineWindowStart` starts 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 with `400 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_TYPES` lists every type pruning deletes. `findUnprunableThreadEventSequence` returns the first row at or after a sequence whose type is not in that list (range scan on `events_thread_sequence_idx`). `advanceThreadPruning` no longer returns `rewroteHistory`; it still advances the rewrite generation for rate-limit, delta and background-progress prunes. - `apps/server/src/services/threads/timeline-selection-memo.ts` and `timeline.ts`: when a window has no request row to start at, `selectTimelineWindowStart` now 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.ts` and `thread-pruning-sweep.ts`: live steps and the settled sweep no longer send `history-compacted`. The sweep's per-pass notice bookkeeping from #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-compacted` keeps 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 with `Timeline 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 equal `PRUNABLE_THREAD_EVENT_TYPES`. Removing `item/reasoning/textDelta` from the list fails it. It also checks `findUnprunableThreadEventSequence` skips prunable rows. - Tests that asserted notices now assert none, and keep their other checks: served window equals a fresh build after every sweep run, earlier viewers converge on the compacted timeline, failed transactions keep earlier commits and resume. Commands: - `pnpm exec turbo run typecheck lint --filter=@bb/server --filter=@bb/db` - server `test/system`, `test/services/threads`, `public-thread-timeline-delta`, `periodic-sweeps`, `hub`: 657 passed - db `test/data`: 477 passed **Live** (`pnpm start:worktree`, Codex, a 60-command turn of 509 rows, WebSocket subscriber on `thread-detail` plus a 1 s poller on the events table): | | #7246 (main before this PR) | this PR | |---|---|---| | mid-turn prune (rate limits 29 → 1) | 1 `history-compacted` | 0 | | turn-end prune + sweep (156 rows) | 2 | 0 | After pruning, `GET /api/v1/threads/:id/timeline` returns 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. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
Every prune that removed rows advanced the thread's rewrite generation and sent
history-compacted. That threw away the server's timeline caches for the thread (response cache, selection memo, projection fold, grouping and outline state), and the app refetched the timeline and turn details, whatever kind of rows had gone. Two kinds of work were wasted:thread/tokenUsage/updated,thread/contextWindowUsage/updatedandturn/diff/updatedare excluded from every timeline, outline and turn-detail query, and the snapshots the context indicator reads are kept. These prunes still caused full rebuilds and refetches.history-compacted, so one turn end produced a burst of notices, refetches and rebuilds.Separately, any
history-rewrittenon one thread cleared the grouping-context cache for every thread.Replaying the production schedule (see below) also showed that live prunes on active threads rarely remove rows: 5 of 61–65 live calls on u738kqjs29 and kdrbtee92b. Their thread-scoped cursors crawl from sequence 0 through deltas that can't be pruned; production's kdrbtee92b deltas cursor sat at 505 of 13,030. The churn was at turn end, in the sweep.
What changed
packages/db/src/data/thread-pruning.ts:usageandturn-diffsprunes no longer bump the rewrite generation.advanceThreadPruningnow returnsrewroteHistory. Rate-limit, delta and background-progress prunes are unchanged: they can move a window's budget floor, and in the replay they changed 1–14 windows per thread, so they still invalidate.apps/server/src/services/system/thread-pruning-sweep.ts: the sweep notifies only for advances that rewrote history. It sends onehistory-compactedper (policy, thread) pass, when the pass ends, even if the pass spans several runs. A pass that fails still notifies straight away, as before.rewriteGenerationto the revision on main, so after the rebase this PR relies on it and no longer changestimeline-cache.ts.apps/server/src/services/threads/thread-timeline-windows.ts: uses the per-thread forget below instead of clearing every thread's grouping contexts.apps/server/src/services/threads/timeline-context-order.ts:history-rewrittennow forgets only that thread's grouping contexts and ordering logs.docs/events-table-pruning.md: new section on cache invalidation and notifications.No wire, CLI or SDK changes.
history-compactedkeeps its meaning; fewer of them are sent.How you verified
After rebasing onto main (78e0e28):
pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/dbpasses; the pruning, sweep, invalidation, timeline-cache and rewrite-generation test files pass (server 33, db 39). Live on astart:worktreeserver, a 60-command Codex turn (508 rows) sent nohistory-compactedfor the settled sweep's token-usage prune (61 rows); the mid-turn rate-limit prune and the turn-end delta/rate-limit prunes still notified.Replay of the production pruning schedule. Snapshot
/tmp/tl-audit-db/bb.db(Nov 7 10:48), in-process, on a fresh APFS clone per run. It covers the 5 busiest threads of the 27 h log window: kdrbtee92b, u738kqjs29, dwzy4aij2h, y6xhxw8t8w and pvd2eqmdcv.The snapshot is already fully pruned: a first replay over 76 threads found nothing left to remove. So the replay rebuilds what production deleted:
The replay then re-appends each thread's rows in sequence order and runs the real code paths:
pruneThreadEventHistoryBestEfforton prod's live schedule: ≥30 s and ≥250 sequences while active.turn/completed.threadPruningSweepruns after each turn end.Reads follow production: a push every 20 rows, plus a desktop and phone refetch after every
history-compacted. After every prune, the next served read (desktop and phone) is compared byte for byte with a build on a separate connection whose caches were cleared.3 alternating A/B pairs (A = main, B = this branch), medians, load average 15–67 throughout because other benchmarks shared the machine:
history-compactednotices (163 turn ends)y6xhxw8t8w and pvd2eqmdcv show no clear change in build time (ranges overlap under load). B folds about 6% more events in total. All of the extra folding is phone-window reads made by the replay's own parity check: B checks quiet prunes at the next push, and the replay only pushes the desktop window. That inflates B, not production.
A broader B-only parity replay (7-day window, 24 more threads with ≥1,000 events, including i2qj9tb7j3, fq6umiby2y and wg5iwwrezi) replayed 140,872 rows and 980 turn ends. All 1,031 post-prune reads equalled a fresh build. The other harness threads (avim9t7kpe, 6e9knccemi, d5ej4e2gtv, 9h3n4aiax8, dbcv9uurw7, ymhw6pktq4) had no events in that window, so the replay can't cover them.
Harness
pushscenario (tl-audit.test.ts, u738kqjs29 active and kdrbtee92b): rows, bytes and folded counts are identical. Wall time stays within noise:Tests. Each new test fails on main:
apps/server/test/system/thread-pruning-invalidation.test.ts:history-rewrittenon one thread keeps another thread's grouping context.packages/db/test/data/event-rewrite-generation.test.ts:apps/server/test/system/thread-pruning-sweep.test.ts:Commands:
pnpm exec turbo run typecheck lint --filter=@bb/db --filter=@bb/serverpnpm exec turbo run test --filter=@bb/db --filter=@bb/server(db 664 passed; server 3,944 passed, 1 skipped)Not verified:
🤖 Generated with Claude Code