Skip to content

Stop pruning from invalidating timelines it cannot change - #7246

Merged
ymichael merged 1 commit into
mainfrom
bb/timeline-s3-pruning-invalidation-thr_vph67q29ek
Nov 9, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/timeline-s3-pruning-invalidation-thr_vph67q29ek

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • Usage and turn-diff snapshot prunes changed nothing the timeline reads. thread/tokenUsage/updated, thread/contextWindowUsage/updated and turn/diff/updated are 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.
  • The settled sweep notified once per 10 s run, not once per thread. After a turn ends, the sweep works through the thread over several runs (50 ms / 64 advances each), across four policies. Each run that removed rows sent its own history-compacted, so one turn end produced a burst of notices, refetches and rebuilds.

Separately, any history-rewritten on 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: usage and turn-diffs prunes no longer bump the rewrite generation. advanceThreadPruning now returns rewroteHistory. 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 one history-compacted per (policy, thread) pass, when the pass ends, even if the pass spans several runs. A pass that fails still notifies straight away, as before.
  • The response-cache revision must include the rewrite generation: the client notice can now come later, so the server has to see the rewrite itself, or a read between sweep runs serves the pre-prune window. Share timeline window builds across page shapes and key caches correctly #7245 already added rewriteGeneration to the revision on main, so after the rebase this PR relies on it and no longer changes timeline-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-rewritten now 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-compacted keeps 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/db passes; the pruning, sweep, invalidation, timeline-cache and rewrite-generation test files pass (server 33, db 39). Live on a start:worktree server, a 60-command Codex turn (508 rows) sent no history-compacted for 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:

  • In the 27 h window, 74k rows created were later pruned, against 88.5k survivors. They show up as sequence holes.
  • Holes inside a completed reasoning, agentMessage or command item become that item's deltas, splitting the item's real final text.
  • Holes outside items become usage snapshots.

The replay then re-appends each thread's rows in sequence order and runs the real code paths:

  • pruneThreadEventHistoryBestEffort on prod's live schedule: ≥30 s and ≥250 sequences while active.
  • The idle prune at each root turn/completed.
  • The real threadPruningSweep runs 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:

A (main) B (this PR)
history-compacted notices (163 turn ends) 344 [349, 344, 326] 121 [121, 129, 121]
notices per turn end 2.1 0.74
rewrite-generation bumps 275 156
served timeline build time, total 133 s [133, 160, 62] 63 s [68, 60, 63]
refetch build time after notices 44 s 12 s
u738kqjs29 notices / build time 30 / 78.8 s 9 / 32.5 s
kdrbtee92b notices / build time 44 / 20.9 s 15 / 13.4 s
dwzy4aij2h notices / build time 126 / 12.6 s 51 / 4.9 s
post-prune reads ≠ fresh build 0 of 275 0 of 239

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 push scenario (tl-audit.test.ts, u738kqjs29 active and kdrbtee92b): rows, bytes and folded counts are identical. Wall time stays within noise:

  • 5 low-load pairs with 40 appends each: u738 warm push median A 9.2–12.8 ms vs B 10.1–13.8 ms.
  • Bisecting the diff into its parts put every variant in the same 10.6–13.1 ms band; A itself measured 12.8 ms once.

Tests. Each new test fails on main:

  • apps/server/test/system/thread-pruning-invalidation.test.ts:
    • Live usage and turn-diff prunes on an active thread keep the served window (same object) and send no notice.
    • A sweep pass split over runs (one advance per run) sends exactly one notice, in its final run. The served window equals a fresh build after every run, and the window does grow (it gains turn 1). With the generation removed from the revision (now on main via Share timeline window builds across page shapes and key caches correctly #7245), this test fails.
    • A history-rewritten on one thread keeps another thread's grouping context.
  • packages/db/test/data/event-rewrite-generation.test.ts:
    • Usage and turn-diff prunes keep the generation.
    • A rate-limit prune advances it. It replaces the old "usage prune advances it" case, which pinned the behavior this PR changes.
  • apps/server/test/system/thread-pruning-sweep.test.ts:
    • The notification tests now use rate-limit rows, since turn diffs no longer notify.
    • New case: a settled turn-diff sweep is silent.

Commands:

  • pnpm exec turbo run typecheck lint --filter=@bb/db --filter=@bb/server
  • pnpm exec turbo run test --filter=@bb/db --filter=@bb/server (db 664 passed; server 3,944 passed, 1 skipped)

Not verified:

  • No live server or app. The app-side refetch count is inferred from the notice count; the app's debounced handler was not exercised.
  • The replay reconstructs pruned rows. Their types are inferred from position: about 79% fall inside text items, the rest are treated as usage. Real turn-diff rows aren't represented.

AGENT GENERATED

🤖 Generated with Claude Code

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
ymichael force-pushed the bb/timeline-s3-pruning-invalidation-thr_vph67q29ek branch from 06e80f4 to c4dfd23 Compare November 9, 2026 18:34
@ymichael
ymichael merged commit 9e3c153 into main Nov 9, 2026
52 checks passed
@ymichael
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]>
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