Repository navigation
Make timeline pagination own event windows and share row planning - #3817
Merged
Merged
Conversation
Timeline pagination defined "segment anchor" twice. The window start came from timelineSegmentAnchorConditions in SQL, while segment selection re-derived anchors from row shape in isTimelineSegmentAnchorRow. The two disagreed: a steer whose expected turn did not match projected as a message-kind user row without being a SQL anchor, a context clear was a SQL anchor only when contextBoundarySeq was set, and the non-empty input requirement existed only in SQL. When a window contained no row the TypeScript side accepted, every segment failed the ownership filter and the page bailed with rows: [] and a hard-coded null cursor while knownHasOlderSegments reported older history, leaving the thread blank and the client polling a cursor it could never request. listTimelineSegmentAnchorSequences returns the anchor sequences for a window from the same SQL predicate that chooses its start. The selection computes them for its own window and paginateTimelineRows matches segments on sequence, so isTimelineSegmentAnchorRow is gone. Ownership filtering now falls back to the leading partial segment instead of discarding everything, and the remaining empty-rows branch reports hasOlderRows false, making hasOlderRows true with a null cursor unrepresentable. Verification: three new pagination tests, all of which fail on the previous code with the reported empty-rows response. Building both revisions against identical snapshots of a 5 GB store returned identical pages for 457 of 462 threads over 1,000 events; the five that moved are segment boundaries, two of which previously anchored a page on a client/turn/rejected event. Paging 40 of those threads back to their first event terminated every time with strictly decreasing cursors. Fixes #3694 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ry rule Pagination chose a raw event window in SQL and then decided which rendered rows belonged to the page by inspecting the rows: it looked for rows whose source sequence matched a boundary, took the page cursor from whichever row it found, and discarded rows it could not attach. Rendered rows do not have to line up with the raw window. An accepted steer renders at its acceptance sequence, context loaded for grouping renders rows from outside the window, and a content cut reconstructed a different group on the next request. Those mismatches produced the blank thread in #3694, skipped and looped cursors, lost rows, and duplicated summaries. A page now owns exactly the rendered rows whose source sequence falls inside its window, in display order. Boundaries inside the window group rows for the segment limit without matching any row. The cursor is the window start, so a walk visits contiguous windows with strictly decreasing cursors, content cuts continue inside the same bounds, and older history is only advertised with a cursor. Boundaries sit where input enters the conversation: a steer accepted into its expected turn is bounded at its acceptance, everything else at its request. Anchor lookup is three indexed range queries resolved in TypeScript. The cursor format is v2 so stale cursors fail cleanly. Display order and completed-turn grouping had three definitions of "a user message landed inside another turn": the projection measured a turn by its last loaded event, the server recomputed it from loaded events, and the database-wide version used lifecycle rows only. A budgeted page therefore ordered and grouped rows differently from the full history. One rule now lives in thread-view and both the projection and the server use it: a turn spans from its first event to turn/completed, or stays open while running. The ordering-boundary query no longer shares the pagination predicate, so counting steers as page boundaries does not change display order. Verification: every thread in a production snapshot (2,363) walked page by page at segment limits 20 and 8 and compared to an unpaginated render. Before: 2,357 and 2,355 matched, two failed with the #3694 response. After: 2,362 at both limits; the remaining thread renders a resumed delegation row twice in the full history and the client dedups it. 49 full renders changed, all where a background command finished after its turn completed and the old rule stretched the turn over later user messages. Latest-page latency is unchanged at the median with the anchor queries at parity on the largest thread. Fixes #3694 Co-Authored-By: Claude Fable 5.1 <[email protected]>
This was referenced Sep 17, 2026
ymichael
added a commit
that referenced
this pull request
Sep 17, 2026
## Human comments ## What was wrong Bounded event-type queries in `listStoredEventRows` could use the thread/sequence index and filter by type, despite an existing thread/type/sequence index. A measured default timeline request executed six such context queries over 110,630 event rows. Even a query returning no rejected inputs took about 54 ms. ## What changed Select the existing `events_thread_type_sequence_idx` for typed queries, retaining the planner-selected path for unfiltered queries. Use the existing SQL field projection helper for Drizzle's indexed table expression. Ordering, bounds, type deduplication, limits and returned fields are preserved. No new index, migration, public API or daemon protocol change. This is the first independent performance follow-up to #3817. It does not change conversation-context bounds or detail reconstruction. ## How you verified - Added the missing lower-bound case to the migrated SQLite query-plan regression. It fails before the change and passes after it. - `pnpm exec turbo run test typecheck --filter=@bb/db`: 577 tests and typecheck pass, including event query ordering/bounds behavior. - Compared default HTTP route cold opens, cached opens and unchanged deltas for all 2,385 threads in a consistent read-only main-database snapshot: all payload hashes match before/after. One deleted-thread 404 is unchanged. One warmup and three measured rounds per thread; nine initially flagged cold requests were rechecked with nine samples, followed by a reverse-order 15-sample confirmation for the remaining flag. No cold regression remained above both 10% and 5 ms. - The slow context-heavy request fell from 456 ms to 118 ms in the census and 448 ms to 100 ms in the final confirmation. This includes route execution, serialization and response parsing, but excludes network/browser time; cold clears application caches, not disk caches. The broad census ran versions sequentially and the host was shared, so small distribution changes are not claimed as stable speedups. > AGENT GENERATED
This was referenced Nov 17, 2026
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
Timeline pagination coupled raw event-window selection to finding a matching visible user-message anchor. Windows inside an existing conversation or at hidden input could discard visible output and advertise older history without a usable cursor (#3694 and the agent-only trigger in #3830). Context loading could change ownership, and inconsistent turn boundaries made pages disagree with whole-history rendering. Resolving exact anchors also introduced a request-ID fallback that scanned the thread's request history. Collapsed summaries and expansion followed separate row-construction paths with duplicated grouping and summary-building logic.
What changed
[start, end)and returns rows whosesourceSeqStartis inside it. Context helps reconstruct those rows without changing ownership. Indexed request positions are cheap selection hints; visible user rows define segments after projection. Segments guide page size, while window edges can be partial. The exact-anchor queries and full-history request-ID fallback are removed.c2a5063a41have been removed.docs/timeline-pagination.mddocuments the final ownership, planning, materialization and merge contracts.This separates page ownership, grouping and rendering without replacing the event log. Queries still read and decode the required context. A huge collapsed turn is therefore not a constant-time lookup. The existing context-loading rules, caches and snapshot-aware client merge safeguards remain; this PR does not introduce persisted projections or a metadata-only storage index.
How you verified
Regression coverage includes arbitrary/anchorless windows, hidden/empty/mixed requests, accepted steers, empty-window progress, content continuation, late background events, duplicate identities and unchanged/changed client deltas. A real migrated SQLite scale test covers indexed hints at 1,000 and 30,000 requests. Row-plan tests verify that a 10,000-output-delta turn has identical collapsed/expanded summary metadata and that expansion returns exactly the selected nested summary from a projection containing multiple turns.
Commands included:
A fresh consistent main-database snapshot contained 2,380 threads / 2,457,953 events. The retained all-thread comparison was PR commit
c34764c4eaversusc2a5063a41, which still included the subsequently removed deferral experiment. That baseline already contains the pagination correctness fix and client delta optimization. These are historical measurements of that experiment, not fresh measurements of the current branch. No new performance measurements were run after removing deferral.All complete page walks at segment limits 8 and 20 matched before/after. Every collapsed whole-history result at
c2a5063a41equals both walks. Complete nested content also matched, except that one identical duplicated root subtree is now returned once; explicitly deduplicating the baseline yields exactly the nested result atc2a5063a41. No remaining whole-history/builder-page-walk exceptions, cursor loops or builder errors. These builder walks did not exercise HTTP cursor validation; the subsequent archived-thread route review caught that coverage gap. Production data was read only; append checks used rolled-back transactions on a private copy.Actual default-route benchmark: every thread, default query flags and persisted settings (2,161 collapsed / 218 flat / one expected deleted-thread 404). Four alternating rounds per thread, one warmup plus three measured samples. Timings include route execution, serialization and response parsing, excluding network/browser rendering. Cold means application caches cleared, not cold OS/disk caches. All cold/cached/delta payloads matched before/after, and all 14,274 measured appended-update comparisons matched fresh full responses.
Total request latency is effectively unchanged. Repeated all 27 flagged threads with nine measured samples in a fresh process: no regression remained above both 10% and 5 ms. Explicit nested latest requests on the 20 largest histories and detail requests on the 19 with a latest summary also matched before/after, with no regression above that threshold (seven measured samples each).
Browser through visible rendering: three independent cold thread opens per version/family in isolated source-dev Chrome. Click-to-visible medians were 356 → 373 ms for roughly 6,000-event histories and 268 → 285 ms for dense 20,013-event completed turns; ranges overlapped substantially. This small local sample demonstrates no visible-load speedup. These shared-host measurements are not production latency guarantees. The prior 99% figure concerned isolated unchanged-delta client merging in the earlier branch change, not total request/rendering time.
After removing deferral, the shared row plan and duplicate-row fix remain. Thread-view correctness tests, relevant server timeline/detail tests, typechecks and scoped lint were rerun; the whole-database benchmark and browser measurements were not rerun. New performance work is paused while the missing component measurements are scoped.
An audit of existing browser server logs recovered one concrete default-request breakdown: for a dense 20,013-event collapsed fixture, the before build averaged 96.05 ms in selection/context loading, 44.36 ms in decoding, 17.53 ms in projection and under 0.5 ms in pagination/compaction (158.40 ms total, three opens). These are synthetic-fixture build timings, not the cost distribution of all real threads. Projection does not separately identify output buffering, grouping or allocations.
A subsequent independent review found an HTTP contract regression at the oldest window: the branch issued cursor sequence zero but the route and public response schemas required positive values. All three public surfaces now accept zero. A new migrated SQLite HTTP regression fails before the fix and passes after it; 79 server-contract tests and the server/server-contract typechecks pass.
Replayed the nine reviewed archived threads through the real Hono routes on a read-only database snapshot: 315 pages, zero HTTP/schema failures, and all nine complete nested payloads exactly match whole-history rendering after normalizing route output truncation. The six reportedly missing assistant IDs are nested in summaries, have identical text to 0.43.1, and their detail requests succeed. The additional 2,646 unique roots in the largest reviewed thread are older history recovered beyond the release walk's saved
deadEnd: truecutoff.Known limitation found during review: two other summary-detail requests in
thr_kbjzy5zdu7return HTTP 500 on both this branch and 0.43.1, using each version's own returned summary ranges. Nested timeline walks contain the content correctly, but detail context selection reconstructs different summary bounds. This pre-existing issue remains unresolved; the page-walk checks do not establish exhaustive expansion correctness. No new performance measurements were collected during this review.Fixes #3694