Repository navigation
Conversation
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.
| NULLIF(json_extract(`data`, '$.item.parentToolCallId'), ''), | ||
| NULLIF(json_extract(`data`, '$.parentToolCallId'), '') | ||
| ) | ||
| WHERE instr(`data`, '"parentToolCallId"') > 0;--> statement-breakpoint |
There was a problem hiding this comment.
🚨 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, { |
There was a problem hiding this comment.
🚨 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.
There was a problem hiding this comment.
🚨 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 SQLitemalformed JSON. The server cannot start after that failed upgrade. Addjson_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 --checkpassed.- 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.
…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
## 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
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
parentToolCallIdintoevents.parent_tool_call_idat the event-write boundaries and read that typed field for root-turn, nested-turn, parent-closure, and parent-crossing decisions.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.Current main already had two adjacent optimizations: superseded workflow snapshots/out-of-window turn filtering from #1872, and
events_tool_call_parent_lookup_idxfor parent-crossing tool-call probes. This change preserves both; the new index serves the inverse child-by-parent lookup. Main also gained0102_app_settings_key_valuewhile this work was in progress, so the event migration and snapshot were regenerated as0103rather than retaining the source branch's colliding0102name. 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, soHOST_DAEMON_PROTOCOL_VERSIONis unchanged.Performance
Final comparison was run from exact base
35732c53922906a6f6684f684461077b685a812bto head919e28b4cc4bb09a674f3e2d8ffc2c6bd7639f72on an Apple M4 Max / 48 GiB Mac (Darwin 25.5.0), Node22.23.1, SQLite3.51.0. Both refs used forced production server builds, private loopback ports45321/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).Median response sizes were unchanged: 37,609 bytes initial, 36,592 bytes older, and 36,320 bytes parent-context.
Representative query evidence:
events_thread_sequence_idx; the gain is fewer native-boundary crossings/materialized result rows.EXPLAIN QUERY PLANselectedevents_thread_sequence_idx (thread_id=?)and evaluated JSON parent expressions across the thread. After, it selectsevents_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:
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.@bb/serverrun 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).