Skip to content

fix(threads): ignore agent-only timeline anchors - #3830

Closed
iamhenry wants to merge 1 commit into
get-bb:mainfrom
iamhenry:fix/agent-only-timeline-anchor
Closed

iamhenry wants to merge 1 commit into
get-bb:mainfrom
iamhenry:fix/agent-only-timeline-anchor

Conversation

@iamhenry

Copy link
Copy Markdown
Contributor

Summary

  • exclude agent-only input parts from SQL timeline segment-anchor selection
  • preserve mixed requests because any visible input part still qualifies the request
  • add an event-budget regression for a hidden workflow request accepted into an existing visible turn

Why

Timeline projection intentionally omits all-agent-only requests. Anchor selection still counted them, so an event-budget window could begin at a hidden request while the following visible assistant output remained grouped under an earlier visible anchor. Pagination then discarded every projected row and returned rows: [], hasOlderRows: true, and olderCursor: null.

The change makes anchor eligibility match user-message visibility.

Validation

  • the new regression was demonstrated failing on unmodified main: expected a non-empty latest page, received zero rows; the other 20 tests in the file passed
  • the equivalent compiled-bundle predicate restored the affected live thread from 0 to 7 rows
  • the thread event count and sequence range remained unchanged at 4,855 events, sequences 1–5,420

Relates to #3694. This PR fixes a concrete agent-only-anchor trigger; it does not claim to implement the generic anchorless fallback proposed there.

packages/db/src/data/events.ts
  - What: Exclude agent-only input parts from visible timeline anchor selection.
  - Why: Keep SQL window anchors aligned with projection visibility.

apps/server/test/services/threads/timeline-event-budget.test.ts
  - What: Cover a hidden workflow request accepted into an existing visible turn.
  - Why: Prevent latest pages from collapsing to zero rows at the event-budget boundary.
@github-actions

Copy link
Copy Markdown
Contributor

Thanks @iamhenry for the PR. This repo needs approval before a PR. Join the #contributors channel in Discord (https://discord.gg/kvBU6tJhcJ) and explain what you want to open a PR for and why. A maintainer then adds you to the allow list. This PR now closes on its own. Reopen it or open a new one after approval.

@github-actions github-actions Bot closed this Sep 17, 2026
ymichael added a commit that referenced this pull request Sep 17, 2026
)

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

```sh
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

---------

Co-authored-by: Claude Opus 5 (1M context) <[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