Skip to content

Extend the latest timeline selection and projection on pushes - #7012

Merged
ymichael merged 4 commits into
mainfrom
bb/resume-timeline-projection-thr_envvcje6te
Nov 4, 2026
Merged

ymichael merged 4 commits into
mainfrom
bb/resume-timeline-projection-thr_envvcje6te

Conversation

@ymichael

@ymichael ymichael commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • buildThreadTimelineFromEvents still 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.
  • The memo re-selected from the database far more often than needed. A replay analysis in @thread:thr_932ndnsbdg found memo misses at 64–69% of push CPU (22 heavy threads, 2,000 events each), and the fresh selection was identical to the extended one in almost every case:
    • children of a parent with no tool-call rows (Claude Code background tasks parented to a shell command), 19–40% of push CPU, and 60–85% on three threads;
    • turn starts, acceptances and completions, plus background task starts and completions, about 3–6% each;
    • every read of a thread that was not active (7.5%), plus the first read after it became active again (6.2%);
    • tool calls without children (1–2%).
  • Every turn boundary recomputed the ordering context behind turn grouping by scanning all request and turn rows since the context epoch.
  • A moved window start (a new request, or the event budget passing a request) re-ran the whole selection against the database, although the new window is part of the old one.

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-view build-event-projection.ts, build-thread-timeline.ts, server timeline-projection-fold.ts):

  • The per-event loop body of buildFlatProjectionData is now foldProjectionEvent. It moved unchanged (continue → return), so the diff is large but mechanical. New startEventProjectionFold / resumeEventProjectionFold / finishEventProjectionFold:
    • The fold's lookups over the whole selection are built from client/turn/requested, client/turn/rejected, turn/input/accepted and turn/started only. resumeEventProjectionFold refuses those event types and out-of-order events, so a resumed fold always has the lookups a fresh fold would.
    • Finishing (flush the active tool cell, finalize interrupted turns, enrich background-agent models) mutates state, so it runs on a copy:
      • For an active thread with no interrupted turn in the window, the copy shares message objects and copies only the containers finishing touches and the workflow messages it enriches.
      • Otherwise the copy is a structuredClone.
  • For active threads the build keeps the fold per selection key (16 windows). The next build resumes it only if the new selection starts with exactly the row objects it folded. Any other selection projects from scratch, exactly as main, and keeps that fold.

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.

  1. Parent rules. A child of a parent id is accepted when the parent is visible, or when it has no toolCall/delegation rows (the result is remembered per entry). A new tool call is accepted when it has no earlier children.
  2. Turn and background-task events, idle threads. Turn starts, acceptances and completions, and background task starts and completions, now extend the memo:
    • A newly fetched turn must have no earlier rows, and its turn/started row must already be selected.
    • An acceptance's request rows must be selected, and the request must have no other acceptance.
    • A background task completion must not drop rows: there are no earlier progress rows, and its started row is kept by the window, its turn or its parent.
    • The memo no longer forgets threads that are not active (selection never depended on status). At most 4 of its 16 entries can belong to non-active threads, so browsing idle threads cannot evict active ones.
    • history-rewritten and history-compacted notifications now drop the thread's memo entries and folds.
  3. Incremental ordering context (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.
  4. Trim on window-start moves. New requests extend the memo too (unique request id, no earlier acceptance or rejection) and update the cached window hints.
    • When the start moves forward, selectStandardTimelineEventRows reruns 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.
    • The source throws a fallback (and the build re-selects from the database) whenever a query would need a turn or children it never fetched, or a parent row it does not hold.
    • In the randomized memo test this path ran 227 times across 25 seeds without a fallback, and every result equaled a cold build.

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.md describes the extended selection, the trim and the kept projection.

How you verified

Data: the scrubbed subset.db (300 threads) and heavy.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:

  • removes each thread's last 300 events and re-inserts them one at a time;
  • flips the thread's status the way the server does (active on a request or root turn start, idle or error on root turn completion);
  • reads the latest window with the previous tag through createThreadTimelineWindows().read, which is the push's buildWindow + 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):

  • Page parity: every thread × idle/active × default/nested/inline × latest + 5 older pages. That is 2,502 responses (subset) and 7,050 (heavy), byte-identical to main on all 9,552.
  • Push replay: every pushed window's tag is identical to main, 3,600/3,600 (subset) and 5,100/5,100 (heavy).
  • Warm (kept selection and fold) == cold (fresh connection, all caches cleared) after every event: 3,600 checks on subset and 5,100 on heavy, 0 mismatches.

Push CPU per fix (cumulative; total push read CPU, median and p95 per push, GC collections; rounds 1 / 2):

stage subset CPU subset p50 / p95 heavy CPU heavy p50 / p95 GC (subset / heavy)
main 112.8 / 116.4 s 24.1 / 91.9 ms 252.7 / 263.4 s 24.9 / 132.9 ms 1,105 / 2,822
kept projection 90.8 / 91.9 s 14.5 / 90.2 ms 219.2 / 219.8 s 16.5 / 132.1 ms 771 / 2,331
+ 1 parent rules 90.4 / 90.7 s 14.7 / 91.1 ms 180.2 / 180.2 s 16.6 / 115.2 ms 763 / 1,820
+ 2 turn/task events, idle threads 72.2 / 68.9 s 14.1 / 49.0 ms 125.2 / 124.1 s 15.9 / 74.9 ms 594 / 1,174
+ 3 incremental ordering context 69.9 / 69.4 s 13.9 / 44.7 ms 112.0 / 111.1 s 15.5 / 54.3 ms 582 / 1,180
+ 4 trim on start moves 64.7 / 59.7 s 13.7 / 40.2 ms 106.6 / 104.3 s 14.9 / 51.0 ms 549 / 1,096

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:

  • stage 1 keeps turn and background-task events as selection-changing, keeps the memo active-only, and rescans the ordering context;
  • stage 2 rescans the ordering context.

Per thread (round 1, push CPU over 300 events, main → final):

thread main kept projection +1 +2 +3 +4
thr_m46b55x3yc (orphan-parent background tasks) 17.0 s 12.8 12.0 4.9 4.9 4.5
thr_d5ej4e2gtv (short turns) 16.9 s 16.3 16.9 11.3 7.8 7.5
thr_9ighpmg7u5 (short turns) 10.1 s 9.7 9.8 8.5 4.1 3.4
thr_gcuc46ug4j 14.8 s 9.8 10.2 9.1 8.8 8.4
thr_ymhw6pktq4 5.9 s 5.6 5.4 3.9 3.9 3.5

In 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.
  • Selection memo tests:
    • The randomized warm == cold test now also generates background tasks parented to commands and tool calls, plus subagent turns. Locally it ran with 25 seeds; CI runs 5.
    • Cases for parents without rows and for childless tool calls.
    • The idle-entry cap.
  • Locally at low priority: pnpm exec turbo run typecheck --filter=@bb/server, plus vitest for test/services/threads/, timeline-streaming-memo, timeline-pagination-correctness, public-thread-timeline-* and public-thread-diagnostic-events (340 tests). CI runs the full suites.

Supersedes #6980 (in-memory units on a separate read path).

AGENT GENERATED

🤖 Generated with Claude Code

… 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]>
@ymichael ymichael changed the title Resume the latest timeline projection on pushes instead of re-folding the window Extend the latest timeline selection and projection on pushes Nov 4, 2026
@ymichael
ymichael merged commit 4f973b8 into main Nov 4, 2026
52 checks passed
@ymichael
ymichael deleted the bb/resume-timeline-projection-thr_envvcje6te branch November 4, 2026 18:27
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]>
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