Skip to content

Skip superseded workflow snapshots and out-of-window turn rows in timeline pages - #1872

Merged
SawyerHood merged 2 commits into
mainfrom
bb/fix-build-expo-thread-bug-thr_dimqh92e2n
Aug 19, 2026
Merged

SawyerHood merged 2 commits into
mainfrom
bb/fix-build-expo-thread-bug-thr_dimqh92e2n

Conversation

@SawyerHood

Copy link
Copy Markdown
Collaborator

What was wrong

A thread whose finished turn started a long-running Workflow stacked the same Worked for 7m 19s row six or seven times above Working… and paged in through "Loading older messages…" (#1868, report: https://get-bb.github.io/reports/issues/1868.html). Two causes combine. (1) Every item/backgroundTask/progress row carries the full workflow snapshot (~250 KB with 206 agents). Only the newest snapshot per task is load-bearing and pruneBackgroundTaskProgressEvents deletes the rest, but only every 250 sequences / 30 s, so between prunes 100+ snapshots (25 MB+) sat above the 4 MiB THREAD_TIMELINE_EVENT_DATA_BYTE_LIMIT and the thread was cut into byte pages that held nothing but superseded snapshots. (2) The snapshots name the Workflow tool call in the finished spawning turn as parentToolCallId; on each byte page, parent closure pulled that tool call in, turn lifecycle closure added the turn's turn/started/turn/completed, byte-window mode clears contextOnlyToolCallIds, and buildSequencePageTimelineRows returned the resulting turn row verbatim (its range lies entirely below the window, so the clamp did not apply) under a page-unique :sequence-page:<anchor> id. The client keeps one row per id, so every page added another Worked for.

What changed

  • packages/db/src/data/events.ts: a shared predicate isNotSupersededBackgroundTaskProgress (same rule as the pruner: a progress row with a later progress or completed row for the same item) is applied to the timeline reads that decide and materialize a window: storedTimelineWindowConditions (byte floor, byte count, window rows), findTimelineWindowBudgetFloorSequence, listRecentStoredEventRows (full read), and storedEventRowsByParentToolCallIdsConditions (parent-child closure). The subquery uses the existing partial index events_background_task_thread_type_item_sequence_idx (covering).
  • apps/server/src/services/threads/timeline.ts buildSequencePageTimelineRows: on byte pages, a finished-turn row whose source range does not intersect the window is dropped instead of emitted verbatim; the page that holds the turn's own events renders its summary.
  • No wire changes; no CLI/doc changes.

How you verified

  • New apps/server/test/services/threads/timeline-workflow-progress-window.test.ts (3 tests): the spawning turn's summary appears once across pages; byte pages of a large later turn do not emit it; superseded snapshots do not spend the byte budget (hasOlderRows: false, one page). Each half fails on main without its fix (4 turn rows / 2 turn rows / hasOlderRows true).
  • New db test in packages/db/test/data/events.test.ts: window read, full read, byte floor and byte count agree and keep only the newest snapshot per task while keeping the completed row and other items.
  • pnpm exec turbo run test --filter=@bb/db --filter=@bb/server: db 391/391; server 1732/1733 — the one failure is test/internal/internal-skill-trees.test.ts, which also fails on the pristine tree (known local file-mode failure). pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/server clean.
  • Manual: imported thr_7wvd28jzpj (with 125 synthesized 262 KB snapshots, 33 MB) into a dev instance. Before: latest page = 1 phantom turn row + 7 byte pages; after: one page, 7 rows, the two real Worked for segments, workflow banner intact; the timeline read shrinks from 259 rows / 33 MB to 135 rows / 475 KB. EXPLAIN QUERY PLAN shows the covering partial index for the correlated subquery.

Fixes #1868

AGENT GENERATED: by Claude Opus 5

…eline pages

A running Workflow streams item/backgroundTask/progress rows that each carry
the full workflow snapshot (~250 KB with 200 agents). Between prunes a
hundred of them exceed the 4 MiB timeline byte budget, so the thread was cut
into byte pages of nothing but superseded snapshots. Each such page pulled
the Workflow tool call from the finished spawning turn in as parent context,
completed that turn around it, and buildSequencePageTimelineRows emitted the
out-of-window turn row verbatim under a page-unique id — one phantom
"Worked for" row per page.

- packages/db: timeline reads (byte floor, window rows, full read,
  parent-child closure) skip progress rows that a later progress/completed
  row for the same item supersedes; only the newest snapshot is load-bearing.
- apps/server: byte pages drop finished-turn rows whose source range does not
  intersect the window; the page that holds the turn's events renders it.

Fixes #1868

Co-Authored-By: Claude <[email protected]>

@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 the SlopCop. I started the review for PR #1872.

I will check security, code quality, architecture, performance, tests, and the user-visible timeline behavior.

Comment thread packages/db/src/data/events.ts Outdated
inArray(eventParentToolCallId, parentToolCallIds),
inArray(itemParentToolCallId, parentToolCallIds),
)!,
isNotSupersededBackgroundTaskProgress,

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 — Parent closure still parses each old snapshot before this check rejects it.

SQLite runs both json_extract operations before the indexed state check. The byte-count query and row query repeat this work.

A 250-snapshot test took 44.77 ms for two warm reads. Please filter by indexed metadata before the JSON parent tests.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Addressed in 2dc5437: the predicate now precedes the two json_extract parent terms in storedEventRowsByParentToolCallIdsConditions, so superseded snapshots are rejected by a type comparison / indexed probe before any payload is parsed. The event-count floor now has a binding-budget assertion at both the db and server level.

* snapshots between prunes cannot spend the page byte budget on rows that
* project to nothing.
*/
const isNotSupersededBackgroundTaskProgress = sql`NOT (

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 — This filter does not cover the conversation outline.

The outline query still loads and decodes every old workflow snapshot. A 250-snapshot test loaded 71.58 MiB and took 403.61 ms.

Wide layouts request the outline after the first timeline page. Please apply this filter to the structural outline query and add a large-snapshot test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Addressed in 2dc5437: the structural branch of listStoredConversationOutlineEventRows now carries the same predicate, so the outline reads only the newest snapshot per task. packages/db/test/data/events.test.ts asserts the outline rows, and query-plans.test.ts asserts the branch stays on the thread/type/item-kind index with the snapshot check probing the background-task partial index (no SCAN).

@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 removes old workflow snapshots from timeline pages. It also stops finished-turn summaries from repeating across pages.

I found two blocking performance problems.

  1. The conversation outline still loads every old workflow snapshot. A 250-snapshot test loaded 71.58 MiB and took 403.61 ms. The standard timeline loaded 0.29 MiB and took 10.59 ms. Wide layouts request the outline after the first timeline page.
  2. Parent closure parses both JSON parent paths before it rejects old snapshots. The byte-count query and row query repeat this work. A 250-snapshot test took 44.77 ms for two warm reads.

Please apply the shared snapshot filter to the structural outline query. Please also filter parent-closure rows by indexed metadata before JSON extraction.

The event-count floor also needs a direct regression test. The new server tests use a budget that never binds.

The security review found no defect. Thread isolation, event validation, transactions, and the partial index all work correctly.

CI passed every check. The database suite passed 392 tests. The new server file passed three tests. An isolated rerun passed all 44 tests that timed out under parallel load.

I also tested the dev app with 45 large workflow snapshots. The page showed one “Worked for” row and one active workflow banner.

I think the two performance items block the merge. I used a comment-only review, as requested.

… parent checks

SlopCop review on #1872: the conversation outline's structural branch still
read every workflow snapshot, and parent closure ran both json_extract parent
tests before the cheap snapshot check. Apply the shared predicate to the
outline branch and order it ahead of the JSON terms. Add binding event-count
floor and outline assertions; the outline query-plan test captures the full
statement instead of the truncated slow-query log.

Co-Authored-By: Claude <[email protected]>
@SawyerHood
SawyerHood merged commit fa9a15b into main Aug 19, 2026
12 checks passed
@SawyerHood
SawyerHood deleted the bb/fix-build-expo-thread-bug-thr_dimqh92e2n branch August 19, 2026 20:08
ymichael added a commit that referenced this pull request Aug 19, 2026
## 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:

```sh
pnpm seed:perf -- --data-dir /tmp/bb-pr2-perf.IeuChw/baseline-data --reset --projects 12 --threads 240 --events 480000 --seed 20260819
git switch --detach 35732c5
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
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.

Timeline stacks one "Worked for" row per byte page while a large Workflow streams progress snapshots

1 participant