Repository navigation
Conversation
ymichael
changed the base branch from
bb/avoid-full-timeline-push-after-resubscribe-thr_kigfsdgsy7
to
main
October 24, 2026 05:10
A new subscription target had no previous push, so the first push after opening or returning to a thread resent the whole window over the socket even though the client had just fetched it over HTTP. The push now uses the rows the server last delivered for the same params (HTTP read or push) as its baseline, and records pushes in that cache so the resume refetch can be an HTTP delta too. The client applies a pushed delta only when its maxSeq equals the baseline and refetches otherwise. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pushes resent the whole row order on every appended row and every unchanged top-level field, so a push was 11-42KB for 1-2KB of changed rows. A delta's baseline was named only by afterSequence, and rows built while a thread is idle differ from rows built while it is active at the same sequence, so opening an idle thread and starting a turn pushed the full window. Every timeline window now carries a content-hash tag. Clients send afterTag, and the server diffs against the exact window it served under that tag, whatever thread status built it. Deltas encode row order as ranges over the base window plus new ids, and carry only the top-level fields (and timeline page keys) that changed. Clients apply a delta only when their window's tag matches and refetch with their own tag otherwise. Pushes keep afterSequence null so clients from before tags refetch rather than apply them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The app subscribes to a thread's timeline and reads it over HTTP at the same time. When the thread changed before the read was served, the push had no baseline and sent the full window, and the read returned a second one. A new subscription's baseline was also a guess: the window most recently served to anyone with the same options. Subscribe messages now carry timelineTags, the tag each timeline target's client holds (null until its first read returns). The hub tracks the tag per socket, outside the target's identity, and moves it to every window it pushes there. Pushes are grouped by each subscriber's own baseline; a subscriber with no tag yet gets nothing, and receiving a tag schedules a push so changes after the read still arrive. Subscriptions without timelineTags keep the previous behaviour, and older servers strip the field. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The served-windows cache held up to eight full windows for 64 threads, about 190 MB of heap when filled with large threads. It now holds 16 threads within 32 MB of window JSON, measured from row lengths memoized alongside the row hashes. Over the budget it drops the least recently used threads, then the oldest windows of the current thread. A dropped tag costs a full window. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The served-windows cache kept the last eight windows per thread. During a turn every push adds one, so it held windows nobody had and still lost the ones a returning client needed after a few seconds. It now keeps a window while it is the latest for its request shape, while a connected subscriber's tag names it, or for 30 seconds after a read served it. A read with that window's afterTag, or the subscription sending its tag, releases the read's hold, so a client that refetches on every change keeps one window. Pushes are recorded after they are sent, so subscribers have already moved to the new window. A window over a quarter of the 32 MB budget is not kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
force-pushed
the
bb/shrink-timeline-pushes-and-idle-to-active-delta-thr_h9yeqibab5
branch
from
October 26, 2026 20:48
2262c26 to
2d1d1cb
Compare
ymichael
deleted the
bb/shrink-timeline-pushes-and-idle-to-active-delta-thr_h9yeqibab5
branch
October 26, 2026 21:41
ymichael
added a commit
that referenced
this pull request
Oct 27, 2026
## Human comments ## What was wrong #6220 made `thread-timeline` subscriptions tag-aware: a `subscribe` message tells the server which window the client holds (`timelineTags`), and a subscriber whose tag is `null` gets no pushes until a tag arrives. The client only sent a tag after a fetch (`fetchThreadTimeline` → `syncThreadTimelineSubscriptionTag`). `WebSocketManager.unsubscribe()` deleted the tracked tag when you left a thread, so coming back resubscribed with `null` and the server recorded a `pending` baseline that `pushTarget` skips. If the cached timeline was less than 2s old (global `staleTime`), remounting didn't refetch. With pushes on, that is the usual case for a running thread, because every applied push refreshes `dataUpdatedAt`. So no tag was ever sent. In push mode, appended events also don't invalidate an open timeline (`dirtyThreadTimelineQueriesForAppendedEvents`). The thread stayed frozen until a focus refetch or reconnect. This only happens with the `timelinePush` experiment, which early adopters get by default. A real app run also showed a race that hides the bug on fast-streaming threads. A push still in flight after the unsubscribe re-recorded the tag in `handleIncomingMessage`, so the bug showed only when you left during a quiet moment. That stale entry could also outlive the cached window it named. ## What changed - `apps/app/src/lib/ws.ts`: `WebSocketManager.setHeldThreadTimelineTagSource(source)` registers a lookup for the tag of the window the client holds. Every `subscribe` message, both a single subscribe and the batched one sent when the socket opens or reconnects, uses that tag first, then the tracked tag, then `null`. It also records the tag it sends, so later `syncThreadTimelineTag` calls dedupe against what the server holds. A pushed tag is recorded only while the target is still subscribed. - `apps/app/src/hooks/cache-owners/thread-timeline-push-owner.ts`: `trackHeldThreadTimelineTags(queryClient)` points that lookup at the React Query cache: the `.tag` of the cached `ThreadTimelineResponse`. The cache is the source of truth. `useWebSocket` installs it next to the existing `applyThreadTimelineSignal` wiring. - Edge cases: - **Garbage-collected cache entry.** The lookup returns nothing, so the client subscribes with `null`. The mount fetch that always follows sends the tag. This is #6220's first-open path, so the double full-window push it removed doesn't come back. - **Segment limit / compact viewport.** The query key is per thread, not per segment limit. A cached window fetched with the other limit is still an exact baseline, because the server looks baselines up by content tag per thread and diffs window to window. `fetchThreadTimeline` already sends `afterTag` across limits the same way. - **Reconnect.** Sends the cached window's tag rather than the tag of a push the client received but couldn't apply. - **Stale cache on return.** The pushed delta and the mount refetch's HTTP delta are both built against the same tag. Only if the server has evicted that window (16-thread / 32MB backstops) do both send a full window. The client keeps the newer one. - No server change. With this fix, a client sends `null` only when it holds no window, and then a fetch always follows and syncs the tag. A server-side fallback for `pending` subscribers would bring back the full-window push before the GET that #6220 removed. I added a server test that pins the assumption the fix relies on: a subscriber that leaves and returns with the last pushed window's tag gets a delta, not a full window, even after the 30s read hold has expired. - `docs/timeline-pagination.md`: updated the "Deltas and pushes" paragraph. - No wire change and no `HOST_DAEMON_PROTOCOL_VERSION` bump. No server/daemon field changed, and app/server subscribe messages keep the same shape. ## How you verified - New `apps/app/src/hooks/queries/thread-timeline-resubscribe.test.tsx` renders the real `useWebSocket` and `useThreadTimeline`, with the real `wsManager` on a fake socket and the app query client (`staleTime` 2000): - Leaving and returning within the stale window resubscribes with the cached tag and doesn't refetch. **Fails on `main`**: the tag sent is `null`. - On reconnect after an unapplied push, the client sends the tag of the window it holds. **Fails on `main`**: it sends the pushed tag. - After the cache entry is removed, the client subscribes with `null`, then sends the refetched tag. - `apps/app/src/lib/ws.test.ts`: a push that lands after the last subscriber left doesn't leave a tag behind. - `apps/server/test/public/public-thread-timeline-push.test.ts`: a subscriber returning with its last pushed tag gets a delta that matches a fresh GET. - `pnpm exec turbo run typecheck lint test --filter=@bb/app --filter=@bb/server`: 14/14 tasks pass. App: 6310 passed. Server: 3690 passed. The first run had one failure in the existing `pushes deltas from the fetched window that keep a subscriber equal to a fresh GET`, which this PR doesn't touch. It uses 50ms push-settle timing under full-suite load. The file passed 3/3 times alone, and the full rerun was green. - Real dev app (`pnpm dev`, fresh data dir, Claude Code provider, `bb settings experiment timelinePush true`, headless Chromium with a `WebSocket` send/receive hook). I opened a running thread that runs a 4s Bash step at a time, waited for a push, then clicked another thread and clicked back about 450ms later: - Without the `useWebSocket` wiring (`main` behaviour): the resubscribe carried `null`. No pushes arrived in the next 12s, and the view stayed on step 3 while the server was past step 6. - With the fix: the resubscribe carried the cached tag. Pushes kept arriving as ~1.1KB deltas (none full), and the view kept updating. - On a fast-streaming thread, `main` sometimes escaped the bug through the in-flight push race described above. That race is why the bug showed up only intermittently. > 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
This PR now targets
mainand includes #6208's change, which is closed in favour of this PR. #6208 made the server push a delta instead of a full window after a resubscribe; this PR replaces its sequence-number baselines with content tags and keeps that behaviour.computeTimelineRowDeltasent the wholerowOrder(every row id in the window, about 30.6KB onthr_iegshhdusf) whenever a row was added, and every delta spread the full response, soproviderCommands(about 10KB) andcontextWindowUsage(about 7.3KB) rode along on every push.afterSequence. At onemaxSeq, rows built while the thread is idle differ from rows built while it is active (finalizePendingMessagesinterrupts pending tools when idle). So the baseline lookup keyed on status, and it missed when the client had fetched while idle. Dropping status from the key was unsafe, because nothing told the server which version a client held.What changed
Baseline tags. Every full timeline response now carries
tag, a hash of the window's whole content (rows, every top-level field,maxSeq). Clients sendafterTagin place ofafterSequence. The server keeps the windows it served by tag and diffs against the exact window behind that tag. It keeps a window only while someone can diff against it:afterTagor its subscription sends the tag. So a client without pushes, which refetches on every change, keeps one window.Pushes are recorded after they are sent, once subscribers have moved to the new window. On the harness this holds exactly one window per window size after every push (106 of 106), where a fixed ring of 8 per thread held up to 8. Backstops: 16 threads, 32MB of window JSON (least recently used threads go first), and no window over 8MB is kept. Sizes come from row JSON lengths memoized with the row hashes: within 40 bytes of the real 446KB window, and 0.05ms per window. The earlier fixed ring (8 windows × 64 threads) came to about 190MB of heap on threads like
thr_iegshhdusf(343KB per default window). Because tags are content hashes, an idle-built window is a valid baseline for an active one. Deltas after a history rewrite or compaction are also exact, so the delta-floor bookkeeping is gone.Compact deltas (
packages/server-contract/src/thread-timeline-delta.ts). A delta response is{ maxSeq, tag, delta: { afterTag, upsertRows, rowOrder?, fields } }:rowOrderlists new row ids plus[start, length]ranges over the base window's rows. Appending a row costs a few bytes, not 30KB.fieldscarries only the top-level fields that changed.timelinePageis patched per key, so unchangedolderRowUpdatesare not resent. A field that is no longer reported is sent asnull.JSON.stringifydiff it replaces cost about 1.4ms.Client (
thread-timeline-push-owner.ts,thread-queries.ts).applyThreadTimelineDeltaapplies a delta only when the held window's tag equalsafterTagand every range and upsert fits. Otherwise the client refetches with its own tag, which is usually a small HTTP delta. It never guesses. When several subscribers hold different versions, each one either applies the push or refetches its own exact delta.Tag-aware subscriptions (
packages/domain/src/change-kinds.ts,apps/server/src/ws/hub.ts,thread-timeline-windows.ts,apps/app/src/lib/ws.ts):subscribemessage can carrytimelineTags: eachthread-timelinetarget key mapped to the tag the client holds, ornullbefore its first read returns.nulland sends the read's tag once the GET returns. It sends its tag again whenever a read changes it, and with every subscription after a reconnect. Tags of windows it receives over the socket are recorded without a message.servedWindows.get(tag)), so default and compact windows, or two tabs, each get a delta against the window they hold.nullsubscriber gets no push. Receiving a tag schedules a push, so anything that changed after the read still arrives.lastPushedByTargetandservedWindows.latestare used only for legacy subscriptions.SDK.
sdk.threads.timelinetakesafterTag. It is typed to return a full window unlessafterTagis given, so the CLI, status, and plugin callers are unchanged. Plugin SDK bumped to 0.6.85, abovemain's 0.6.84, because the bundled types changed.Documented in
docs/timeline-pagination.mdunder "Deltas and pushes".Compatibility (app ↔ server, no daemon protocol involved)
There is no app/server version negotiation. Each skew degrades to a full read and never to a misapplied delta:
afterSequence: null, so an old client treats a pushed delta as unusable and refetches. ItsafterSequencequery is no longer read, so it gets full windows. That is correct but large until the tab reloads. The timeline push path is behind thetimelinePushexperiment.afterTagand returns full windows. It also stripstimelineTagsfrom subscribe messages: the field is on the message, not in the strict target schema, so the subscription is kept and treated as legacy.timelineTags(an old client) is legacy and keeps the earlier behaviour: a delta against the window last pushed to that target or, for a new target, the window most recently served for the same options. An entry ofnullmeans "tag-aware, nothing held yet": no pushes until a tag arrives. A string means "holds this window".Why a
nullsubscriber can safely get no pushes:read()builds the window and records it inservedWindowsin one synchronous call, and the client sends the tag only after the response arrives. A change either lands in that read, or comes after it. In the second case it is pushed against the read's tag: by a push that runs after the tag arrives, or by the push the tag schedules. That push runs on the nextschedulePushtimer, at mostMAX_PUSH_PAUSE_MS(1s) later. If a timer is already pending, it reads the updated tag when it fires. The one way this degrades is eviction: the read's window must still be held when the tag arrives. Its 30-second read hold covers that, unless the thread falls out of the 16-thread or 32MB backstop first. If it isn't, the subscriber gets the full window. That is correct but large.HOST_DAEMON_PROTOCOL_VERSIONis not bumped: no server/daemon wire field changed.How you verified
Measured with #6208's harness: the real server app on a read-only copy of
thr_iegshhdusf's rows (448 rows in the default window), default and compact (segmentLimit: 8) subscribers withdeferContent, replaying the last turn's real events. The harness was updated to the tag protocol, and its check now compares each client's whole window (all fields, not just rows) with a fresh GET. Every run matched.Opening a running thread in the app's order: subscribe, an event lands and its push runs, then the GET, then the tag. Compared with this branch before tag-aware subscriptions (measured before the rebase onto
main; the rebase changed none of this PR's code):#6208's thread storage was archived, so I rebuilt the harness database read-only from~/.bb/bb.db. It holdsthr_iegshhdusf's rows: 1259 events up to sequence 2572. Every other scenario reproduces the earlier numbers byte for byte.HTTP totals are dominated by the initial full open (about 517KB), which this PR does not change. The 8KB maximum is the turn-end push where
contextWindowUsagechanges; it is resent whole.Tests:
packages/server-contract/test/thread-timeline-delta.test.ts:timelinePagekeys are sent, and cleared fields are removed.afterTag, out-of-range ranges and unplaced upserts are refused.apps/server/test/public/public-thread-timeline-delta.test.ts:maxSeq.afterSequencereads get the full window.apps/server/test/public/public-thread-timeline-push.test.ts:apps/server/test/app/client-protocol.test.ts:timelineTagssets the per-socket state (legacy,null, tag) without closing the socket, and only a real tag notifies the windows.apps/app/src/lib/ws.test.ts:null, then the GET's tag once.apps/app/src/hooks/queries/thread-timeline-push.test.tsx: a matching tag applies without fetching. A delta built on another window refetches with the client's own tag; this includes the samemaxSeqwith a different tag. Unreadable pushes refetch, and stale or foreign pushes are ignored. Each fetched window's tag is reported to the subscription.turbo run typecheck --filter='...[origin/main]'passes (98 packages). Servertest/app, the timeline push, delta and scrollback tests,services/threadsandturn-tracepass (502 tests). Appsrc/lib,src/hooksand timeline tests pass (2133), and so does@bb/server-contract(85).@bb/applint passes.pnpm exec turbo run testpassed for@bb/server(3686 tests; the one failure in the full run wasplugin-native-server-loading, which ran while I bumped the plugin SDK version and passes on rerun),@bb/app(6304),@bb/server-contract,@bb/client-core,@bb/sdk,@bb/cliand@bb/demo-server.pnpm exec turbo run typecheckpasses for those packages andbb-plugin-side-chat.@bb/applint andoxfmt --checkpass on the changed files.check-plugin-sdk-version.mjspasses.🤖 Generated with Claude Code