Skip to content

Make timeline pagination own event windows and share row planning - #3817

Merged
ymichael merged 6 commits into
mainfrom
bb/explain-issue-3694-thr_e3rd9ikqbz
Sep 17, 2026
Merged

ymichael merged 6 commits into
mainfrom
bb/explain-issue-3694-thr_e3rd9ikqbz

Conversation

@ymichael

@ymichael ymichael commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • A page owns [start, end) and returns rows whose sourceSeqStart is 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.
  • Cursors preserve exact window ownership and snapshot/display settings. Empty windows advance, with up to eight skipped per build, and older history always has a usable cursor. Content continuation stays inside the same window, including window start zero at the history epoch; HTTP query and both cursor metadata schemas accept that zero consistently. Projection and database ordering share the completed-turn boundary rule; late background events do not extend a completed turn.
  • One structural row plan decides summary identity, bounds, counts, timing and message membership for both collapsed rendering and expansion. Expansion selects its summary before rendering children. Tool-output buffering and delegation projection retain their original eager behavior; the experimental output queue and lazy delegation machinery from c2a5063a41 have been removed.
  • Response assembly emits each row identity once, fixing an identical duplicated delegation subtree found in the whole-database comparison. Client merging reuses unchanged delta rows and summary objects while preserving recursive deduplication and partially loaded history.
  • Cursor format is v3; older cursors use the existing HTTP 400/reload path. Existing public SDK/CLI fields remain. No database migration, new index or server/daemon protocol change. docs/timeline-pagination.md documents 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.

  • After removal: 405 thread-view correctness tests and 70 server pagination, in-turn/detail and public timeline tests. Earlier branch verification passed the broader 228 server tests, 576 DB tests and 294 client-core tests.
  • Thread-view, server, server-contract and provider-parity typechecks; earlier branch DB/client-core typechecks. Scoped changed-test lint and whitespace checks pass. Linting the contract source reports 28 pre-existing forbidden comments; this change adds none.
  • Isolated source-app Chrome checks: older-page loading, summary/command expansion, complete dense tool output, and appended request/tool/assistant updates retaining older history and scroll position. Earlier branch checks also covered hidden input and the source CLI full-history walk. HTTP refetches exercised the real query/delta merge path; this does not claim websocket delivery or iOS Safari coverage.

Commands included:

pnpm exec turbo run test typecheck --filter=@bb/thread-view
pnpm exec turbo run test --filter=@bb/server -- test/services/threads/timeline- test/public/public-thread-timeline test/public/public-thread-data.test.ts test/provider-corpus/timeline-perf.test.ts
pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/provider-parity

A fresh consistent main-database snapshot contained 2,380 threads / 2,457,953 events. The retained all-thread comparison was PR commit c34764c4ea versus c2a5063a41, 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 c2a5063a41 equals 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 at c2a5063a41. 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.

Request Before p50 After p50 Before p95 After p95
Cold open 12.78 ms 12.76 ms 34.01 ms 33.66 ms
Cached open 0.34 ms 0.34 ms 1.39 ms 1.38 ms
Unchanged delta 0.27 ms 0.27 ms 1.10 ms 1.13 ms
Appended update 9.80 ms 9.81 ms 25.51 ms 25.65 ms

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: true cutoff.

Known limitation found during review: two other summary-detail requests in thr_kbjzy5zdu7 return 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

AGENT GENERATED

ymichael and others added 3 commits September 16, 2026 19:02
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]>
@ymichael ymichael changed the title Own timeline pages by their selected window and share one turn-boundary rule Fix timeline pagination with window ownership and indexed request hints Sep 17, 2026
@ymichael ymichael changed the title Fix timeline pagination with window ownership and indexed request hints Make timeline pagination own event windows and defer hidden details Sep 17, 2026
@ymichael ymichael changed the title Make timeline pagination own event windows and defer hidden details Make timeline pagination own event windows and share row planning Sep 17, 2026
@ymichael
ymichael merged commit 0188d91 into main Sep 17, 2026
16 checks passed
@ymichael
ymichael deleted the bb/explain-issue-3694-thr_e3rd9ikqbz branch September 17, 2026 21:18
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
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.

Timeline returns 0 rows with olderCursor: null when the window has no user-message anchor, leaving the thread permanently blank

1 participant