Skip to content

Stop re-reading delegated children in timeline window selection - #7239

Merged
ymichael merged 2 commits into
mainfrom
bb/timeline-s1-duplicate-sql-reads-in-window-select-thr_na9gybpywj
Nov 9, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/timeline-s1-duplicate-sql-reads-in-window-select-thr_na9gybpywj

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

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 ensureTimelineWindowParentedRows to 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 ran length(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: ensureTimelineWindowParentedRows now takes a lookups object 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/db listStoredEventRowsByParentToolCallIds has a new optional excludedTurnIds argument (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.
  • listStoredTimelineTurnEventRows and listStoredEventRowsByParentToolCallIds still 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 raw sql<T> fields, so the values are the same.
  • Both hot queries now split their IDs with 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 raised too many SQL variables at around 32k IDs.
  • truncatedEventDataColumn now checks octet_length(data) <= max before length(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.

case (cold, app latest window) before ms after ms Δ SQL rows read (distinct)
u738kqjs29 222.8 (212–436) 149.2 (136–156) −33% 19,463 → 7,857 (7,665)
kdrbtee92b 36.1 (35–52) 27.7 (26–31) −23% 2,264 → 1,332 (1,299)
avim9t7kpe 129.2 (115–359) 104.2 (104–109) −19% 5,897 → 5,897 (5,890)
wg5iwwrezi 60.3 (60–139) 53.3 (50–72) −12% 3,358 → 2,653 (2,628)
d5ej4e2gtv 49.3 (37–92) 35.2 (35–36) −29%* 662 → 662
u738kqjs29 older-page walk (5 pages) 1,012 678 −33%
kdrbtee92b walk 236 193 −18%

* 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:

  • Replayed main and this branch over 159 snapshot threads: the 12 harness threads plus 147 sampled from the 947 threads with at least 1,000 events. Each thread ran the app latest window at segment limits 20 and 8, the CLI log, includeNestedRows, summaryOnly, up to 6 older app pages, up to 3 CLI pages and 2 turn-details pages. All 1,648 response SHA-256 hashes match: 0 diffs.
  • Memo path: on a separate clone, appended 4 events to each of the 12 harness threads (alternating plain items and children of a delegating call) and compared each memo-served latest window with a fresh build. 48 of 48 match.

Tests:

  • New 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: excludedTurnIds keeps null-turn and other-turn children and drops the excluded turn's children. The unmapped turn and child rows equal the Drizzle-mapped listStoredEventRows rows. 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 raised too many SQL variables before the batching commit.
  • packages/db/test/query-plans.test.ts: the child read with 300 excluded turns and the truncation column still runs SEARCH events USING INDEX events_parent_tool_call_thread_parent_sequence_idx (thread_id=? AND parent_tool_call_id=? AND sequence>? AND sequence<?) with no SCAN events.
  • After the batching commit, a parity replay of the 12 harness threads matches main on all 156 responses.
  • 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 in test/app/install-machine-script.test.ts at 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.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 2 commits November 7, 2026 11:43
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
ymichael marked this pull request as ready for review November 9, 2026 17:46
@ymichael
ymichael merged commit c361d7c into main Nov 9, 2026
33 checks passed
@ymichael
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]>
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