Skip to content

Speed up timeline pagination queries - #1976

Merged
ymichael merged 3 commits into
mainfrom
bb/perf-pr-2-faster-timeline-pagination-queries-thr_ht7bbc3jt7
Aug 19, 2026
Merged

ymichael merged 3 commits into
mainfrom
bb/perf-pr-2-faster-timeline-pagination-queries-thr_ht7bbc3jt7

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

What was wrong

Timeline pagination paid three avoidable costs on its synchronous request path. Parent-context discovery decoded every selected event payload before normal projection decoded it again; child lookup parsed JSON across an entire thread because the parent relationship existed only inside events.data; and the byte-budget check crossed the better-sqlite3 boundary once per candidate row even when the whole window fit (the common case). Large concurrent threads therefore held the event loop longer than the rows returned by the API required.

What changed

  • Normalize parentToolCallId into events.parent_tool_call_id at the event-write boundaries and read that typed field for root-turn, nested-turn, parent-closure, and parent-crossing decisions.
  • Add generated migration 0103_wandering_mongoose: backfill the new column from both legacy JSON shapes, then add the one partial (thread_id, parent_tool_call_id, sequence) index required by the changed lookup.
  • Ask SQLite for one aggregate window byte count first. Fitting windows return one scalar; only oversized windows take the existing newest-first iterator needed to preserve the exact cutoff and single-event-placeholder rules.
  • Add migration/backfill coverage, parent-field derivation coverage, and a query-plan assertion that parented timeline lookup selects the new index.

Current main already had two adjacent optimizations: superseded workflow snapshots/out-of-window turn filtering from #1872, and events_tool_call_parent_lookup_idx for parent-crossing tool-call probes. This change preserves both; the new index serves the inverse child-by-parent lookup. Main also gained 0102_app_settings_key_value while this work was in progress, so the event migration and snapshot were regenerated as 0103 rather than retaining the source branch's colliding 0102 name. The initial string-presence guard from the first source commit is intentionally absent from the final diff because the normalized column removes that JSON decode entirely. No other performance commits from the source branch are included. There is no server/host-daemon wire change, so HOST_DAEMON_PROTOCOL_VERSION is unchanged.

Performance

Final comparison was run from exact base 35732c53922906a6f6684f684461077b685a812b to head 919e28b4cc4bb09a674f3e2d8ffc2c6bd7639f72 on an Apple M4 Max / 48 GiB Mac (Darwin 25.5.0), Node 22.23.1, SQLite 3.51.0. Both refs used forced production server builds, private loopback ports 45321/45322, and private copies of the same deterministic fixture: 12 projects, 240 threads, 480,450 events, 270.5 MiB event JSON, 582 MiB SQLite database, plus 48 deterministic cross-window parent relationships in the largest threads.

Each of five repetitions pre-read all event data to control OS-cache ordering, restarted the production server to clear response caches, warmed 19 disjoint threads (38 timeline requests), then issued distinct cold-response-cache URLs at timeline concurrency 16 while four workers continuously requested GET /api/v1/projects. Initial and older-page scenarios used 160 distinct threads; parent-context used 48. Values below are the median of the five per-run medians/p95s (raw JSON and server logs retained under /tmp/bb-pr2-perf.IeuChw).

Scenario response median response p95 throughput server CPU / batch competing projects p95
Initial page (160) 142.3 → 127.0 ms (-10.7%) 239.9 → 193.8 ms (-19.2%) 99.5 → 114.6 req/s (+15.2%) 2.15 → 1.95 s (-9.3%) 242.5 → 196.6 ms (-18.9%)
Older page (160) 130.4 → 115.6 ms (-11.3%) 179.9 → 131.0 ms (-27.2%) 115.4 → 137.5 req/s (+19.2%) 1.67 → 1.46 s (-12.6%) 179.5 → 133.2 ms (-25.8%)
Parent context (48) 166.1 → 132.9 ms (-20.0%) 184.4 → 136.5 ms (-26.0%) 95.1 → 120.7 req/s (+26.8%) 0.59 → 0.49 s (-16.9%) 187.4 → 138.8 ms (-25.9%)

Median response sizes were unchanged: 37,609 bytes initial, 36,592 bytes older, and 36,320 bytes parent-context.

Representative query evidence:

  • A fitting latest window held 276 rows / 158,900 payload bytes. Before, the byte check materialized 276 iterator rows (27,658 serialized bytes in the diagnostic capture); after, it materialized one 24-byte aggregate scalar. Both plans correctly use events_thread_sequence_idx; the gain is fewer native-boundary crossings/materialized result rows.
  • A parent-context sample had 7,747 thread rows / 4,709,745 payload bytes and returned one 111-byte child row. Before, EXPLAIN QUERY PLAN selected events_thread_sequence_idx (thread_id=?) and evaluated JSON parent expressions across the thread. After, it selects events_parent_tool_call_thread_parent_sequence_idx (thread_id=? AND parent_tool_call_id=?) and visits the one matching index entry.

Exact setup/build commands included:

pnpm seed:perf -- --data-dir /tmp/bb-pr2-perf.IeuChw/baseline-data --reset --projects 12 --threads 240 --events 480000 --seed 20260819
git switch --detach 35732c53922906a6f6684f684461077b685a812b
pnpm exec turbo run build --filter=@bb/server --filter=@bb/scripts --force
env NODE_ENV=production BB_DATA_DIR=/tmp/bb-pr2-perf.IeuChw/final-baseline-data BB_SERVER_PORT=45321 BB_HOST_DAEMON_PORT=45322 BB_SERVER_BIND_HOST=127.0.0.1 BB_TELEMETRY=false node apps/server/dist/index.js
sqlite3 /tmp/bb-pr2-perf.IeuChw/final-baseline-data/bb.db 'SELECT sum(length(CAST(data AS BLOB))) FROM events;'
node tmp-perf-pr2-run.mjs /tmp/bb-pr2-perf.IeuChw/targets.json "$server_pid"

The same commands/settings were repeated after switching to the head and changing only the private data-dir copy. Absolute values are local loopback/warm-data results; the comparison is intended to isolate CPU, materialization, and event-loop effects, not model production network latency.

How you verified

  • pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/server --force — passed.
  • pnpm exec turbo run test --filter=@bb/db --force — 29 files, 404 tests passed, including migration and query-plan coverage.
  • pnpm exec turbo run test --filter=@bb/server --force -- test/services/threads/timeline-parented-pagination.test.ts test/services/threads/timeline-event-budget.test.ts test/services/threads/timeline-workflow-progress-window.test.ts test/public/public-thread-data.test.ts — 4 files, 86 tests passed.
  • pnpm exec turbo run build --filter=@bb/server --filter=@bb/scripts --force — passed on both exact baseline and head production builds.
  • Clean migration: empty database reached all 104 migrations and contained the new column/index.
  • Upgrade migration: the pre-change 480,450-event fixture reached all 104 migrations; 48/48 parent rows were backfilled with zero JSON/column mismatches (the logged backfill took 940 ms on this machine).
  • Full @bb/server run completed 1,780/1,781 tests; the unrelated plugin compatibility warning test exceeded its 5 s timeout under full-suite load. Its isolated Turbo rerun passed all 24 tests (the timed-out case completed in 1.73 s).

AGENT GENERATED: by GPT-5

Parent-context discovery parsed every selected event payload to look for parentToolCallId, then timeline projection parsed the same payload again. Persisted event data is canonical JSON.stringify output, so rows that do not contain the exact property key cannot carry parent context. Guard the narrow parent lookup before JSON.parse; nested rows continue through the existing parsed and validated path.\n\nSeeded 402k-event DB, five cold 200-thread timeline runs at concurrency 16:\n- median throughput: 100.3 -> 106.0 req/s (+5.7%)\n- median timeline p95: 303.8 -> 288.6 ms (-5.0%)\n- median concurrent ping p95: 366.8 -> 346.5 ms (-5.5%)\n\nValidation: 81 parented-pagination, workflow-window, and public thread-data tests.
The byte-budget guard crossed the better-sqlite3 boundary once per event to sum a window that almost always fits, then the timeline query read the same rows again. Ask SQLite for one aggregate byte count first and return immediately for fitting windows. Only oversized windows pay the ordered iterator needed to identify their exact floor or single-event placeholder.\n\nSeeded 402k-event DB, five cold 200-thread timeline runs at concurrency 16:\n- median throughput: 106.0 -> 110.6 req/s (+4.4%)\n- median timeline p95: 288.6 -> 272.9 ms (-5.4%)\n- median concurrent ping p95: 346.5 -> 328.1 ms (-5.3%)\n\nValidation: @bb/db typecheck and all 393 database tests.

@bb-slop-cop bb-slop-cop Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

I am SlopCop. I am reviewing this pull request for security, code quality, performance, architecture, and end-to-end behavior.

@ymichael
ymichael merged commit b40dc05 into main Aug 19, 2026
12 checks passed
@ymichael
ymichael deleted the bb/perf-pr-2-faster-timeline-pagination-queries-thr_ht7bbc3jt7 branch August 19, 2026 23:44
NULLIF(json_extract(`data`, '$.item.parentToolCallId'), ''),
NULLIF(json_extract(`data`, '$.parentToolCallId'), '')
)
WHERE instr(`data`, '"parentToolCallId"') > 0;--> statement-breakpoint

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The migration can stop on malformed stored event JSON.

events.data can intentionally contain malformed daemon payloads. A row like {"parentToolCallId": passes instr, then json_extract raises malformed JSON. This stops the server upgrade. Add json_valid(data) to the predicate and test a malformed matching row.

// scalar instead of crossing the native boundary once per event merely to
// rediscover that no floor is needed. Oversized windows still take the
// ordered iterator below so they retain the exact cutoff/placeholder rules.
const windowDataBytes = getStoredTimelineWindowEventDataBytes(db, {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The new preflight can scan an unbounded client-selected range.

The turn-summary-details route accepts arbitrary start and end sequences. This SUM scans the complete range before the iterator. The capped fallback can run it twice. Better-sqlite3 then blocks the server event loop. Bound the aggregate by event count, or skip it for unbounded ranges.

@bb-slop-cop bb-slop-cop Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

Plain-English summary: This PR makes older timeline pages faster. It stores parent tool-call links in an indexed column. It also lets SQLite total window bytes.

I found one upgrade blocker and one additional availability risk.

  • Migration blocker: Malformed historic event JSON containing "parentToolCallId" makes migration 0103 fail with SQLite malformed JSON. The server cannot start after that failed upgrade. Add json_valid(data) to the backfill predicate. Add a migration test with a malformed matching row. Inline finding

  • Availability risk: The byte preflight scans a client-selected turn-detail range before the limited iterator. Large ranges can scan twice. The capped fallback can repeat the work. Bound this aggregate, or bypass it for an unbounded range. Inline finding

The architecture scan found three existing queries that still decode this parent relationship from JSON. They occur near events.ts lines 3247, 3446, and 3558. A later cleanup should use the normalized column and keep one relationship definition.

The new index gives real gains for parent lookups. I found no cross-thread data leak, unsafe SQL interpolation, or privilege change.

Validation:

  • I reproduced the migration failure with SQLite.
  • The focused query-plan suite passed all 18 tests.
  • GitHub CI passed all required test and package jobs.
  • git diff --check passed.
  • The full local suites hit unrelated timeouts during concurrent shared-host runs.
  • The dev launcher did not reach a running state before I stopped it. Therefore, I could not run the browser test.

Please fix the migration blocker before merge.

SawyerHood added a commit that referenced this pull request Aug 20, 2026
…1657)" (#1981)

## What was wrong

Main CI is red in `Checks` and `Tests (server)` since d9a5934 (#1657).
#1976 made `parentToolCallId` required in `InsertEventInput`; #1657 was
written before that change and merged after it, so its new test inserts
events without the field. Typecheck fails with TS2741 on six literals
and the SQLite insert fails with `near ",": syntax error`. Main runs
32314735170 and 32314935793 show it.

## What changed

Reverts d9a5934 ("Keep mid-turn user exchanges visible after a turn
completes (#1657)") with `git revert`. The revert applies cleanly on
current main. #1657 can be re-landed after a rebase that adds
`parentToolCallId` to its event inserts.

Supersedes #1980, which was a forward fix of the test only.

## How you verified

- `pnpm exec turbo run typecheck --filter=@bb/server
--filter=@bb/thread-view --filter=@bb/app` passes.
- `pnpm exec turbo run test --filter=@bb/thread-view --filter=@bb/db`
passes.
- CI on this PR.

> AGENT GENERATED: by Claude Opus 5
ymichael added a commit that referenced this pull request Aug 20, 2026
## What was wrong

The parent-tool-call backfill added in #1976 evaluated `json_extract`
for any historic event payload containing the parent key text, so
malformed stored JSON aborted migration 0103 and prevented server
startup. The byte-budget optimization from the same PR also aggregated
every matching payload in a client-selected turn-details range before
its early-stopping iterator ran, allowing a very wide range to add one
or two unbounded synchronous scans.

## What changed

- Guard migration 0103 with `json_valid(data)` so malformed historic
payloads remain unbackfilled instead of aborting the upgrade.
- Accept the original merged 0103 hash so development databases that
already applied it continue to pass migration-history validation.
- Limit the scalar byte-total preflight to 2,001 matching events, which
keeps the aggregate fast path for normal event-budgeted timeline windows
and falls back to the existing exact, early-stopping iterator for
unusually long ranges.
- Add regressions for malformed matching JSON, the historical migration
hash, and a wide byte range whose older payload must not be visited by
the aggregate.

This is a database/server implementation fix only. There is no
server/host-daemon wire change, so `HOST_DAEMON_PROTOCOL_VERSION` is
unchanged.

## How you verified

- `pnpm exec turbo run typecheck --filter=@bb/db --force`
- `pnpm exec turbo run test --filter=@bb/db --force` — 29 files, 406
tests passed
- `pnpm exec prettier --check packages/db/src/data/events.ts
packages/db/src/migration-history.ts
packages/db/test/data/events.test.ts packages/db/test/migrate.test.ts`
- `git diff --check`

Follow-up to #1976 and its [migration
finding](#1976 (comment))
and [range-scan
finding](#1976 (comment)).

> AGENT GENERATED: by GPT-5
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