Repository navigation
Bound thread timeline cost within long-running turns - #891
Merged
Merged
Conversation
Follow-up to #882, which bounded a timeline window by event count. Profiling that residual against a real 148,031-event database found the remaining cost was not where the follow-up expected, so this fixes what the measurements actually showed. **A running turn larger than the budget is now cut at the budget.** #882 kept a minimum of one whole turn, so an agent working through a 3,900-event turn re-read and re-projected all of it on every update — and the page reported no older rows, so nothing could shrink it. Such a window now starts at the budget floor, mid-turn, and pages backwards from a cursor that names the cut (`<threadId>:in-turn:<seq>`) instead of a user message. Only while the turn is unfinished: a finished turn collapses into one summary row that two pages cannot each own, so it is still rendered whole. An in-turn cut can land between an item's start and its completion, which would project two rows under one id with one stuck "pending". A window now takes whole items: it drops items a newer window will show and backfills the earlier lifecycle rows of the ones it keeps. **`listLatestOpenBackgroundTaskStateRowsForThread` was quadratic.** Two correlated subqueries re-scanned the thread once per candidate row: 154 ms of a 219 ms build on a 9,012-event thread with 2,640 background-task rows. Rewritten as set membership. Verified row-identical on all 257 threads. **`turn/diff/updated` is excluded from timeline windows.** It carries a full workspace diff, projects into nothing, and was 11.3 MB of one thread's 11.7 MB window read. **Oversized inline outputs are truncated during the read**, in SQLite, rather than after projection. Byte-identical output verified across all 148,031 events. **An older page no longer reads one segment past its cursor.** It ended at the next anchor *after* the cursor and trimmed that segment off after projecting it — 5,513 events against a budget of 1,500 on one thread. **A steer sent with nothing running is a segment anchor.** The SQL predicate disagreed with the projection, so a page could hand back a cursor the next request rejected as stale, stranding all older history on that thread. Measured on a production database (257 threads, 148,031 events): | Thread | Before | After | |---|---|---| | `thr_zqfgksiw39` (9,012 events) | 222 ms | 70 ms | | `thr_2dcydebhkn` (11.7 MB window) | 66 ms | 15 ms | | `thr_f3ndpkf6iz` | 55 ms | 38 ms | | `thr_62bp724ett` (10,207 events) | 34 ms | 20 ms | | `thr_u8agadfekn`, turn running | 77 ms / 519 rows / 1.73 MB | 48 ms / 262 rows / 873 KB | Correctness: walking every page of every thread returns byte-identical rows to an unbudgeted build, on all 257 threads. The one known divergence is documented in `resolveTimelineWindowBounds`: a turn that compacts context twice on opposite sides of a cut emits its (turn-keyed) compaction banner from both pages. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The workflow banner is thread-scoped state resolved by a lookup that ignores the window, so it survives a cut that leaves the task's own rows behind — but nothing asserted that, and the only real database available has exactly one thread with an open background task, so the equivalence sweep was comparing empty against empty on 256 of 257 threads. Verified to fail when `ensureLatestTimelineOpenBackgroundTaskStateRows` is removed from the latest-page path. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A GPT-5.6-Sol review of the previous two commits rejected them. Most of it held up under checking; this fixes what did. **Item ownership across an in-turn cut was decided from two event types.** An item goes on emitting between its start and its end — output deltas, reasoning text, tool progress — and an unfinished item has no end to find, so reading only `item/started`/`item/completed` made a window believe an item ended where it did not and let two pages project the same row id from different halves. Ownership now comes from the item's full event span (`listItemEventSpansByItemIds`, metadata only). This also fixes the case where a completion lands between the latest fetch and a later older fetch, which previously dropped the item from both loaded pages. **A finished turn's latest window cannot be spliced onto in-flight rows.** While a turn runs, its window starts at the budget floor with no user message above it; the moment it finishes it collapses into one summary row spanning the whole turn, so the next latest response starts *before* everything the client holds. `mergeLatestTimelineRows` spliced them and rendered the prompt after the work it produced. The controller now checks contiguity and rebuilds from the fresh response when the windows cannot be joined — which also closes a gap where a turn advancing more than a budget between refreshes left history no response contained and no cursor could reach. This changes behaviour that `useThreadTimelinePages.test.ts` asserted deliberately: a latest window that advances past the loaded rows with a hole between them no longer keeps both and appends. That test is updated, because the hole it preserved was unreachable by scrolling. **Deleting `splitFutureSteerAcceptedContextRows` narrowed accepted-row coverage.** Its replacement searched from the newest row in the window, and the window carries rows backfilled from past its own upper bound — an in-window background task's latest state, a tool call's children — so the floor could sit above the accepted row being looked for. It now searches from the request. **The unfinished-turn gate asked the wrong question.** "Did any turn finish at or after the floor" identifies no turn: a turn can finish and be followed by more than a budget of thread-scoped traffic, leaving the floor in a region owned by no turn, and an unrelated completion could veto a safe cut. `findUnfinishedTurnCoveringSequence` names the turn or refuses. **SQLite and JavaScript disagree about string length.** SQLite counts code points, JavaScript counts UTF-16 code units, so 32,000 emoji arrive as 64,000 units and were truncated a second time with a character count measured against an already-truncated string. The row-level pass now recognises the marker and leaves such a value alone. `length` also stops at an embedded NUL, which costs the saving on those payloads and nothing else; both limits are documented. **A cursor is no longer refused because the anchor predicate changed its mind.** The predicate is SQL and the projection is not, and they can still disagree — a steer accepted into a turn other than the one it named is a user message to the projection and not an anchor here. Refusing that cursor stranded every older page behind it, which is the bug the previous commit set out to fix. A cursor whose sequence still exists is now honoured; in-turn cursors, which name no stored row, are checked for that existence too. Verified unchanged: full-page replay is byte-identical to an unbudgeted build on all 257 threads, read-boundary truncation is byte-identical across 148,031 events, and the streaming case still costs 52 ms against 77 ms before. Not fixed, documented instead: a turn that compacts context twice on opposite sides of a cut emits its turn-keyed banner from both pages. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
SawyerHood
added a commit
that referenced
this pull request
Jul 30, 2026
## What changed - preserve the last assistant or error message for each human-boundary segment of a completed provider turn - keep that terminal message visible between the collapsed work summary and the following user steer - add regression coverage for accepted in-turn steers and external human new-turn boundaries ## Why Completed-turn grouping only preserved the globally final assistant message for a provider turn. When a human steer split a long provider turn into multiple visible exchanges, the preceding segment's last agent message remained inside the collapsed work summary and disappeared from the conversation flow. This restores the intended visible order: 1. user message 2. collapsed work summary 3. last agent message 4. next user message History tracing shows this behavior was introduced by `a0c5475ab` (June 23, "Split completed turn summaries at user boundaries"), not by the July timeline pagination optimizations. ## Cross-version DOM audit Three isolated builds were run against identical thread-only databases: - pre-optimization: `ec8b31a1e`, the parent of PR #882 - post-optimization/pre-fix: `afe167761`, containing PRs #882, #891, and #894 - this PR: `1f389914d` The corpus contains 19 selected threads and 45,418 events, spanning 10 to 10,207 events and including Codex/Claude threads, parent/child threads, giant completed turns, and multi-page histories. The databases contain no hosts, environments, project sources, daemon sessions, app settings, or Connect configuration. After loading every older page, canonicalized top-level timeline row DOM was exact for all 19/19 threads between the pre-optimization and post-optimization builds. Canonicalization removed only transient inline transition measurements and generated Radix IDs; row order, IDs, structure, classes, attributes, and rendered text remained strict. This PR changed 11/19 sampled threads by restoring 102 assistant rows at human boundaries. No conversation row was removed. Two now-empty collapsed summary rows disappeared because their only content became the visible assistant row; the remaining in-place text changes were collapsed-duration labels recalculated without the extracted terminal message. ## Validation - full `@bb/thread-view` test suite: 345 tests passed - `pnpm exec turbo run typecheck --filter=@bb/thread-view` - rendered the originally reported production thread from an isolated thread-only import and confirmed the corrected DOM order in the browser - cross-version DOM audit described above: 19/19 optimization comparisons exact - `git diff --check`
SawyerHood
added a commit
that referenced
this pull request
Jul 30, 2026
## The problem Since #891 bounded timeline cost within long-running turns, the tops of long streaming assistant messages were clipped — the message rendered starting mid-sentence, and the cut point kept advancing as the stream grew (observed live in a real thread whose final message streamed ~28KB across ~5,700 events in one turn). #894 added a guard meant to carry a still-streaming message's below-the-cut deltas into the owning window, but the guard keyed off `row.itemKind` on the in-window rows. The only in-window rows for a message that began below the budget floor are delta rows, and delta rows are always persisted with `item_kind = NULL` (`deriveStoredEventItemFieldsFromSource`). The guard therefore never fired in production: verified against a live database where all 9,242 `item/agentMessage/delta` rows have a NULL kind. ## The fix `ensureInTurnWindowWholeItemRows` now reads the item kind from the backfilled `item/started` lifecycle row instead of from in-window rows. The lifecycle backfill is fetched first, and the completed-item check covers backfilled rows too, so an item that completed below the cut is never treated as still streaming. ## Why CI was green The #894 regression test seeded delta rows with `itemKind: "agentMessage"` through raw `insertEvents` — a row shape the production write path can never produce. The test now seeds deltas with `itemKind: null`, and fails against the previous server code. The parented-toolCall `itemKind === "toolCall"` checks elsewhere in `timeline.ts` were audited and left alone: they run after whole-item backfill has merged in lifecycle rows, so the kind is available there. ## Testing - `pnpm exec turbo run test --filter=@bb/server -- --run` on all 7 timeline suites (33 tests pass) - rewritten regression test confirmed to fail against pre-fix `timeline.ts` - `pnpm exec turbo run typecheck --filter=@bb/server` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 5 <[email protected]>
amadad
pushed a commit
to amadad/bb
that referenced
this pull request
Aug 14, 2026
…#913) ## The problem Since get-bb#891 bounded timeline cost within long-running turns, the tops of long streaming assistant messages were clipped — the message rendered starting mid-sentence, and the cut point kept advancing as the stream grew (observed live in a real thread whose final message streamed ~28KB across ~5,700 events in one turn). get-bb#894 added a guard meant to carry a still-streaming message's below-the-cut deltas into the owning window, but the guard keyed off `row.itemKind` on the in-window rows. The only in-window rows for a message that began below the budget floor are delta rows, and delta rows are always persisted with `item_kind = NULL` (`deriveStoredEventItemFieldsFromSource`). The guard therefore never fired in production: verified against a live database where all 9,242 `item/agentMessage/delta` rows have a NULL kind. ## The fix `ensureInTurnWindowWholeItemRows` now reads the item kind from the backfilled `item/started` lifecycle row instead of from in-window rows. The lifecycle backfill is fetched first, and the completed-item check covers backfilled rows too, so an item that completed below the cut is never treated as still streaming. ## Why CI was green The get-bb#894 regression test seeded delta rows with `itemKind: "agentMessage"` through raw `insertEvents` — a row shape the production write path can never produce. The test now seeds deltas with `itemKind: null`, and fails against the previous server code. The parented-toolCall `itemKind === "toolCall"` checks elsewhere in `timeline.ts` were audited and left alone: they run after whole-item backfill has merged in lifecycle rows, so the kind is available there. ## Testing - `pnpm exec turbo run test --filter=@bb/server -- --run` on all 7 timeline suites (33 tests pass) - rewritten regression test confirmed to fail against pre-fix `timeline.ts` - `pnpm exec turbo run typecheck --filter=@bb/server` 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 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.
Summary
Measurements
On the sampled active long turn:
The delegation crossing guard measured 1.953 ms median and uses
events_thread_sequence_idxon both sides of the existence query.A real-data page walk covered 257 threads and 148,031 events with zero paginated/unpaginated row-equivalence failures.
Validation
pnpm exec turbo run typecheck— 54/54 tasks passed@bb/db— 355/355 tests passed@bb/thread-view— 344/344 tests passed@bb/app— all 2,133 collected tests passed; one unchanged automations recipe suite did not collect becausereact/jsx-dev-runtimecould not resolve@bb/server— 1,319 tests passed; one unchanged skill-tree test failed because the environment produced mode 0664 instead of expected 0644Risk and follow-up
Finished oversized turns and delegated aggregates that cross the candidate cut deliberately remain whole. Browser profiling also found a separate full-DOM scrolling bottleneck after enough pages accumulate; that is tracked independently as BB-79.
No server/daemon wire contract changed, so
HOST_DAEMON_PROTOCOL_VERSIONis unchanged.