Skip to content

Remove the fixed per-push cost of building the latest timeline window - #7033

Merged
ymichael merged 2 commits into
mainfrom
bb/push-fixed-cost-thr_envvcje6te
Nov 4, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/push-fixed-cost-thr_envvcje6te

Conversation

@ymichael

@ymichael ymichael commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

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

ymichael and others added 2 commits November 4, 2026 11:16
Each push rebuilt and re-prepared the same handful of SQL statements through
the query builder, re-parsed app settings and experiments, and read the rows
the server had just written back from the database.

- The push-path event queries (latest sequence, appended range, timeline
  window, budget floor advance, context-clear boundary, context-window and
  token usage rows) are prepared once per connection and reused.
- App settings and experiments keep their parsed value per connection and
  re-parse only when the stored rows differ.
- Committed event rows are remembered per thread; the selection memo takes
  them instead of reading the appended range back, after an id-only check of
  that range. Rows longer than the inline output limit, or that the SQL window
  filters decide, still come from the database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit fc119e5 into main Nov 4, 2026
51 checks passed
@ymichael
ymichael deleted the bb/push-fixed-cost-thr_envvcje6te branch November 4, 2026 20:43
ymichael added a commit that referenced this pull request Nov 4, 2026
## Human comments

## What was wrong

#7011 (updateWhenIdle settings) reverted two PRs that had merged about
30 minutes before its commit was created: #7028 (merge child notices
while the parent is blocked, skip `/compact` turns) and #7030 (count
only the latest workflow run in GitHub PR check status). Its body
mentions neither, so it looks accidental.

- #7011 is a single commit, `6b17f1bc04`, whose parent is #7028's merge
commit `920804af63`. Even so, the commit's own diff rewrites 11 files to
their earlier content:
- In #7028's 9 files it is an exact inverse of #7028, apart from four
exports #7011 added to `packages/db/src/data/index.ts`.
- #7030's 3 files in `plugins/github-pr-status/host/` went back to their
pre-#7030 content.
- That pattern fits a branch whose files came from an older checkout and
were committed onto a newer base.
- CI stayed green because each revert also removed the matching tests.
- No other PR was affected. Every file the commit touched was compared
with its earlier versions on main; only these two PRs match.

What users got back after #7011:
- **#7028:** a parent blocked on a question, a starting turn or an
offline host collects a separate notice for every child update again (on
Nov 3 one parent got ten from one child). `/compact` turns on a child
send the parent "No final output was recorded."
- **#7030:** bb shows green PRs as failing ("22 passed, 4 failed") when
GitHub cancelled a duplicate CI run.

## What changed

- Cherry-picks `b0e91c38f8` (#7030) and `920804af63` (#7028) onto
current main with `-x`. #7030 applies unchanged.
- #7028 conflicted only in `coalesced-system-notices.ts`, because #7029
(merged after #7011) added withdrawing a pending notice there. The
result is #7028's version with #7029's withdraw path kept: the pending
lookup has no `now` and a merge writes `windowEndsAt`. This is the
combination #7029 was tested with before #7011 landed.
`child-thread-notifications.ts` resolved to main's existing version,
which already guards on a scheduled row.
- Restores the #7029 test that depends on #7028: an ownership change
undone after its 2 s window but before delivery is withdrawn. Its test
helper comes back with it.
- `internal/events.ts` and `db/data/events.ts` merged cleanly with the
later #7031 and #7033 changes.
- No daemon wire, CLI, config or plugin SDK surface change;
`check-plugin-sdk-version` reports the surface unchanged.

## How you verified

- With main's current code and the restored tests, 7 tests fail. With
this branch they pass:
- `thread-ownership-notices`: "withdraw a move undone after its window
but before delivery"
- `system-notice-dispatch`: "merge later outcomes into a row still
waiting on the parent"
- `child-completion-turn-output`: "does not notify the parent for a turn
that only compacted context"
- `github-pr-status` `git-host` / `batch`: superseded workflow runs,
including on a later checks page and for drafts found through `gh pr
view`
- Server: ownership notices, notice dispatch, child completion output,
notice kinds, child outcomes, parenting, plugin events, queue updates,
sidebar status and child notifications all pass (112 tests).
- `turbo run test` for the GitHub PR Status plugin, `@bb/db` and
`@bb/templates` passes (10/10 tasks). `turbo run typecheck` for server,
db, app and the plugin passes (10/10 tasks).

> 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