Repository navigation
Extend the latest timeline selection and projection on pushes - #7012
Merged
Merged
Conversation
… the window While a thread is active, the latest window's sparse selection is kept between reads (#6964) and extended with appended events, but every push still folded the whole selection through the projection. The server now keeps the fold's state for that selection and, when the next read only extends it, folds just the appended events. Finishing (flushing the active tool cell, finalizing interrupted turns, enriching workflow messages) runs on a copy, so the kept state is never consumed. Any fresh selection (turn boundary, moved window start, rewrite, other-connection write, idle thread) projects from scratch as before and keeps the result. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…parent events Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 4, 2026
Merged
ymichael
added a commit
that referenced
this pull request
Nov 4, 2026
…the agent what was cut (#7004) ## Human comments ## What was wrong #6955 resumes only threads that were mid-turn when the daemon came back as a new instance: `planRestartResumes` selects `status = "active"` threads ([restart-resume.ts#L37](https://github.com/get-bb/bb/blob/64c2f7099e1a678070dd24d730aa1120b2fb18e1/apps/server/src/services/threads/restart-resume.ts#L37)). An idle thread whose agent started a long background command (Claude Code `run_in_background`) and ended its turn to wait for it is not resumed. On reconnect the server only marks that background task `stopped` ([session-owner-side-effects.ts#L135](https://github.com/get-bb/bb/blob/64c2f7099e1a678070dd24d730aa1120b2fb18e1/apps/server/src/internal/session-owner-side-effects.ts#L135)). The process is gone, so the provider never sends the completion that would wake the agent. The thread stays idle indefinitely. That is the migration example in #6127. Mid-turn threads were resumed with a bare "Please continue." ([turn-retry.ts#L98](https://github.com/get-bb/bb/blob/64c2f7099e1a678070dd24d730aa1120b2fb18e1/apps/server/src/services/threads/turn-retry.ts#L98)), which didn't say which command or background job the restart cut off. Claude Code also records the cut tool call as rejected by the user. Reproduced live on main (`pnpm start:worktree`, experiment on, real Claude Code thread): the agent started `./migrate.sh` as a background command and went idle. I killed the daemon with `kill -9 <literal pid>`, and the daemon came back as a new process. 4 s later the server settled the task as stopped, with the migration stuck at batch 15/600. 3.5 minutes later the thread was still idle: no new events, no queued rows. ## What changed All of it is behind `resumeThreadsAfterRestart` and uses #6955's retry row, front-of-queue hold, and attempt cap. Nothing new is scheduled or parked. - **Wake idle threads** (`restart-resume.ts`): before interrupting and settling, `planRestartResumes` reads the host's open background tasks (`listOpenBackgroundTaskItemRowsForHost`; tasks with `skipTranscript` are left out). It plans a resume for every live (unarchived, undeleted) `idle` thread that has one, alongside the cut `active` turns. The resume is a retry row of the thread's latest turn with reason "bb restarted" (`retryTurnAfterRestart` in `turn-retry.ts`, which shares `dispatchRetry` with `retryFailedTurn`). Loop protection is the same retry-chain counter, so a thread that keeps losing its job to restarts is woken at most three times in a row. Idle threads without stopped background work are untouched. - **Name what was cut:** the agent-only continuation that replaced "Please continue." comes from a new `systemMessageRestartResume` template. It names the unfinished foreground command from the cut turn (`getUnfinishedCommandItemData`) and every background job the restart stopped, as `` `command` (description) ``. The command comes from the task's parent tool call (`listCommandItemDataByItemIds`). The message says once that the restart, not the user, cut the work off, and asks the agent to check before rerunning anything. The forms: | Case | Message after `[bb system]` | |---|---| | Idle, one job | bb restarted and may have stopped this background work: JOB. The user didn't stop it. Check whether it's still running and how far it got, then restart it only if that is safe. | | Idle, several jobs | bb restarted and may have stopped this background work:<br>- JOB<br>- JOB<br><br>The user didn't stop them. Check whether each is still running and how far it got, then restart each only if that is safe. | | Cut turn, running a command | bb restarted while you were running `CMD`. The restart cut it off, not the user, even if your history says the user rejected it. Check what it finished, then continue the task, rerunning it only if that is safe. | | Cut turn, no command | bb restarted while you were working. The restart cut off your turn, not the user, even if your history says the user rejected it. Check whether your last step finished, then continue the task without repeating work. | | Cut turn with jobs | Either cut-turn form, then: It also stopped this background work: JOB. Check how far it got, and restart it only if that is safe. (With several jobs: one per line, "Check how far each got, and restart only what is safe to restart.") | Several jobs are listed one per line in the order they started, up to ten, then "- and N more". To keep that order, `listOpenBackgroundTaskItemRowsForHost` now sorts by event sequence instead of item id. Its other caller, settling dangling tasks, doesn't depend on order. When the provider never accepted the cut turn's input, the original input is still re-sent as before. The Retry button and provider-retry still send "Please continue.". - **Resume title:** a retry row whose reason is the restart reason (`RESTART_RESUME_RETRY_REASON`, `@bb/domain`) is titled "Resume after bb restarted" instead of "Retry failed turn from …". Its wait line reads "resuming at … · attempt N". This applies in the app's queue card and collapsed queue list (`queued-message-wait.ts`) and in `bb thread queue list` (`organization.ts`). Retry-button and provider-retry rows keep their wording. - **Not on for early adopters:** the experiment stays off by default for everyone, including early adopters. It has to be turned on in Settings → Experiments. - **Docs:** `docs/configuration.md`, `bb guide thread-lifecycle`, `bb guide customization`, and the Settings → Experiments description. No daemon wire change, so no `HOST_DAEMON_PROTOCOL_VERSION` bump. No CLI, SDK, or plugin API change. ### What users see - **Idle thread waiting on a background command:** a few seconds after bb comes back, the queue briefly shows "Resume after bb restarted · resuming at … · attempt N". The agent then picks up on its own: it checks the job, restarts it if that is safe, and goes back to waiting. Before this change the thread sat idle and the job was dead. - **Restart resume rows** for mid-turn threads now carry the same "Resume after bb restarted" title. In #6955 they read "Retry failed turn from …". - **Mid-turn thread:** the agent's next reply reflects that it was told what was cut. For example: "The build only reached step 13 of 300 and nothing is still running…". The message itself is agent-only, as before. - All of this applies only with the experiment on. ## How you verified New tests in `apps/server/test/threads/restart-resume.test.ts`, on the real server harness with the daemon reopened as a new instance: | Test | Against main's source (test file only changed) | |---|---| | Idle thread with a stopped background command is woken with a message naming `./migrate.sh` (description); idle thread without background work and an archived one are not | fails: no resume row | | Experiment off: that idle thread stays idle | passes (no-change check) | | Cut turn's message names its foreground command and the stopped background job, with the "not the user" wording | fails: "Please continue." | App (`queued-message-wait.test.ts`) and CLI (`thread-organization.test.ts`) tests cover the resume title, and check that other retry rows keep theirs. The four existing restart tests now expect the new continuation instead of "Please continue.". - `pnpm exec turbo run test --filter=@bb/server -- test/threads/restart-resume.test.ts`: 14/14 pass, including a new test for twelve stopped jobs (ten bullets plus "and 2 more"). With `turn-failed-retry` and the background-task tests, 57/57 pass. `@bb/db` events and query-plan tests: 150/150. - `turbo run test --filter=@bb/templates`: 47 pass. - `turbo run typecheck` (server, app, cli, db, templates) and `lint` pass. - `turbo run test` on `@bb/app` (queued-message-wait, QueuedMessagesList: 86) and `@bb/cli` (thread-organization: 18) passes. - Full suites are left to CI. Live, `pnpm start:worktree` on this branch, real Claude Code threads, daemon killed with `kill -9` on literal PIDs: - **AFTER, idle:** the agent started `./migrate.sh` in the background and went idle. After the kill, the daemon came back and the resume went out 7 s later (attempt 2) with the message above. The agent read the task output and `ps`, found it stopped at batch 14 with nothing running, saw that the script resumes from `progress.txt`, and restarted it in the background (from batch 15). It then went idle waiting again. - **Second restart on the same thread:** the next daemon kill stopped that restarted job too. The thread was woken again (attempt 3) and resumed from batch 53. - **AFTER, mid-turn:** the agent started `./watch-logs.sh` in the background and then ran `./build.sh` in the foreground. After the kill, the error row read "Thread interrupted because bb restarted · bb will resume the thread shortly." The resume named `` `./build.sh` `` and `` `./watch-logs.sh` (Start log watcher in background) ``. The agent checked both, said "The build only reached step 13 of 300 and nothing is still running. Both scripts are safe to rerun…", and restarted both. It then finished: "The last line of `./build.sh` was: BUILD-DONE … The new build finished all 300 steps. `./watch-logs.sh` is running in the background again." - **Full server + daemon restart** (stop and relaunch `pnpm start:worktree` with the title change): both idle threads, each waiting on a background job, were woken. `bb thread queue list` showed both rows as "Resume after bb restarted · scheduled … in 5s". The app's queue card read "Resume after bb restarted · resuming at 8:48 PM · attempt 4". Re-verified after rebasing onto `4f973b851a` (#7012), `pnpm start:worktree` on `ef0d75fcf9`, fresh Claude Code threads, four `kill -9`s on literal daemon PIDs: | Check | Result | |---|---| | Idle thread waiting on `./migrate.sh` in the background | Woken each time (attempts 2, 3, 4). The agent found the job stopped (batches 260, 439, 479) and restarted it from `progress.txt`. | | Mid-turn `./build.sh` plus background `./watch-logs.sh` | The resume named both. The agent restarted both each time. | | Idle thread with no background work | No new events and no queue rows after any kill. | | Fourth restart in a row | Server logged "Not resuming a thread that restarts keep cutting off" (attempt 5) for both threads. The mid-turn thread ended in error with "Please retry the thread to continue." | | `bb thread retry` on that thread (Retry path) | Sent "Please continue.". The build finished with BUILD-DONE. | | App queue row, same live row, branch vs main bundle | "Resume after bb restarted · resuming at 10:37 AM · attempt 3" vs "Retry failed turn from 10:37 AM · bb restarted · retrying at 10:37 AM · attempt 3" | | `bb thread queue list`, branch vs main CLI | "Resume after bb restarted" vs the raw agent-only text "[bb system] bb restarted, or the machin…" | | A user's scheduled message | Same title and wait line in both builds | | Fresh idle thread on `ef0d75fcf9` | Woken; resumed the migration from batch 35 | Re-verified the shorter wording on `df6e457c26` with live Claude Code threads and a `kill -9` on the literal daemon PID: | Thread | Message received | What the agent did | |---|---|---| | Idle, waiting on `./migrate.sh` and `./watch-logs.sh` | Both jobs as bullets, in start order | Checked `progress.txt` (batch 5) and both scripts, then restarted both: "The restart stopped both scripts, and I've started them again." | | Mid-turn `./build.sh` with background `./watch-logs.sh` | "bb restarted while you were running `./build.sh`. … It also stopped this background work: `./watch-logs.sh` (…)" | Ran `cat build-progress.txt; tail -2 watch.log; pgrep -fl 'watch-logs\|build.sh'`, then restarted both | Refs #6127 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 4, 2026
…#7033) ## Human comments ## What was wrong After #7012 almost every push extends the kept selection and resumes the kept projection, but each push still paid about 4.5 ms of fixed cost that does not depend on the event. A probed replay of #7012 split a typical 11–12 ms push into: reading the appended rows back (1.7–1.8 ms) and other fixed queries and parsing (2.8–2.9 ms), on top of the window-proportional work. A CPU profile of main's push path showed why. About three quarters of each of those queries was the query builder rebuilding the SQL and better-sqlite3 re-preparing the statement on every call, not running it. For example, reading one appended row took 0.75 ms through the builder against 0.15 ms for the same SQL prepared once. App settings and experiments were also re-read and re-parsed with zod on every push (about 0.7 ms together), and the rows the server had just written were read back from the database twice: once for the range, once through the timeline window filters. ## What changed One read path; the same queries, prepared once. - **Prepared push-path queries** (`packages/db/src/data/events.ts`, `connection.ts`). The latest thread sequence, the appended range, the timeline window rows, the budget floor advance, the context-clear boundary, and the context-window and token-usage rows are now prepared statements cached per connection through `prepareCachedQuery`. A new `prepareCachedQueryVariant` keys variants whose SQL depends on arguments (inline output limit, excluded types, an optional bound). The SQL is unchanged apart from placeholders. - **Settings and experiments in memory** (`app-settings.ts`, `experiments.ts`, new `stored-setting-rows.ts`). `getAppSettings` and `getExperiments` keep the parsed value per connection and re-parse only when the stored rows differ, checked with one small prepared read. That covers every way the rows change (the setting writers, raw SQL, other connections, rollbacks) without a separate invalidation path. The cached value is deep-frozen, so a caller that tried to mutate it would fail loudly; no caller does. - **Appended rows handed to the memo** (new `appended-event-rows.ts`, `timeline-selection-memo.ts`): - `insertStoredEventRow`, which every event insert goes through, remembers each committed row per thread after its transaction commits (`afterCommit`): 64 threads, 128 rows each, rows up to 64,000 characters. - `listAppendedEventRows` returns those rows after an id-only query confirms they are exactly the rows in the appended range. It falls back to reading the range when any row is missing, or when a row is longer than the inline output limit, since SQLite would truncate it. - `selectAppendedTimelineWindowRows` derives the window rows from the appended rows by excluding the excluded types. Ranges with background task progress or diagnostic event types, which the SQL filters decide, still run the window query. Not changed: what any query returns, the selection and projection rules, and the cold and older-page paths. No wire, protocol, CLI or settings change. `docs/timeline-pagination.md` describes the appended rows and prepared queries. ## How you verified Data: the scrubbed `subset.db` (300 threads) and `heavy.db` (all 353 production threads with 2,000+ events), as migrated clones, never a copy of `~/.bb/bb.db`. Baseline: origin/main 4f973b8 (#7012). The replay harness removes each thread's last 300 events and re-inserts them one at a time through `insertEvents`, the server's write path, so the hand-off runs. It flips the thread's status the way the server does and reads the latest window with the previous tag through `createThreadTimelineWindows().read` (the push's `buildWindow` + delta). 12 subset threads and 17 heavy threads, two interleaved rounds at background priority on a shared machine. **Output is identical to main:** - Page parity, every thread × idle/active × default/nested/inline × latest + 5 older pages: 2,502 (subset) and 7,050 (heavy) responses, all byte-identical. - Push replay: every pushed window's tag identical to main in both rounds, 3,600/3,600 (subset) and 5,100/5,100 (heavy). - Warm (kept selection, fold and remembered rows) == cold (fresh connection, all caches cleared) after every event: 3,600 + 5,100 checks, 0 mismatches. **Push CPU and latency** (total push read CPU; per-push CPU p50 / p95; rounds 1 / 2): | | subset CPU | subset p50 | subset p95 | heavy CPU | heavy p50 | heavy p95 | |---|---|---|---|---|---|---| | main | 56.9 / 51.6 s | 12.3 / 11.5 ms | 33.4 / 31.5 ms | 91.2 / 91.0 s | 12.6 / 13.1 ms | 43.8 / 41.5 ms | | this PR | 40.5 / 42.1 s | 8.0 / 8.2 ms | 28.5 / 27.0 ms | 73.0 / 77.0 s | 9.3 / 9.5 ms | 38.0 / 43.4 ms | | change | −29% / −18% | −35% / −29% | −15% / −14% | −20% / −15% | −26% / −27% | −13% / +5% | GC collections: 562 / 560 → 432 / 429 (subset), 1,092 / 1,097 → 908 / 914 (heavy). The fixed cost is about 4 ms per push, so the median moves most. p95 on heavy is dominated by work that grows with the window, which this PR does not touch; its round-to-round spread is about ±5%. **Tests.** - New `packages/db/test/data/appended-event-rows.test.ts`: - remembered rows equal the stored rows and are served from memory; - a rolled-back insert is never served; - a row longer than the inline output limit is read back truncated; - the derived window rows equal the window query; - ranges with SQL-filtered types fall back to the query. - Existing settings and experiments tests already cover raw SQL writes after a cached read. - Locally at background priority: - `pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/server`; - `@bb/db` vitest: the new file, `events`, `app-settings`, `experiments`, `event-rewrite-generation` (120 tests); - `@bb/server` vitest: `test/services/threads`, `timeline-pagination-correctness`, `timeline-streaming-memo`, `public-thread-timeline-*`, `public-thread-diagnostic-events`, and the settings and experiments route tests (486 tests). Four files timed out under background priority while the benchmark ran and passed when rerun with longer timeouts. - CI runs the full suites. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.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.
Human comments
What was wrong
Every push to a watched thread rebuilt most of the latest window. #6964 made the sparse selection incremental (the selection memo extends the window with appended events), but:
buildThreadTimelineFromEventsstill folded every event of the selection: tool-argument and shell parsing, assistant and reasoning text, the per-event state machine. Profiling main's push path with a replay of real events put that fold at 27–32% of push CPU.What changed
One read path (main's sparse selection and memo), extended in place where a fresh read would give the same rows.
Kept projection (
@bb/thread-viewbuild-event-projection.ts,build-thread-timeline.ts, servertimeline-projection-fold.ts):buildFlatProjectionDatais nowfoldProjectionEvent. It moved unchanged (continue→return), so the diff is large but mechanical. NewstartEventProjectionFold/resumeEventProjectionFold/finishEventProjectionFold:client/turn/requested,client/turn/rejected,turn/input/acceptedandturn/startedonly.resumeEventProjectionFoldrefuses those event types and out-of-order events, so a resumed fold always has the lookups a fresh fold would.structuredClone.Selection memo extensions (
timeline-selection-memo.ts). Each appended row is checked against the rows a fresh selection would add, with targeted queries. Any doubt selects afresh.toolCall/delegationrows (the result is remembered per entry). A new tool call is accepted when it has no earlier children.turn/startedrow must already be selected.history-rewrittenandhistory-compactednotifications now drop the thread's memo entries and folds.timeline-context-order.ts). The ordering context keeps its request and turn rows per thread and epoch and reads only rows after the last read; the derivation over those rows is unchanged. The memo reads request ids and acceptances from it.selectStandardTimelineEventRowsreruns over a row source backed by the kept rows plus the appended rows instead of the database. These cover thread window rows, root window turns, turn rows, children and context rows. Queries that are cheap and unbounded (head state, background task state, interruptions, request lookups) still go to the database.Not changed: the decode cache size, and no sticky window. There is no wire, protocol, CLI or settings change, and no change for older pages. Docs:
docs/timeline-pagination.mddescribes the extended selection, the trim and the kept projection.How you verified
Data: the scrubbed
subset.db(300 threads) andheavy.db(all 353 production threads with 2,000+ events, 1.89M events), as migrated clones; never a copy of~/.bb/bb.db. Main is this PR's base, d060de8.The replay harness:
createThreadTimelineWindows().read, which is the push'sbuildWindow+ delta path.It replays 12 subset threads and 17 heavy threads (the 12 heaviest plus the five @thread:thr_932ndnsbdg threads with the most misses). Timings ran at background priority on a shared machine, with stages interleaved, so compare ratios rather than absolute times.
Output is identical to main (final code):
Push CPU per fix (cumulative; total push read CPU, median and p95 per push, GC collections; rounds 1 / 2):
All told, against main: push CPU is −43% / −49% on subset and −58% / −60% on heavy (rounds 1 / 2), p95 push is −56% (subset) and −62% (heavy), and GC collections are −50% and −61%.
The intermediate stages were measured as patches of the final code that turn later fixes off:
Per thread (round 1, push CPU over 300 events, main → final):
thr_m46b55x3yc(orphan-parent background tasks)thr_d5ej4e2gtv(short turns)thr_9ighpmg7u5(short turns)thr_gcuc46ug4jthr_ymhw6pktq4In this 300-event replay, parent rules alone help less than @thread:thr_932ndnsbdg's 2,000-event estimate suggests: on those threads, most orphan-parent pushes also start or complete a background task, which needs fix 2.
Thread opens (best of 2, all threads, cold = fresh connection): subset 20.7 s main vs 20.9 s, heavy 45.3 s vs 44.6 s. Warm reopens of the replay threads: subset 1,052 vs 1,061 ms, heavy 2,207 vs 2,241 ms.
Tests.
event-projection-fold.test.ts: a fold resumed from every point equals a cold build after every appended event, and resume refuses lookup events.pnpm exec turbo run typecheck --filter=@bb/server, plus vitest fortest/services/threads/,timeline-streaming-memo,timeline-pagination-correctness,public-thread-timeline-*andpublic-thread-diagnostic-events(340 tests). CI runs the full suites.Supersedes #6980 (in-memory units on a separate read path).
🤖 Generated with Claude Code