Skip to content

Shrink timeline pushes and diff idle windows against active ones - #6220

Merged
ymichael merged 7 commits into
mainfrom
bb/shrink-timeline-pushes-and-idle-to-active-delta-thr_h9yeqibab5
Oct 26, 2026
Merged

ymichael merged 7 commits into
mainfrom
bb/shrink-timeline-pushes-and-idle-to-active-delta-thr_h9yeqibab5

Conversation

@ymichael

@ymichael ymichael commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

This PR now targets main and 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.

  • Pushes were 11–42KB for 1–2KB of changed rows. computeTimelineRowDelta sent the whole rowOrder (every row id in the window, about 30.6KB on thr_iegshhdusf) whenever a row was added, and every delta spread the full response, so providerCommands (about 10KB) and contextWindowUsage (about 7.3KB) rode along on every push.
  • Opening an idle thread and then starting a turn pushed the full window (about 517KB). A delta's baseline was named only by afterSequence. At one maxSeq, rows built while the thread is idle differ from rows built while it is active (finalizePendingMessages interrupts 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.
  • Opening a running thread could push the full window as well as returning it from the GET. The app subscribes and reads at about the same time. If the thread changed before the read was served, the push found no baseline and sent the whole window (about 426KB + 98KB here). A new subscription's baseline was also a guess: the window most recently served to anyone with the same options.

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 send afterTag in place of afterSequence. 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:

    • the latest window for each request shape (window size and content options);
    • every window a connected subscriber's tag names, including hidden tabs;
    • each read's window for 30 seconds, released early when that reader reads again with it as afterTag or 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 } }:

    • rowOrder lists new row ids plus [start, length] ranges over the base window's rows. Appending a row costs a few bytes, not 30KB.
    • fields carries only the top-level fields that changed. timelinePage is patched per key, so unchanged olderRowUpdates are not resent. A field that is no longer reported is sent as null.
    • Row comparison uses per-row SHA-256 hashes, memoized per row object, and the tag reuses them. On this 448-row window, the tag costs about 1.1ms per build. The double JSON.stringify diff it replaces cost about 1.4ms.
  • Client (thread-timeline-push-owner.ts, thread-queries.ts). applyThreadTimelineDelta applies a delta only when the held window's tag equals afterTag and 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):

    • A subscribe message can carry timelineTags: each thread-timeline target key mapped to the tag the client holds, or null before its first read returns.
    • The tag sits outside the target, so a tag update doesn't change the watch's identity or start a new watch.
    • The hub keeps the tag per socket and moves it to every window it pushes to that socket.
    • The app subscribes with null and 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.
    • Pushes are grouped by each subscriber's own baseline (servedWindows.get(tag)), so default and compact windows, or two tabs, each get a delta against the window they hold.
    • A null subscriber gets no push. Receiving a tag schedules a push, so anything that changed after the read still arrives.
    • A tag the server no longer holds gets the full window.
    • lastPushedByTarget and servedWindows.latest are used only for legacy subscriptions.
  • SDK. sdk.threads.timeline takes afterTag. It is typed to return a full window unless afterTag is given, so the CLI, status, and plugin callers are unchanged. Plugin SDK bumped to 0.6.85, above main's 0.6.84, because the bundled types changed.

  • Documented in docs/timeline-pagination.md under "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:

  • Old client, new server. Pushes keep afterSequence: null, so an old client treats a pushed delta as unusable and refetches. Its afterSequence query is no longer read, so it gets full windows. That is correct but large until the tab reloads. The timeline push path is behind the timelinePush experiment.
  • New client, old server. The lenient signal schema maps an untagged push to "unreadable", and the client refetches. The old server ignores afterTag and returns full windows. It also strips timelineTags from subscribe messages: the field is on the message, not in the strict target schema, so the subscription is kept and treated as legacy.
  • Subscriptions. A subscription without 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 of null means "tag-aware, nothing held yet": no pushes until a tag arrives. A string means "holds this window".

Why a null subscriber can safely get no pushes: read() builds the window and records it in servedWindows in 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 next schedulePush timer, at most MAX_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_VERSION is 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 with deferContent, 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.

Scenario #6208 (before) This PR (after)
Open running thread: first push (default + compact) 40.7KB + 18.7KB 1.1KB + 1.5KB
Open running thread: median push (default / compact) 11.6KB / 13.4KB 1.2KB / 1.6KB
Open running thread: WS total 420.1KB 42.5KB
Return after >5s hidden: resume GET (default + compact) 41.6KB + 19.6KB 2.0KB + 2.4KB
Return after >5s hidden: first push after resume 40.9KB + 18.9KB 1.2KB + 1.6KB
Return after >5s hidden: WS / HTTP total 495.1KB / 578.1KB 53.8KB / 521.3KB
Open idle thread, then a turn starts: first push 422.4KB + 94.8KB full 0.5KB + 0.9KB delta
Open idle thread, then a turn starts: WS total 1157.2KB 64.9KB
All 86 pushes: p50 / p90 / max 13.4KB / 41.3KB / 422.4KB 1.6KB / 2.7KB / 8.0KB

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):

Before tag-aware subscriptions With tag-aware subscriptions
Push before the GET is served (default + compact) 426.0KB + 98.4KB full none
First push after the GET 1.6KB + 2.0KB delta 1.6KB + 2.0KB delta
WS total 564.3KB 40.0KB
HTTP total (both initial GETs are full) 524.1KB 524.1KB
WS + HTTP 1088.4KB 564.1KB

#6208's thread storage was archived, so I rebuilt the harness database read-only from ~/.bb/bb.db. It holds thr_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 contextWindowUsage changes; it is resent whole.

Tests:

  • packages/server-contract/test/thread-timeline-delta.test.ts:
    • Deltas round-trip exactly through appends, removals, inserts and moves, including 300 seeded random edit steps.
    • Only changed top-level fields and timelinePage keys are sent, and cleared fields are removed.
    • A wrong afterTag, out-of-range ranges and unplaced upserts are refused.
    • A locally appended optimistic row still applies.
    • Both field lists cover their schemas, and untagged pushes from old servers parse as unreadable.
  • apps/server/test/public/public-thread-timeline-delta.test.ts:
    • HTTP deltas equal fresh GETs: appends, turn collapse, interleaved clients and eviction, streaming, compaction, no-op.
    • An idle-built window gets an exact delta to the active window at the same maxSeq.
    • Unknown tags and pre-tag afterSequence reads get the full window.
  • apps/server/test/public/public-thread-timeline-push.test.ts:
    • Pushes are deltas from the fetched window.
    • A client that fetched while idle gets a delta once the turn starts.
    • Two subscribers holding the idle- and active-built windows of one sequence: one applies the push, the other refetches an exact HTTP delta.
    • Resume after a dropped or hidden socket, and deltas after a history rewrite.
    • Tag-aware subscriptions, through the real client message parser:
      • No push while the subscriber has no tag. When an event lands between the GET and the tag, the tag brings a delta against the GET's window, and later pushes follow on from it.
      • No push when the GET already holds the latest change.
      • A stale tag gets an immediate delta, and an unknown tag gets the full window.
      • Subscribers holding the same window share one signal, legacy included. Subscribers holding different tags get their own deltas.
      • A hidden then resumed subscriber gets a delta against the tag it held.
  • apps/server/test/app/client-protocol.test.ts: timelineTags sets 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:
    • A subscription sends null, then the GET's tag once.
    • A pushed tag counts as known, and is resent on reconnect.
    • The tag is forgotten when the last subscriber leaves.
  • 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 same maxSeq with a different tag. Unreadable pushes refetch, and stale or foreign pushes are ignored. Each fetched window's tag is reported to the subscription.
  • After tag-aware subscriptions: turbo run typecheck --filter='...[origin/main]' passes (98 packages). Server test/app, the timeline push, delta and scrollback tests, services/threads and turn-trace pass (502 tests). App src/lib, src/hooks and timeline tests pass (2133), and so does @bb/server-contract (85). @bb/app lint passes.
  • Before tag-aware subscriptions, pnpm exec turbo run test passed for @bb/server (3686 tests; the one failure in the full run was plugin-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/cli and @bb/demo-server.
  • pnpm exec turbo run typecheck passes for those packages and bb-plugin-side-chat. @bb/app lint and oxfmt --check pass on the changed files. check-plugin-sdk-version.mjs passes.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael changed the base branch from bb/avoid-full-timeline-push-after-resubscribe-thr_kigfsdgsy7 to main October 24, 2026 05:10
ymichael and others added 7 commits October 26, 2026 13:46
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]>
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]>
@ymichael
ymichael force-pushed the bb/shrink-timeline-pushes-and-idle-to-active-delta-thr_h9yeqibab5 branch from 2262c26 to 2d1d1cb Compare October 26, 2026 20:48
@ymichael
ymichael merged commit 4d0a8cd into main Oct 26, 2026
95 of 96 checks passed
@ymichael
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]>
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