Skip to content

Push a timeline delta instead of a full window after resubscribing - #6208

Closed
ymichael wants to merge 1 commit into
mainfrom
bb/avoid-full-timeline-push-after-resubscribe-thr_kigfsdgsy7
Closed

ymichael wants to merge 1 commit into
mainfrom
bb/avoid-full-timeline-push-after-resubscribe-thr_kigfsdgsy7

Conversation

@ymichael

@ymichael ymichael commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

thread-timeline-windows.ts keeps the last push per subscription target object in a WeakMap. The hub creates a new target object whenever a key goes from unwatched to watched: hub.subscribe, setClientVisible(true) after the client drops its watches (5s hidden), and WebSocket reconnects. A new target has no entry, so its first push sent afterSequence: null with the whole window, even though the client had just refetched over HTTP on resume. In production logs for one thread this came to about 420KB (default window) plus about 125KB (compact segmentLimit: 8 window) each time the thread was opened or returned to, where the deltas right after were about 18KB. Over a bb connect tunnel that blocks the socket and keeps "Loading latest messages…" on screen longer.

What changed

  • Server (thread-timeline-windows.ts): if a target has no previous push, the push now uses the most recent rows the server delivered for the same params key as its baseline (new latestRowsCache.latest()), and sends a delta with that afterSequence. Pushes are also recorded in latestRowsCache, so the client's resume refetch (afterSequence = last pushed maxSeq) can be an HTTP delta too and not a full response. A baseline at or below the history-rewrite delta floor is never used, which matches the read path, so a rewrite or compaction still forces a full push.
  • Client (thread-timeline-push-owner.ts): a pushed delta is applied only when the cached maxSeq equals afterSequence. If it doesn't match, the client refetches instead (an HTTP delta). Before, a client already past the base would apply a delta computed against rows it didn't have. With baselines that can now come from another reader, an exact match is required.
  • No wire-format change. Rows are fixed by (params key, maxSeq) within a delta floor; timelineCache already relies on this.

How you verified

  • apps/server/test/public/public-thread-timeline-push.test.ts:

    • Updated: fetch-then-subscribe now gets deltas starting from the fetched window. A dropped socket that resubscribes gets a delta from the window it last received, and that delta applies to equal a fresh GET.
    • New: a client that is hidden then made visible gets an HTTP delta on refetch, then a socket delta.
    • New: after history-rewritten, the push is still full, even when a GET has served the rewritten window at the floor sequence.
    • All four fail on the old server code. The rewrite test fails when the floor guard is removed.
  • apps/app/src/hooks/queries/thread-timeline-push.test.tsx: a delta applies at its exact base, and a client past the base refetches.

  • Real-thread measurement. I extracted the rows for one production thread (thr_iegshhdusf, 2572 events, the thread from the logs) into a fresh migrated DB. Then I ran the real server app (hub and HTTP routes) on it through the client's sequence: subscribe to the default and compact (segmentLimit: 8) windows with deferContent, GET, then replay the last turn's real events one at a time. The same harness ran against main's server code and this branch. On every run, the client's applied rows matched a fresh GET.

    Scenario First push after subscribing (default + compact) WS total HTTP total
    Open a running thread: main 426.0KB + 98.3KB full 885KB 523KB
    Open a running thread: branch 40.7KB + 18.7KB delta 420KB 523KB
    Return after >5s hidden: main resume GET 426.9KB + 99.3KB full, then push 427.6KB + 100.0KB full 1422KB 1043KB
    Return after >5s hidden: branch resume GET 41.6KB + 19.6KB delta, then push 40.9KB + 18.9KB delta 495KB 578KB
    Open an idle thread, then a turn starts: both 422.4KB + 94.8KB full (unchanged) 1157KB 517KB

    Pushes after the first one are the same on both (10–42KB each).

    Not fixed here: the last row. Thread status is part of the window's params key, and rows built while idle differ from rows built while active at the same sequence (timeline.ts passes thread.status into the projection). So an idle-built fetch can't safely be the baseline once a turn starts. Fixing that needs a way to tell those rows apart, or a push on status change.

  • pnpm exec turbo run test --filter=@bb/server -- <push, scrollback, turn-trace tests>, app thread-timeline-push + realtime-cache-effects tests, and turbo run typecheck lint --filter=@bb/server --filter=@bb/app all pass.

AGENT GENERATED

🤖 Generated with Claude Code

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]>
@ymichael

Copy link
Copy Markdown
Collaborator Author

Closing in favour of #6220, which includes this change. #6220 is built on this branch, rewrites the same five files, and replaces the sequence-number baselines with content tags. It now targets main.

@ymichael ymichael closed this Oct 24, 2026
ymichael added a commit that referenced this pull request Oct 26, 2026
## 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](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: review <review@local>
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