Skip to content

Fix timeline pagination with snapshot-bound conversation groups - #3325

Merged
ymichael merged 6 commits into
mainfrom
bb/timeline-pagination-correctness
Sep 10, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/timeline-pagination-correctness

Conversation

@ymichael

@ymichael ymichael commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Timeline pages grouped independent event/byte windows and assigned fragment IDs. The client merged by row ID, so boundaries could change accepted messages to pending, fragment turns, and lose or duplicate content. Reproduced on main before implementation: three of four large copied-corpus walks disagreed with canonical history.

What changed

Select conversation groups using existing anchors, load their full turn/delegation context, and filter context-only groups out of page ownership. Oversized groups paginate canonical children under stable summary IDs; the client and CLI recursively merge those children. The existing detail endpoint and SDK now support continuation cursors, and the app walks them on expansion.

Opaque cursors bind the history tip, grouping version, status, and display surface. Appends stay outside an existing walk. Pagination continues on a best-effort basis across history edits and suffix replacement: pages loaded before and after an edit may disagree until history is reloaded. A new latest snapshot replaces loaded history because late events can change earlier grouping. Cursors whose anchor event was deleted return HTTP 400, preserving main's behavior. Existing message-edit notifications invalidate request and grouping-context caches. There is no new database table, migration, event trigger or daemon wire change. Main's large-output sidecars remain intact; no rejected streaming-projection code was used.

How you verified

  • Actual Hono endpoint plus actual client merge matched complete canonical content/order on four copied threads: 63,853, 42,033, 32,384, and 22,940 events. The oracle removes one exactly duplicated canonical delegation row in the fourth thread; it does not discard differing content with the same ID.
  • Tiny event/512-byte targets, huge turns/details, nested/late events, straddling items, appends between requests, continuation after in-place edits, same-sequence suffix replacement, rejection of deleted anchors, and a stale in-flight app page are covered.
  • Turbo: 158 server timeline/public-route tests, 19 client merge tests, 142 database event/migration tests, 30 app query/controller tests, 18 CLI log tests, 104 SDK tests, and 67 server-contract tests. Affected server/client/CLI/app/database/SDK/contract typechecks passed. Server tests and typechecks passed again after rebasing onto 682f0d2c5d.
  • Isolated source browser: paged to all 45 synthetic messages exactly once, expanded the oldest summary into 20 commands, and reloaded. Source CLI thread log --all --format verbose returned all 45 messages exactly once. Owned dev processes/store were cleaned up. No provider execution or mobile Safari verification is claimed. The verification inventory has an existing unrelated unmapped browser CLI family.

The initial 1.7–5.0 s walks were rejected as too slow. The optimized paired run restores main's original timeline builder, event queries and client merge from 682f0d2c5d and runs main/fixed/fixed/main per copied thread, with fresh databases and route caches. Correct walks now take 0.72–1.76 s, versus 0.68–2.15 s for main: the two largest walks are faster, and the other two are within 6%. All eight fixed walks match canonical content/order. Cold latest requests retain roughly 3 ms and 13 ms overhead on two threads; exact numbers are in the report.

The optimization scopes payload context, selects turn IDs before reading full event bodies, skips already-loaded request lookups, and uses existing selective indexes for turn, child and interruption queries. Only compact request-to-turn IDs and an ordering boundary are cached per exact snapshot; no projected rows or payloads are cached. The profile clears that cache to include its cold construction cost. New tests guard against decoding unrelated history and acceptance after a later conversation boundary. CI's missed optional-contract and old sequence-fragment expectations are now covered and pass locally.

Ordering overlap detection uses a linear scan, with six cases for accepted turns, overlapping alternatives and expired spans. A paired comparison against 51e0dc78d2 preserves canonical results but does not establish another general latency improvement. History-edit invalidation was removed in favor of the best-effort contract above; regression tests require these cursors to continue.

Full benchmark report. Pagination lifecycle and SDK contract.

AGENT GENERATED

@ymichael
ymichael marked this pull request as ready for review September 9, 2026 05:09
@ymichael

ymichael commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

@slopcop

1 similar comment
@ymichael

ymichael commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

@slopcop

@ymichael
ymichael merged commit 8d2a028 into main Sep 10, 2026
16 checks passed
@ymichael
ymichael deleted the bb/timeline-pagination-correctness branch September 10, 2026 18:15
ymichael added a commit that referenced this pull request Sep 10, 2026
## Human comments

## What was wrong

Several synchronous database paths read more event history or payload
data than their results required: filtered high-water marks aggregated
complete histories, open-turn recovery did not seek directly past
interruption boundaries, request recovery repeated scans for requests
from the same thread, and search loaded text before limiting matches.
Destroyed-environment cleanup bounded rows but could rewrite megabytes
in one batch. The timeline byte-budget helper also aggregated up to
2,001 payloads before potentially scanning them again.

## What changed

Six separate fixes:

| Issue | Fix | Before → after, ms |
|---|---|---:|
| Latest sequence for seven active threads | Seek the final indexed
event per requested thread | 5.795 → 0.007 |
| Open accepted turns | Seek past each requested thread’s latest
interruption | 1.467 → 0.216 |
| Search for `the` | Rank and limit metadata before loading result text
| 87.482 → 80.570 |
| Eight request IDs in one thread | Group request IDs so each thread
history is scanned once per batch | 21.932 → 2.926 |
| Large-event environment detachment | Cap each batch at 256 KiB,
preserving progress for oversized events and existing yields between
batches | 4.038 → 0.619 longest batch |
| Timeline byte-budget helper | Stop at the byte budget without a
preceding aggregate scan | 5.075 → 0.819 in the historical 512 KiB case
|

These are controlled warm benchmark medians from a private database
snapshot or isolated fixtures, not deployed latency measurements. The
original measurements preceded the removal of an experimental delta
index; that index remains present in the benchmark snapshot. Detachment
total work was 4.038 → 3.616 ms across 1 → 17 batches.

Rebased onto the snapshot-bound conversation-group pagination change in
#3325. The byte-budget helper now serves only turn-summary detail
expansion; main timeline pages no longer call it. A fresh comparison
against main at the caller’s 4 MiB budget returned identical results in
all six fixtures. An oversized 5,000-event window improved 2.667 → 1.717
ms, while a fitting 2,000-event window regressed 0.454 → 1.114 ms due to
JavaScript iteration. Retained the early-stop behavior with this
explicit tradeoff.

The net change has no checkpoint worker, schema/migration, server/daemon
wire, CLI, or configuration changes.

## How you verified

- Database regression coverage exercises lookup batching and query
plans, byte-budget early exit, and byte-bounded environment cleanup,
including an oversized first event.
- `pnpm exec turbo run test typecheck --filter=@bb/db`: 34 files, 481
tests passed; typecheck passed.
- `pnpm exec turbo run test --filter=@bb/server --
test/services/threads/timeline
test/services/threads/thread-runtime-display.test.ts
test/services/database-maintenance-sweep.test.ts
test/system/event-pruning.test.ts test/public/public-thread-data.test.ts
test/public/public-thread-diagnostic-events.test.ts
test/public/public-thread-timeline
test/public/public-thread-search.test.ts`: 20 files, 205 tests passed,
including the new pagination and detail-expansion cases.
- `pnpm exec turbo run build typecheck --filter=@bb/server`: passed.
- `git diff --check`: passed. Rebase range comparison confirmed
unchanged patches.
- Fresh timeline helper benchmark: migrated in-memory database, five
warmups, 31 alternating measured iterations per implementation, exact
result equality. Production was not modified or restarted; no deployed
latency or full historical corpus replay is claimed.

> AGENT GENERATED
SawyerHood added a commit that referenced this pull request Sep 15, 2026
## Human comments

## What was wrong

Since #3325, `mergeLoadedTimelineWithLatest` replaces every loaded row
whenever the latest page's `historySnapshot` changes, and the snapshot
includes `maxSeq`, so each appended event unloads all older pages. When
the previous conversation group is larger than the 1,500-event
latest-page budget, it exists only on an older page. While a thread
streams, each event removes it, the "Loading older messages" sentinel
scrolls back into view, auto-load fetches it again, and the next event
removes it again. The controller also discarded an older page still in
flight whenever the snapshot moved. Separately, a page's older cursor
used the group's first displayed row. Rows recorded after a request but
displayed above its message, such as "Provider environment resolved",
formed their own group with a higher sequence, so the first older
request re-served the current group and merging it moved that row below
the reply.

## What changed

- `packages/client-core` `mergeLoadedTimelineWithLatest`: when a new
latest snapshot reaches the loaded tip, loaded older pages stay and only
the rows the latest page covers are replaced. It still rebuilds from the
latest page when the pages do not line up, when they share no rows and
leave a gap, or when the server reports a later change to a row the page
omitted. On a cursor tie it keeps the walk's cursor.
`prependOlderTimelineRows` keeps the loaded order when an older page
repeats loaded rows.
- `useThreadTimelineController`: an in-flight older page is applied when
its request cursor is still the loaded `olderCursor`, instead of
requiring an unchanged snapshot.
- `apps/server` pagination: new `timelinePage.olderRowsSourceSeqEnd`,
the greatest `sourceSeqEnd` among rows the snapshot projected before the
page's returned rows but omitted (`null` when none). That covers older
conversation groups, owned groups a size cut left out, and the leaves a
content cut dropped from the page's oldest group, so a command that
completes before a content cut still triggers a rebuild. A row that
keeps changing before a content cut therefore rebuilds on each refresh.
Leading rows recorded after a group's message now join that group, and
its cursor is the message row.
- `packages/server-contract`: the field is optional in
`timelinePageMetadataSchema`, matching the other snapshot fields. No
daemon wire change, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged.
- `docs/timeline-pagination.md` describes the new rule. This relaxes
#3325's "a new latest snapshot replaces loaded rows" behavior for
refreshes that only append to newer rows; a later change to a row the
page omitted still replaces them.
- One #3325 assertion changed in `timeline-event-budget.test.ts`. After
a late append that sorts into the newest group, the merge must now equal
the full canonical timeline rather than the latest page alone.

## How you verified

- New client-core merge tests: a streaming refresh keeps older pages, a
tie keeps the walk cursor, a content-cut running turn keeps its head, a
group starting right after the tip appends, no overlap with a gap
rebuilds, a change to an omitted row rebuilds, and a repeated group
keeps the loaded order. 5 of these fail against main's merge code.
- New controller test: an in-flight older page applies across refreshes
that advance the snapshot, and older rows survive later refreshes.
- New server unit tests: the cursor anchors at the message row, and the
rebuild value covers context-only older groups, owned groups a size cut
left out, and rows before a content cut.
- Endpoint tests: walked history stays equal to the canonical timeline
after an append to the newest group. A late command completion reports a
rebuild both in an older group and before a content cut in the newest
group; after the rebuild and reloading older pages, the rows equal the
canonical timeline. The content-cut case fails with the previous
pagination code.
- `pnpm exec turbo run typecheck` for `@bb/server-contract`,
`@bb/client-core`, `@bb/server` and `@bb/app`, and earlier for `@bb/cli`
and `@bb/mobile`.
- `pnpm exec turbo run test` for `@bb/client-core`,
`@bb/server-contract`, `@bb/cli`, and `@bb/server --
test/services/threads test/provider-corpus test/routes`. The provider
corpus correctness walk skipped because no corpus was available.
- App Vitest run directly for `src/components/thread/timeline`,
`src/views/thread-detail` and `src/hooks/queries`, because the PWA icon
check fails in this checkout.
- Browser, isolated source instance with
`BB_FF_TIMELINE_WINDOW_EVENT_BUDGET=20` and real Claude Code turns sent
from the composer. A MutationObserver recorded whether the previous
assistant message stayed in the DOM while a follow-up streamed. With
main's client merge it left and returned 8 times within about 4 seconds,
and "Loading older messages" showed in 19 samples. With this change it
never left over a 30-second turn.
- Replayed a real affected thread's events through the server at each of
49 consecutive sequences, feeding both clients. With main's client the
previous message dropped on 49 of 49 refreshes; with this change, 0. The
rebuild value stayed `null` throughout.
- The browser check ran before rebasing onto #3591, and the replay
before the omitted-rows change. Tests and typechecks were rerun after
both.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> AGENT GENERATED

---------

Co-authored-by: Claude Code <[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