Skip to content

Read timeline pages without whole turns, and page long turns by sequence - #7247

Closed
ymichael wants to merge 7 commits into
mainfrom
bb/timeline-s6-sequence-based-in-turn-pagination-46-thr_pgx4x6ezq6
Closed

ymichael wants to merge 7 commits into
mainfrom
bb/timeline-s6-sequence-based-in-turn-pagination-46-thr_pgx4x6ezq6

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A timeline page read every turn it touched from the start of history, plus every turn a delegation parent of its rows lived in. This is the structural cause in #4674.

  • Leaf-index pagination and the summary rows of collapsed turns both needed the whole turn projected.
  • A window only ever started at a user message, so a long turn with no message inside it was a single page.

Example: thr_u738kqjs29's 17-row latest page read a 7,407-event turn (7,663 rows, 13.4 MB), because one background task in the window had a parent in that turn. A Codex thread's latest page read a 5,888-event finished turn to render 6 rows.

What changed

Seven commits.

  1. Windowed reads of turns whose rows render flat. This covers a running turn, or any turn under the flat display.
    • The page reads only its window. It adds the complete events of items that cross the window edges, delegation parents, children of the delegations it owns, and the turn's lifecycle, accepted-input, compaction and provider rows.
    • The latest-selection memo appends to windowed turns, and checks the store before accepting an event for an item it hasn't seen.
  2. Grid cuts inside long running turns. When no user-message start fits the event budget, the window starts on a half-budget grid.
    • The cut lands on a lifecycle event (pruning never deletes those) and moves back to the start of the item it lands in.
  3. Remove the regressions.
    • No more tail reads on older pages.
    • No grid cuts inside finished turns, or when a turn has at most one budget of events before the cut. Pages over finished history keep main's boundaries.
    • On the latest page, each touched turn's first sequence comes from one index-only query. A turn that starts within 256 sequences of the window is read whole in the same single query as the window, as main does.
    • The child-row exclusion subquery is gone.
  4. Stored per-turn plans for finished collapsed turns (thread_turn_timeline_plans, migration 0155).
    • The first time a page reads such a turn of at least 1,000 events whole, it stores the summary rows plus the id and source range of each message the turn shows ungrouped.
    • Later pages take the summary rows from the plan and read only the events of the messages they show.
    • The key follows the thread_conversation_outlines precedent: projection version, in-process rewrite generation, thread status and the display settings that change the output.
    • A plan is used only while the greatest sequence of the turn's events, its delegations' children and its open items is unchanged. A suffix rewrite deletes it, and any memo append that touches a planned turn rebuilds.
    • Nested-row reads (bb thread log --format verbose) still read the turn whole.
  5. Durable rewrite generation (thread_event_rewrite_generations, migration 0156).
    • Every rewrite (suffix delete, insert at or below the high-water mark, completed-output migration, pruning that removes rows) bumps a per-thread generation in its own transaction. The pruning bump moved inside the pruning transaction.
    • Stored turn plans and persisted conversation outlines (thread_conversation_outlines) now key on this durable value. Before, they keyed on the in-process counter, which restarts at zero. A gap-fill insert into a finished turn doesn't move the plan watermark, so after a restart the stale plan was used.
    • The in-memory generation stays the key for process-local caches.
  6. olderRowsSourceSeqEnd no longer depends on how a page read its turns. Found by the integration branch (Timeline perf integration (do not merge: verification branch for #7238 #7239 #7245 #7244 #7246 #7243 #7247 #7254 #7249 #7241 #7108 #7240 #7248 #7242 #6215) #7250).
    • Before, the page folded in the latest event of every windowed or planned turn before the window. A whole read instead reports the greatest sourceSeqEnd of rows it projected and didn't return, minus rows sent as olderRowUpdates.
    • So thr_avim9t7kpe's latest page reported 1 on a fresh database and 1925 once its plan was stored, while main reports 1. A nested read could also leave a plan-less memo entry that later app reads reused.
    • A planned turn now adds the end of each stored ungrouped message that ends before the window. Plans keep only messages that render a row.
    • A turn read only inside its window adds its latest event before the window. Context events (already read) and events whose top-level row reaches the window are skipped. A metadata-only backward scan finds it, starting with 16 events.
    • A windowed read also reads the turn-scoped start of an item whose thread-scoped completion is in the window. Without it, thr_u738kqjs29's older pages gave a delegation row a later sourceSeqEnd than main.
  7. SQLite variable limits in the new queries. They hardcoded fixed-variable counts (64, 16), and some had unbatched IN lists.
    • Every list query now batches through queryInSqliteVariableBatches on the exact fixed-variable count. Turn and item rows are read as raw rows through Stop re-reading delegated children in timeline window selection #7239's allStoredEventRowsInVariableBatches.
    • queryRawRowsInSqliteVariableBatches renders the query once with the whole list, takes the exact count from that render, and runs it directly when it fits. Only lists above the limit pay for per-batch renders. Without this, the extra empty-batch render made the context-row read cost 650 µs instead of 410 µs.

Wire shape and cursors (timeline-v3) are unchanged, so there's no version bump: every field keeps its meaning, and the projection of a window is unchanged. The app, CLI, SDK and plugins needed no changes. docs/timeline-pagination.md describes what a page reads, the grid, plans and how a partial read reports olderRowsSourceSeqEnd.

Not in this PR: turn-details paging (S7 caches it). Leaf content cursors remain for windows over 1,500 leaves or 4 MiB.

How you verified

Parity. Main and this branch read the same snapshot clone. Every page was walked and merged with prependOlderTimelineRows. Each set ran twice on the branch: once while plans were being created, and once with every plan stored.

set walks merged rows + latest-page head fields
119 threads with ≥1,000 events (every 8th) × app / CLI / nested 357 identical, both runs
104 Codex threads whose finished turns span pages × app / CLI 208 identical, both runs
12 harness threads × app / CLI / nested / phone 48 identical, both runs

Parity after commit 5 was rerun on a fresh clone with both migrations: identical on all three sets, both runs.

olderRowsSourceSeqEnd and tag parity (commits 6–7). Shared parity script, every full response hashed (rows, cursors, olderRowsSourceSeqEnd, tag). Main 55135d1 and this branch, each on its own migrated clone of the snapshot. 162 threads: 8 latest variants, older pages, repeats, turn details and outlines.

comparison hashes differences before (0106746) after
main vs branch, forward order 4,652 53 (all olderRowsSourceSeqEnd + tag) 0
main vs branch, reverse read order 2,462 71 0
branch forward vs reverse 2,462 37 (integration) 0

The 8 errors are identical on both sides: details requests for turns the route also rejects on main.

Append replay: 64 thread-runs, 1,024 steps, 5,120 deltas. Warm vs cold: 8 mismatches before (all olderRowsSourceSeqEnd), 0 after. Outline and turn-details mismatches: 0.

  • Against main's cold responses, the replay differs on 160 of 6,912. All are thr_avim9t7kpe's latest page with the last 16 events removed, which leaves its turn unfinished, so commit 2's grid starts the window at 9741 instead of 1926.
  • The head before commit 6 differs on the same 160, with identical rows and cursors.

Timing, commits 6–7 vs 0106746. Audit harness, 12 threads, 3 alternating pairs, fresh clone per run, 7 repeats per run, load 4–7. Values are the median of the per-run medians.

scenario before ms after ms change
cold latest, 12 threads summed 298.5 301.5 +1.0%
sqlcount cold latest, summed 293.0 282.9 −3.4%
variants after app, summed 543.9 540.3 −0.7%
push, 4 threads × 3 cases, summed 332.4 320.5 −3.6%
app walk, summed 3,682.6 3,741.6 +1.6%
thread log --all, summed 7,417.7 7,497.9 +1.1%
u738kqjs29 cold latest 24.2 24.4 +0.8%
avim9t7kpe cold latest 12.7 12.2 −3.9%
d5ej4e2gtv app walk 1,861.9 1,896.8 +1.9% (78,469 → 78,476 rows)

Rows read are unchanged except walks, which read the few thread-scoped-completion item starts (+7 rows on u738, +7 on d5ej). Each older page also pays one scan query. Per-call micro-benchmark on u738 (before → after): turn context rows 408 → 409 µs, first sequences 28.3 → 28.6 µs, outside counts 26.4 → 26.7 µs.

Timing (commits 1–5). Audit harness, three alternating main/branch pairs (orders base-branch, branch-base, base-branch), fresh DB clone per run, median of 3 per run, load 6–10. Values are the medians of the three runs.

case main ms branch ms rows read
u738kqjs29 latest 206 24 7,663 → 793
u738kqjs29 push, 1 new event, active 14.9 1.7 7,668 → 798
u738kqjs29 phone layout 194 16 7,663 → 793
avim9t7kpe latest (Codex) 105 14 5,888 → 40
avim9t7kpe phone layout 104 10 5,888 → 40
9h3n4aiax8 latest (Codex, sqlcount run) 18.4 13.3 925 → 399
app walk u738kqjs29 917 303 34.7k → 12.0k
app walk 6e9knccemi 938 677 56.7k → 35.4k
app walk avim9t7kpe 227 15 11.8k → 73
app walk 9h3n4aiax8 146 52 13.9k → 1.5k
app walk d5ej4e2gtv 2,029 1,907 86.5k → 78.5k
thread log --all u738kqjs29 1,668 708 57.7k → 24.8k
thread log --all 6e9knccemi 1,141 818 64.3k → 38.6k
thread log --all avim9t7kpe 211 15 11.8k → 73
kdrbtee92b push, 1 new event, active 3.4 3.2 unchanged

Small threads, measured separately because the harness runs vary ±10% at this size. These are 3 interleaved rounds of 60 fresh-connection builds per side, comparing medians.

  • Cold latest page:
    • pvd2eqmdcv 13.8 → 13.7 ms
    • i2qj9tb7j3 23.4 → 22.8 ms
    • 9h3n4aiax8 16.0 → 15.8 ms
    • kdrbtee92b 31.8 → 31.3 ms
    • ymhw6pktq4 9.93 → 10.00 ms
  • Phone layout:
    • within +0.1–0.4 ms (1–4%) of main
    • the timeline-building stage itself differs by 0.03–0.17 ms, from the one index-only first-sequence query
  • After-app CLI-log, summary-only and nested reads through windows.read, 75 samples per side: dbcv9uurw7 and pvd2eqmdcv within ±3%.

The durable-generation read is one primary-key lookup per collapsed-display build or outline load. Against the previous head (180 builds per side, both orders), the stage that contains it moves 0.05–0.06 ms on collapsed threads and not at all on flat ones.

Residual cost, and why: a nested-row read right after an app read of the same thread used to share the app's whole-turn selection. With plans, the app read no longer loads the turn, so on avim the nested read goes from 45 to 144 ms. That equals a cold nested read: 143–150 ms on main, 137–140 ms on this branch. A nested read right after a plan-creating app read still shares that selection. Reusing plan summaries for nested reads isn't cheap: a nested summary row embeds every grouped message, which is most of the turn's events.

Tests.

  • New tests, which fail when their fix is removed:
    • bounded reads of a long running flat turn
    • a delegation spanning turns
    • two compactions in one turn
    • a streaming item longer than the budget
    • plan-mode banner and model fallback when the window starts inside the turn
    • a collapsed turn read from its plan with identical rows
    • plan invalidation when the turn changes
    • plans deleted on suffix rewrite
    • restart after a rewrite: stale plan and outline ignored, output equals a fresh build (fails when keyed on the in-memory generation)
    • durable generation asserted on every bump path
    • the same latest page, read before and after its turn's plan is stored and with a nested read first, reports one olderRowsSourceSeqEnd and identical responses (before the fix: 1 whole, 604 planned)
    • a flat turn's item still running at the window start is left out of the bound, which matches the definition computed from a whole read (before the fix: 604 instead of 603)
    • turn, item, start, plan and watermark queries with 40,000-id lists (before the fix: too many SQL variables)
  • The two pinned whole-turn tests now assert bounded reads.
  • pnpm exec turbo run typecheck lint test --filter=@bb/server --filter=@bb/db --filter=@bb/thread-view passes (15/15 tasks, after commit 5).
  • After commit 7: typecheck for @bb/server, @bb/db and @bb/thread-view; @bb/db 664 and @bb/thread-view 510 tests; apps/server test/services/threads 283 tests in 30 files.

Refs #4674

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 2 commits November 7, 2026 12:49
A timeline page fetched every turn it touched from the start of history,
plus every turn its delegation parents lived in, so a 17-row latest page on
thr_u738kqjs29 read a 7,407-event turn (7,663 rows, 13.4 MB) because one
background task in the window had a parent in that turn.

A turn whose rows render flat (a running turn, or any turn under the flat
display) is now read only inside the page window. The selection adds the
complete events of items that cross the window edges, delegation parents,
children of delegations the page owns, the turn's lifecycle, accepted input,
compaction and provider rows, and on older pages the turn's events up to the
furthest event those items reach, since the projection fold depends on them.
Turns that start inside the window are still read whole with no extra
queries. Finished turns under the collapsed display are still read whole.
The latest-selection memo appends to windowed turns and checks the store
before accepting an event for an item it has not seen.
olderRowsSourceSeqEnd is at least a windowed turn's last event before the
window, so the client merge never keeps a gap.

thr_u738kqjs29 cold latest page (in-process, snapshot): 7,663 -> 779 rows
read, ~210 -> ~32 ms. Rendered rows are unchanged: merged walks over 119
snapshot threads x 3 variants and the 12 harness threads x 4 variants are
byte-identical to main.

Refs #4674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A window started at a user message, so a turn with no message inside it
was one page however long it ran: thr_kdrbtee92b's oldest page owned a
7,335-event turn.

When no message start fits the event budget, the window now starts on a
grid of half the budget at or below the budget floor, on the first
lifecycle event there (pruning never deletes those, so cursors stay
valid), moved back to the start of the item it lands in so the latest
page is never left holding only a streaming item's tail. The latest start
then moves once per half budget of appends, so the selection memo keeps
appending. The grid is skipped inside a finished collapsed turn, which is
read whole anyway. Cursors stay timeline-v3: their fields keep their
meaning, and the projection of a window is unchanged.

Harness, snapshot, two alternating A/B pairs, median of 3 per run, load
6-10:
- u738kqjs29 latest: 218 -> 24 ms, rows read 7,663 -> 772; push with one
  new event as active: 12.2 -> 1.6 ms; phone layout 188 -> 14 ms
- wg5iwwrezi latest: 53 -> 42 ms
- app walk: u738 918 -> 337 ms (34.7k -> 15.4k rows), 6e9knccemi
  958 -> 544 ms (56.7k -> 26.6k)
- thread log --all: d5ej4e2gtv 3.98 -> 3.04 s (157k -> 115k rows),
  u738 1.55 -> 0.57 s, kdrbtee92b 764 -> 466 ms, 6e9knccemi 1.07 -> 0.65 s
- costs: small-turn cold latest +0.5-1.5 ms (2-9%); app walk kdrbtee92b
  226 -> 292 ms and d5ej4e2gtv 2.04 -> 2.24 s, from the extra pages and
  the tail reads that keep older pages exact
Rows are unchanged: merged walks of 119 snapshot threads x 3 variants and
12 harness threads x 4 variants, plus latest-page head fields, are
byte-identical to main.

Refs #4674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael and others added 5 commits November 7, 2026 14:35
The previous commits made some reads slower than main:
- Older pages re-read a turn's later events up to the furthest event their
  items reached. That guarded against a projection dependency that turned
  out to be a missing background-task start, already fixed, so the tail
  read is gone. On kdrbtee92b's app walk the turn rows read fall from
  15.4k back to main's 9.4k.
- Grid cuts split finished turns into more pages, each paying fixed
  per-page costs. Grid cuts now apply only inside running turns, and only
  when the turn has more than one budget of events before the cut. Pages
  over finished history keep main's boundaries.
- A turn that started before the window paid for context, item-closure and
  count queries. On the latest page each touched turn's first sequence now
  comes from one index-only query. A turn that starts within 256 sequences
  of the window is read whole in the same single query as the window, as
  main does. On older pages a turn with at most 256 events outside the
  window is read whole.
- A child-row exclusion subquery cost about 11 ms on kdrbtee92b's CLI walk
  and has been removed.

ymhw6pktq4 cold latest, the worst small case before this change, went
from +0.35 ms to +0.07 ms in turn loading (180 fresh-connection builds per
side). Merged walks are still byte-identical to main.

Refs #4674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A page that touched a finished turn under the collapsed display (Codex's
default) read the whole turn, because its summary rows depend on every
message in it: thr_avim9t7kpe's latest page read 5,888 rows to render 6.

The first time a page reads such a turn of at least 1,000 events whole, it
stores the turn's row plan in thread_turn_timeline_plans: the summary rows,
and the id and source range of each message the turn shows ungrouped.
Later pages take the summary rows from the plan and read only the events
of the ungrouped messages they show, plus the turn's context events.

A plan is keyed by a projection version, the in-process rewrite
generation, the thread status and the display settings that change the
output, following the thread_conversation_outlines precedent. It is used
only while the greatest sequence of the turn's events, its delegations'
children and its open items is unchanged. Rewriting the history suffix
deletes a thread's plans. The latest-selection memo rebuilds on any append
that touches a planned turn. Nested-row reads (bb thread log --format
verbose) still read the turn whole.

Harness, snapshot, three alternating A/B pairs, fresh DB clone per run,
median of 3 per run, load 6-10:
- avim9t7kpe latest page 105 -> 14 ms (5,888 -> 40 rows), app walk
  227 -> 15 ms, thread log --all 211 -> 15 ms
- 9h3n4aiax8 app walk 146 -> 52 ms (13.9k -> 1.5k rows)
- the first read of a turn materializes its plan at main's cost
- nested-row reads right after an app read of the same thread no longer
  share the app's whole-turn selection: avim 45 -> 144 ms, which is
  main's own cold nested read (143-150 ms; branch 137-140 ms)
Merged walks are byte-identical to main across 357 broad-sample walks,
208 walks of 104 Codex threads whose finished turns span pages, and 48
harness walks, each with plans being created and with all plans stored.

Refs #4674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Stored per-turn plans and conversation outlines were keyed on the
in-process rewrite generation, which restarts at zero. A rewrite before a
restart could leave a stored plan or outline that still looked valid. A
gap-fill insert into a finished turn does not move the plan's watermark
(the turn's greatest sequence), so after a restart the stale plan was used
and the walk rendered the turn without the inserted message.

thread_event_rewrite_generations (migration 0156) holds a per-thread
generation. bumpThreadEventRewriteGeneration increments it in the same
transaction at every rewrite: suffix deletes, inserts at or below the
high-water mark, completed-output migrations, and pruning that removes
rows (moved inside the pruning transaction). The in-memory generation stays
the fast key for process-local caches. Turn plans and persisted outlines
key on the stored value, one primary-key read per build.

The new restart test seeds a plan and an outline, gap-fills an agent
message into the turn, reloads the server modules, and checks that the
walk and outline equal a rebuild with no stored artifacts. It fails when
the keys use the in-memory generation. The rewrite-generation DB tests now
also assert the stored value on every bump path.

Refs #4674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
timelinePage.olderRowsSourceSeqEnd depended on whether a turn's plan
was stored and on read order. The page folded in the latest event of
every windowed or planned turn before the window. A whole read of the
same turn instead reports the greatest sourceSeqEnd of the rows it
projected and did not return, leaving out rows sent as olderRowUpdates.
thr_avim9t7kpe's latest page reported 1 on a fresh database and 1925
once its plan was stored. A nested read first left a plan-less memo
entry that later app reads reused, so those reported 1 again.

The page now adds only what a whole read would have projected:
- a planned turn: the end of each stored ungrouped message that ends
  before the window. Plans keep only messages that render a row, and a
  stored message matches its projected message by id and source range.
- a turn read only inside the window: its latest event before the
  window, skipping context events (already read) and events whose
  top-level row reaches the window. A metadata-only backward scan
  finds it and usually stops after one page.

A windowed read also reads the turn-scoped start of an item whose
thread-scoped completion is in the window. Without it,
thr_u738kqjs29's older pages gave a delegation row a later
sourceSeqEnd than main.

#7247's new queries hardcoded SQL-variable counts and used Drizzle row
mapping. They now batch with queryInSqliteVariableBatches on the
query's exact fixed-variable count, and turn and item rows read raw
rows through the same helpers #7239 adds.

Snapshot parity against main 55135d1, 162 threads, every response
including olderRowsSourceSeqEnd and tag: 4,652 hashes, 0 differences.
Reverse read order: 2,462 hashes, 0 differences. Append replay: 1,024
steps, 5,120 deltas, 0 warm-vs-cold mismatches.

Refs #4674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The batched queries rendered every query twice: once with an empty
batch to count its fixed variables, then again for the batch. The
inline-output truncation column makes that render expensive, so
listStoredTimelineTurnContextRows cost 650 us against 410 us before
batching. queryRawRowsInSqliteVariableBatches now renders the query
once with the whole list, takes the exact fixed-variable count from
that render, and runs it directly when it fits. Only lists above the
SQLite limit pay for per-batch renders. The aggregate and start-lookup
queries keep their raw SQL text, rendered through SQLiteSyncDialect.

The older-row scan starts with 16 events and grows, and the thread-scope
start lookup is skipped when the page reads no turn in part.

Micro-benchmark on thr_u738kqjs29, per call against the PR head:
turn context rows 409 vs 408 us, first sequences 28.6 vs 28.3 us,
outside counts 26.7 vs 26.4 us.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael ymichael closed this Nov 9, 2026
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]>
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