Skip to content

perf(server): extend timeline ordering context rows incrementally - #5678

Closed
ymichael wants to merge 1 commit into
mainfrom
bb/timeline-ordering-context-incremental-thr_2z29ajq3hn
Closed

ymichael wants to merge 1 commit into
mainfrom
bb/timeline-ordering-context-incremental-thr_2z29ajq3hn

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Follow-up to #5598 / #5655. The timeline grouping context cache (apps/server/src/services/threads/timeline-context-order.ts) reuses an entry only when no ordering row arrived since it was computed. Ordering rows are client/turn/requested, turn/input/accepted, turn/started and turn/completed. Every new turn adds them, so the first timeline build after each message re-read every ordering row in the thread epoch through listTimelineOrderingContext.

Warm, that query is cheap (5–25 ms on real long threads). On a long-lived database, though, the request rows sit scattered among other threads' events and fall out of the page cache. Production slow-query logs show the ordering query at 1,081.7 ms wall versus 90.7 ms CPU, and 505.8 ms wall versus 34.3 ms CPU. The first was about 18 hours after a server restart, and the same thread rebuilt its context three times in one afternoon without a restart. These stalls block the event loop: one build logged Thread timeline build blocked the event loop at 2.8 s.

What changed

  • timeline-context-order.ts keeps a second per-db map next to the context entries, keyed the same way (thread, epoch start) and capped at the same 128 keys. It holds the ordering rows already read, together with the maxSeq, rewrite generation and data_version they were read at.
  • When no context entry is reusable, the cache reads only the ordering rows after the cached maxSeq, appends them, and runs the unchanged computeTimelineOrderingContext over the combined rows. An older maxSeq slices the cached rows, which are sorted, with no DB read.
  • A rewrite-generation bump (suffix delete, below-high-water insert, prune, output migration) or a data_version change (a write from another connection) still forces a full read, exactly as before. The context-entry reuse rules and the parented-boundary handling are unchanged.
  • No schema, migration, wire/protocol, CLI or UI changes.

Not addressed: the first build after a server restart still does a full, possibly cold, read. Avoiding that needs persisted per-turn ordering fields, which means a schema change.

How you verified

  • New test reads only rows after the cached sequence when a new turn changes the context. It warms the cache, appends a user request while a turn is running (the boundary changes from null to that request), and asserts that the ordering query runs once, starting at the cached maxSeq + 1, and that the result equals a cold computation.
  • The existing randomized property test, which compares cached and cold contexts across 20 seeds of appends, suffix rewrites and prunes, still passes, along with the other cache tests (22 total).
  • pnpm exec turbo run typecheck lint test --filter=@bb/server passed: 3,550 tests, 1 skipped. Typecheck, lint and the cache tests were re-run after rebasing onto 6a639cfc0d.
  • Benchmark on a snapshot of a seeded 150k-event, 30k-turn thread. Over five appended turns, the first build after each new turn took 41–59 ms incrementally versus 433–454 ms with a full recompute, and the contexts were identical every time. The remainder is the parented-boundary query, about 31 ms here and 1–4 ms on real threads, plus the in-memory recompute.

AGENT GENERATED

🤖 Generated with Claude Code

The timeline grouping context cache could only reuse an entry when no
request, acceptance, turn start or turn completion landed since it was
computed. Every new turn adds those rows, so the first timeline build
after each message re-read every ordering row in the thread epoch. On a
long-lived thread those reads are mostly cold page reads: production
slow-query logs show the ordering query at 1,082 ms wall versus 91 ms
CPU, 18 hours after a restart.

The cache now also keeps the ordering rows it read per thread epoch,
validated by the same rewrite generation and data_version as the context
entries. When an entry cannot be reused, it reads only the rows after the
cached sequence and recomputes the context from the combined rows with
the unchanged pure computation. Rewrites, prunes and external writes
still force a full read, and older snapshots slice the cached rows.

On a 150k-event, 30k-turn thread the first build after a new turn drops
from 433-454 ms to 41-59 ms with identical contexts; the remainder is the
parented boundary query and the in-memory recompute.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Oct 19, 2026
## Human comments

## What was wrong

Confirmed on main at `6a639cfc0d` using a snapshot of real production
threads: timeline projection repeatedly tokenizes identical shell
commands for start/completion events and subsequent rebuilds. Shell
intent parsing accounted for about two-thirds of projection CPU in the
repeatable slow window. The scanner also appended ordinary text one
character at a time, and optional read/search summaries had no
input-size bound. A synthetic two-million-character script with many
short commands took about 97 ms to infer a summary; merely scanning text
faster still took about 90 ms for that shape.

This addresses remaining projection work after #5599 and #5655. It does
not touch #5678's ordering-context implementation or tests.
Event-query/decode costs remain.

## What changed

- Retain a shared LRU cache keyed by exact command text, bounded by
4,096 entries and 2,000,000 total command characters. Empty results are
cached too; callers receive fresh arrays and copies of the flat intent
objects.
- Skip optional shell-summary inference when the unwrapped command
exceeds **2,048 UTF-16 code units**, before cache lookup or scanning.
The complete command remains available and displays as a command rather
than an inferred read/search. No prefix is summarized: a later write
could invalidate an earlier read classification.
- Scan runs of ordinary text using sticky regular expressions for
unquoted, single-quoted and double-quoted text. Existing handling still
processes quotes, escapes, whitespace, separators and redirects. This
also speeds the shared thread-message scanner. The summary cap does not
truncate or disable long `bb thread tell` messages.

The shared implementation serves timeline/CLI consumers. No
configuration, public API, schema, persisted-data, or server/daemon wire
changes. The cache is process-local and clears on restart.

### Why 2K

Measured all 494,340 distinct completed commands in the snapshot;
249,347 currently produce a summary. Counts below are exact, not
sampled:

| Cutoff | Commands that skip inference | Existing summaries removed |
| --- | ---: | ---: |
| 512 characters | 80,330 | 11,267 (4.52%) |
| 1,024 characters | 34,096 | 719 (0.29%) |
| **2,048 characters** | **13,761** | **49 (0.02%)** |
| 4,096 characters | 4,104 | 3 (0.0012%) |

512/1K remove ordinary multi-file searches and batches of file reads.
Inspection of the 2K+ cases found mostly longer scripts whose inferred
label describes only one part of the command. 2K preserves 99.98% of
existing summaries while bounding inference work; 4K doubles the limit
to preserve 46 additional labels. Full command text is retained at every
cutoff.

## How you verified

- Red/green: the 2,049-character timeline fallback test and uncached
scanner CPU regression fail on the cache-only revision and pass after
these changes. Boundary coverage checks inference at 2,048 characters,
fallback at 2,049, full command preservation and displayed titles. Mixed
quoted/escaped runs and long thread-message extraction are covered.
Cache reuse, caller mutation independence, later-write disqualification
and early-write short-circuit coverage remain; performance fixtures stay
below the cap so it cannot hide regressions.
- `pnpm exec turbo run typecheck lint test --filter=@bb/thread-view
--filter=@bb/server`: passed; 495 thread-view tests and 3,550 server
tests passed, 1 server test skipped. Neither package declares a lint
task, so also ran `pnpm exec oxlint` directly on all four changed files.
Oxfmt and `git diff --check` passed.
- Compared the final parser against the original on all **494,340** real
commands: no differences beyond the deliberate >2K fallback. **30,000**
generated quoting/operator cases matched. All **4,596** real commands
matching the thread-message hint retained identical message-extraction
results.
- Final real-data replay: two alternating process rounds per variant
(original main, cache-only, final), 19 historical windows across 16
threads, 10 builds/window. Medians exclude the first build (18
samples/window/variant). Historical sequences are reconstructed from
logged timestamps against the current snapshot, rather than an exact
archive of the original store. Selection/decode caches are cleared for
the first three builds/window.

| Real window | Selected events | Build median, original → final |
Main-thread CPU, original → final | Projection median, original → final
|
| --- | ---: | ---: | ---: | ---: |
| Largest repeatable stall | 7,075 | 217.47 → 150.64 ms (-31%) | 213.88
→ 149.58 ms | 85.87 → 23.94 ms (-72%) |
| Earlier window of the same thread | 6,818 | 186.06 → 142.16 ms (-24%)
| 184.70 → 141.35 ms | 74.48 → 23.06 ms (-69%) |

The cache-only projection medians were 23.26 and 22.88 ms: warm-cache
performance is similar. The additional changes target misses and
oversized inputs. Across 480,579 unique real commands within the new
limit, repeated passes larger than the cache (all misses) used **44%
less parsing CPU** with the final implementation, including its cache
bookkeeping. By input band, CPU improved 1.7× below 512 characters, 2.2×
at 512–1K, and 2.7× at 1K–2K.

Of 380 paired full timeline responses, 360 were byte-identical. The
remaining 20 are repeated builds of one window: a structural comparison
proved the only change was removal of one >2K command's
`activityIntents`; its complete command and every other response field
were unchanged. Cache-only responses all matched the original.

Scripts, snapshot, profiles and reports remain outside the checkout
under the investigation thread's `qa/` storage (`parsing/` contains the
cutoff comparison and final experiments). Production was accessed
read-only to create the snapshot. These are server-builder measurements,
not browser latency; other timeline stages can still stall.

> AGENT GENERATED
@github-actions github-actions Bot closed this Oct 31, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This is an automated message. We have closed this pull request because it has been open for more than two weeks.

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