Skip to content

Bound timeline windows by event count - #882

Merged
SawyerHood merged 1 commit into
mainfrom
bb/does-thread-length-slow-responses-thr_ic34feaiqp
Jul 28, 2026
Merged

SawyerHood merged 1 commit into
mainfrom
bb/does-thread-length-slow-responses-thr_ic34feaiqp

Conversation

@SawyerHood

Copy link
Copy Markdown
Collaborator

The problem

A thread-timeline window was bounded only by segment count, where a segment is a user message. That is a weak bound on work, because an agentic turn can be thousands of events.

The motivating thread has exactly 21 qualifying anchors, and the 21st sits at sequence 1 — so "load the last 20 turns" resolved to "load the entire thread", 10,198 events, on every timeline request. Windowing was running and bounding nothing.

That projection is synchronous, so its duration is the server's event loop blocked outright. The host daemon awaits POST /internal/session/events before every dynamic tool call (app.ts:565) and before registering every interactive request (app.ts:298) — so one long thread being viewed slowed agent work on every thread on the host.

Measured on a production build against a real database:

Condition Mean Max
/internal/session/events, idle 0.9 ms 1.1 ms
…while a 10,211-event thread rebuilds 368 ms 553 ms
…same load, with this change 17 ms 25 ms

The change

A window is now additionally capped at BB_FF_TIMELINE_WINDOW_EVENT_BUDGET events (default 1500) and returns however many whole turns fit. Profiling showed cost splits roughly 44 / 33 / 20 across projection, SQLite read, and JSON decode — so an event budget bounds all three at once, which is why this beat the originally-planned incremental projection for far less code.

Thread Events Before After
thr_62bp724ett 10,211 668 ms 25 ms
thr_f9jfidwbx8 6,163 243 ms 35 ms
thr_wb9c2q8gm4 4,228 103 ms 50 ms
thr_vqr8neq7pi 394 13 ms 14 ms (output identical)

Also included:

  • Older rows load automatically on scroll, reusing the existing scroll anchor. Verified: 11,662 px prepended, the row being read stayed at exactly the same viewport Y. Auto-load stays off where no bottom-anchor context exists, and latches off after a failure so a broken page isn't refetched in a loop.
  • The client's trailing refetch is paced to the observed build duration. It was self-clocking with no floor, so streaming pinned the loop at ~100 % duty cycle.
  • Event-loop stalls and slow builds now log at info. Both existed at debug, and production runs at info — so neither had ever fired. The build log is throttled per thread (with a suppressedSinceLastLog count) because the condition is sustained, not incidental.

Correctness

The risky part is that hasOlderRows is normally inferred by over-reading one sentinel segment past the page, which a budget can't afford. It's now passed explicitly from the anchor list. Getting that wrong makes older history silently unreachable rather than erroring — so a test walks every page and asserts budgeted and unbudgeted reach an identical set of user messages.

Head-state banners are resolved thread-scoped rather than by scanning the window. pendingTodos and goal were extracted from whatever the window happened to contain — which an unbudgeted window always satisfied on the threads this targets, but a budgeted window can start after the turn that set them, silently dropping the banner mid-session. Background tasks (and therefore the workflow banner, since local workflows are background-task items) already had this net; modelFallback resets on every client/turn/requested and the newest anchor is always in the window; contextWindowUsage has its own query.

Why a feature flag and not an experiment

This started as a runtime experiment, but a toggleable budget turned out to be its own bug source: the timeline delta matches a client's afterSequence against the server's last snapshot, and that sequence is identical under both budgets — so toggling could answer a client holding one window with a "nothing changed" delta computed against the other. A process-constant budget removes that failure mode instead of guarding against it.

The budget is an operator escape hatch resolved once at server start. Raising it far above the default restores the previous behavior without a second code path.

Known limits

  • The budget bounds event count, not bytes. A thread with large events (thr_zqfgksiw39: 1,279 events, still ~218 ms) improves ~1.5×, not 26×.
  • A single turn larger than the budget is unbounded — a turn can't be split without breaking projection. thr_u8agadfekn (one 2,844-event turn) is unchanged. Since the streaming case is an active turn, this is why the client-side pacing matters rather than being optional.
  • 1500 is a first guess from cost-per-event, not from how far people actually scroll back. The new logs are how we'll tune it.
  • Deferred: the daemon-side flush on the tool-call path. It needs a HOST_DAEMON_PROTOCOL_VERSION bump, wouldn't reach older enrolled daemons, and is much less urgent now the loop isn't saturated.

Verification

  • Typecheck 54/54. @bb/server 1268/1269, @bb/app 2110/2110, @bb/db 346, @bb/domain 120, @bb/cli 367, @bb/config 48. Lint 0 errors.
  • The one server failure (internal-skill-trees) reproduces on unmodified origin/main in a clean worktree — pre-existing, unrelated.
  • QA ran against a production bundle on an isolated data dir seeded from a real database (248 threads, 142,419 events), exercising UI, CLI, API, and DB. Dev-mode numbers were measured first and discarded as too noisy.
  • Verified on a fresh install that no trace of the removed experiment remains and BB_FF_TIMELINE_WINDOW_EVENT_BUDGET is honoured end to end.

🤖 Generated with Claude Code

A thread timeline window is bounded by segment (user-message) count, which
is a weak bound on work: an agentic turn can be thousands of events, so a
thread with 21 user messages and 21k events reprojects its entire history on
every request. The projection is synchronous, so that time is the server's
event loop blocked outright — which also delays /internal/session/events, the
endpoint the host daemon awaits before every dynamic tool call and before
registering every interactive request. One long thread therefore slows agent
work on every thread on the host.

Measured on a production build against a 10,211-event thread: 668ms per
build, and the daemon-facing endpoint degrading from 0.9ms idle to 368ms
mean / 553ms max while that thread is being viewed. Segment windowing was
engaging and bounding nothing: the thread has exactly 21 qualifying anchors
and the 21st sits at sequence 1.

Cap a window at BB_FF_TIMELINE_WINDOW_EVENT_BUDGET events (default 1500) on
top of the segment limit, returning however many whole turns fit. Cost splits ~44/33/20 across projection, SQLite read, and
JSON decode, so an event budget bounds all three at once. Same thread: 25ms
per build, and 17ms mean on the daemon endpoint under the same load. Threads
under the budget are byte-identical.

hasOlderRows is normally inferred by over-reading one sentinel segment past
the page, which a budget cannot afford, so paginateTimelineRows now takes it
explicitly from the anchor list. Getting this wrong makes older history
silently unreachable rather than erroring, so a test walks every page and
asserts budgeted and unbudgeted reach an identical set of user messages.

A turn larger than the whole budget is still rendered in full, since a turn
cannot be split — the budget bounds long threads, not a single long turn.

The budget is an operator escape hatch resolved once at server start, not a
product setting: raising it far above the default restores the previous
behavior without a second code path. It deliberately started as a runtime
experiment, but a toggleable budget turned out to be its own bug source — the
timeline delta matches a client's `afterSequence` against the server's last
snapshot, and that sequence is identical under both budgets, so toggling could
answer a client holding one window with a "nothing changed" delta computed
against the other. A process-constant budget removes that failure mode rather
than guarding against it.

Head-state banners are resolved thread-scoped rather than by scanning the
window. `pendingTodos` and `goal` were extracted from whatever the window
happened to contain, which an unbudgeted window always satisfied on the
threads this targets — a budgeted window can start after the turn that set
them, silently dropping the banner mid-session. Background tasks (and so the
workflow banner, since local workflows are background-task items) already had
this net; `modelFallback` resets on every client/turn/requested and the newest
anchor is always in the window; `contextWindowUsage` has its own query. Those
two were the remaining gaps.

Also:
- Load older rows automatically as the sentinel nears the viewport, reusing
  the existing scroll anchor so the reading position holds. Auto-load stays
  off without a bottom-anchor context, and latches off after a failure so a
  broken page is not refetched in a loop.
- Pace the client's trailing refetch to the observed build duration. It was
  self-clocking with no floor, so streaming pinned the loop at ~100% duty.
- Log event-loop stalls and slow timeline builds at info; both were
  unreachable in production, where the log level is info. The build log is
  throttled per thread since the condition is sustained, not incidental.
- Echo the requested segmentLimit rather than the budget-reduced one.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/does-thread-length-slow-responses-thr_ic34feaiqp branch from fb62fc6 to 6758c2d Compare July 28, 2026 22:11
@SawyerHood
SawyerHood merged commit f8a8113 into main Jul 28, 2026
10 checks passed
@SawyerHood
SawyerHood deleted the bb/does-thread-length-slow-responses-thr_ic34feaiqp branch July 28, 2026 22:41
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`
smsunarto added a commit to smsunarto/bb that referenced this pull request Aug 29, 2026
node-pty 1.1.0's macOS posix_spawn path leaks one /dev/ptmx master fd
per spawn (cleanup loop never closes low_fds[0]) plus the parent slave
fd and a kqueue fd. The host daemon exhausted the 511-device pty pool.
Upstream fixed all three in get-bb#882 and get-bb#931, shipped in 1.2.0-beta.15.
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