Repository navigation
Conversation
The group-context loop called ensureTimelineWindowParentedRows once per iteration, and each call re-queried the children of every delegating item in the window, including children already loaded with their turn. On thr_u738kqjs29 the latest window read 19,463 rows for 7,665 distinct rows. - Keep the set of tool calls whose children (and missing parents) were already fetched across loop iterations. - Exclude turns the turn query already loaded from the child-row query (new excludedTurnIds argument; the trimmed memo source applies the same filter). - Return the turn and child rows straight from the SQLite statement with aliased columns instead of Drizzle's per-row mapping. - Check octet_length before the character-counting length() in the inline-output truncation column, so rows that are small in bytes skip a full UTF-8 scan. Cold latest window, median of 3 alternating A/B harness pairs on the Nov 7 snapshot (load avg 11-40, shared machine): - u738kqjs29: 222.8 -> 149.2 ms, rows read 19,463 -> 7,857 - kdrbtee92b: 36.1 -> 27.7 ms, rows read 2,264 -> 1,332 - avim9t7kpe: 129.2 -> 104.2 ms - wg5iwwrezi: 60.3 -> 53.3 ms, rows read 3,358 -> 2,653 - u738kqjs29 older-page walk: 1,012 -> 678 ms Responses are byte-identical across 1,648 replayed reads on 159 snapshot threads, and memo-path windows after appends match fresh builds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
listStoredEventRowsByParentToolCallIds bound every parent tool call id plus the excluded turn ids in one unbatched statement, and listStoredTimelineTurnEventRows assumed 32 fixed variables although the inline-output truncation column binds more than that. Both now split their ids with queryInSqliteVariableBatches, counting the fixed variables from the statement built with an empty batch. Tests cover 40,000 parent ids with 500 excluded turns and 33,002 turn ids (both raised "too many SQL variables" before), and assert that the parented read with excluded turns still searches events_parent_tool_call_thread_parent_sequence_idx without a scan. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 8, 2026
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]>
ymichael
marked this pull request as ready for review
November 9, 2026 17:46
ymichael
deleted the
bb/timeline-s1-duplicate-sql-reads-in-window-select-thr_na9gybpywj
branch
November 9, 2026 17:50
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
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. 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]>
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
When the timeline picked rows for a window, it ran a loop: fetch the rows of the turns it had found so far, then call
ensureTimelineWindowParentedRowsto pull in the children of every delegating tool call. Each call started with an empty "already fetched" set. So every pass of the loop queried the children of every tool call in the window again, even though most of those children belong to the same turn and the turn query had already loaded them. The function then dropped the duplicates. On thr_u738kqjs29 the latest window read 19,463 rows to end up with 7,665 distinct rows. The child query took about 68 ms of a 210 ms cold build. On top of that, Drizzle mapped every row of the big turn and child queries one at a time, and the inline-output truncation column ranlength(data)on every row.length()counts UTF-8 characters, so it scans the whole payload.Found in the Nov 7 timeline performance audit (REPORT #2), slice S1.
What changed
apps/server/src/services/threads/timeline.ts:ensureTimelineWindowParentedRowsnow takes alookupsobject that the group-context loop creates once per selection. It records which tool calls have already had their children fetched and which missing parents have already been looked up, so no pass fetches them again. Turn details pass fresh lookups, so their behaviour doesn't change.packages/dblistStoredEventRowsByParentToolCallIdshas a new optionalexcludedTurnIdsargument (turn_id IS NULL OR turn_id NOT IN (...)). The selection passes in the turns it has already loaded, and those turns' children aren't read a second time. The memo's trimmed row source applies the same filter.listStoredTimelineTurnEventRowsandlistStoredEventRowsByParentToolCallIdsstill build their SQL with Drizzle, but now select aliased columns and return the better-sqlite3 rows directly, skipping Drizzle's per-row mapping. They already selected rawsql<T>fields, so the values are the same.queryInSqliteVariableBatches, taking the fixed-variable count from the statement built with an empty batch. Before, the child query bound every parent ID plus the excluded turns in one statement, and the turn query assumed 32 fixed variables even though the truncation column binds more than that. Both raisedtoo many SQL variablesat around 32k IDs.truncatedEventDataColumnnow checksoctet_length(data) <= maxbeforelength(data) <= max. A string's byte length is never smaller than its character count, so the output doesn't change. Most rows now skip the character count.No wire, CLI or plugin changes.
How you verified
Measured with the audit harness on an APFS clone of the Nov 7 production snapshot. Each number is the median of 3 alternating A/B runs (main 55135d1, then this branch), each run itself a median of 3. Load average was 11–40 because other slices were benchmarking on the same machine. The first A run (load 40) was the noisiest, so the ranges are shown.
* d5ej's baseline is noisy. Its cleanest A run was 36.7 ms, so treat it as roughly unchanged.
Every other harness thread is 3–16% faster on cold builds and walks. avim gains less because it has no duplicate reads; its saving comes from skipping row mapping and the character count, and most of its remaining time is JSON decode and projection.
Parity:
Tests:
apps/server/test/services/threads/timeline-parented-row-reads.test.ts: a delegated call with children in its own turn and in a child turn. The child query runs once and returns only the child-turn rows, and both outputs render. It fails on main.packages/db/test/data/events.test.ts:excludedTurnIdskeeps null-turn and other-turn children and drops the excluded turn's children. The unmapped turn and child rows equal the Drizzle-mappedlistStoredEventRowsrows. Multibyte payloads that are over the cap in bytes but not in characters come back untouched, and overflows are cut by characters.packages/db/test/data/events.test.ts: 40,000 parent IDs with 500 excluded turns, and 33,002 turn IDs, both read correctly. Both raisedtoo many SQL variablesbefore the batching commit.packages/db/test/query-plans.test.ts: the child read with 300 excluded turns and the truncation column still runsSEARCH events USING INDEX events_parent_tool_call_thread_parent_sequence_idx (thread_id=? AND parent_tool_call_id=? AND sequence>? AND sequence<?)with noSCAN events.pnpm exec turbo run typecheck test --filter=@bb/db --filter=@bb/server: db 666 passed; server 3,940 passed, 1 skipped. The one failure was a timeout intest/app/install-machine-script.test.tsat load average 64–70, which passed in the earlier run and in CI.Not covered: the remaining small duplicates (tens of rows per thread, from the context-type and background-task-state queries, plus children of a child turn that the turn query later reads again), and the SQL-side truncation work on rows that really are over the cap.
🤖 Generated with Claude Code