Skip to content

perf(native-chat): bound retained items on the structured session path - #19841

Merged
nwparker merged 1 commit into
mainfrom
nwparker/perf-followups-structured-items
Sep 10, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/perf-followups-structured-items

Conversation

@nwparker

@nwparker nwparker commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​152 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​152
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​27 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​21

ELI5

Chat history in a long agent session was a bucket with no lid. Every new message got added and nothing ever came out, so a session you left running all day kept piling up messages in memory even though you could only see the last screenful.

The message list already had a lid (256). The message bubbles did not. This puts a lid on the bubbles too: keep the newest 1024, and if we drop older ones, mark the session as "has older" so scrolling up fetches them straight back from the server. Nothing is lost — it just isn't held in memory until you ask for it.

If you do scroll up, the lid gets raised to whatever you paged in, so a new incoming message can't yank the history you just loaded back out from under you.

What changed

src/shared/structured-agent-session-reducer.ts:

  • New MAX_RETAINED_ITEMS = 1024 and a retainedItemLimit field on the reducer state.
  • The live-batch merge head-trims items to that limit, and sets hasOlder: true whenever it trims, so trimmed items stay reachable through the existing oldestStructuredAgentSessionCursor → agentSession.history direction: 'before' path that both the renderer (structured-agent-session-read-owner.ts) and mobile (use-mobile-structured-agent-state.ts) already use.
  • older-page raises retainedItemLimit to the merged length, so paging back widens the retained window rather than being undone by the next live batch. This mirrors the live path's growing limitRef (use-native-chat-live-session.ts, NATIVE_CHAT_INITIAL_LIMIT 300 + NATIVE_CHAT_PAGE 200).
  • Snapshot/reset/tail-page reset the limit to max(MAX_RETAINED_ITEMS, page.items.length).

The cap sits well above the renderer's 300-item initial read window plus a page, so ordinary sessions never trim.

Why 1024 and not a smaller number

The renderer restores up to NATIVE_CHAT_INITIAL_LIMIT (300) items on hydration and pages 200 at a time. Any cap at or below that would fight the restore loop on every session. 1024 leaves headroom for several pages before the first trim.

Trade-offs (negative, user-facing)

  • A very long live session that is then scrolled all the way up re-fetches trimmed items over the wire instead of finding them in memory. That is one agentSession.history round trip per page, on a path that already exists and is already exercised (hasOlder was already true for any session longer than one page). Over SSH/relay this is a real request, not a local read.
  • Identity churn: once past the cap, every live batch produces a new items array (it did before too, since mergeItems already rebuilt it) and a new head element, so a consumer memoizing on items[0] sees it change more often. No such consumer exists today.

Testing

  • New src/shared/structured-agent-session-item-retention.test.ts (5 tests): the cap binds on a long live session; hasOlder + the older-page cursor stay correct after a trim; a session under the cap is untouched; paging older widens the window and a following live batch slides it instead of collapsing it; no-journal-change batches still preserve items reference identity.
  • Verified the three cap-specific tests fail against origin/main's reducer and pass against this one.
  • pnpm test src/shared/structured-agent-session src/renderer/src/components/native-chat mobile/src/session — 134 files, 1336 tests, all pass.
  • pnpm tc clean; pnpm run check:code-quality:changed — 0 new findings.

Wire compatibility

None. retainedItemLimit is client-side reducer state; no RPC params, stream frames, or published content change.

`mergeSubmissions` caps submissions at 256, but `mergeItems` had no
equivalent bound, so `state.items` grew for the whole life of a long
structured session while the live path caps itself to its read window.

Head-trim `items` to a retained-item limit when a live batch merges, and
set `hasOlder` so anything trimmed is still reachable by paging. Paging
older raises the limit to what the page produced, so a live batch slides
the widened window instead of collapsing it back to the cap -- the same
shape as the live path's growing `limitRef`.
@coderabbitai

coderabbitai Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: a6734b62-f6bd-4269-b5dc-158b98227548

📥 Commits

Reviewing files that changed from the base of the PR and between 4b4acf2 and 7ffb660.

📒 Files selected for processing (2)
  • src/shared/structured-agent-session-item-retention.test.ts
  • src/shared/structured-agent-session-reducer.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The structured session reducer now tracks a retained-item limit. It caps live session items at 1024 by default, preserves hasOlder when older items are trimmed, and exposes the retained-item cursor for paging. Loading older pages expands the limit to preserve the wider window. New tests cover capped sessions, paging, under-cap sessions, expanded windows, and empty-batch item identity.

Merge Risk: ⚪ Minimal · up to 7ffb6

Long-running structured sessions now retain a bounded recent item window while older history remains pageable. The covered retention and paging behaviors introduce no outstanding merge-readiness risk.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, motivation, trade-offs, compatibility impact, and testing. However, the required Linked Issue is empty, the required Visual Proof section does not contain N/A or a… Add a valid issue reference after “Fixes #”. For this non-visual behavior change, add “N/A” with a brief reason under Visual Proof. Complete the applicable Testing, Review, Agent skill upstream boundary, Notes, and Checklist items, or expla…
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: bounding retained items in the structured session path.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description explains the change, motivation, trade-offs, compatibility impact, and testing. However, the required Linked Issue is empty, the required Visual Proof section does not contain N/A or attachments, and the required checklist items remain unchecked.

Resolution

Add a valid issue reference after “Fixes #”. For this non-visual behavior change, add “N/A” with a brief reason under Visual Proof. Complete the applicable Testing, Review, Agent skill upstream boundary, Notes, and Checklist items, or explain why they do not apply.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

A single commit that bounds the number of retained items on the structured agent session path, stopping unbounded in-memory growth on long live sessions while keeping trimmed history reachable through the existing older-page cursor.

  • retainedItemLimit state field — a head-trim floor seeded from MAX_RETAINED_ITEMS (1024), reset on snapshot/tail-page, and raised by older-page so paging back widens the retained window instead of being undone by the next live batch.
  • Live-batch head-trim — trimRetainedItems slices to the limit and sets hasOlder: true whenever it drops items, so trimmed history stays reachable via oldestStructuredAgentSessionCursor → direction: 'before'.
  • Retention tests — five tests covering the cap, hasOlder/cursor correctness after a trim, under-cap passthrough, window widening + live-batch sliding, and reference-identity stability on no-journal-change batches.

I verified the trim stays consistent with the existing paging path: oldestStructuredAgentSessionCursor returns items[0] (the oldest retained item), and before paging is exclusive of the cursor sequence, so trimmed items are fetched back without gaps or duplicates. The cap (1024) sits above the renderer's 300-item restore window plus several 200-item pages, and StructuredAgentSessionState is in-memory only, so there is no wire or schema impact. The three cap-specific tests use exact assertions and genuinely fail against the un-capped reducer.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 0b60b0d into main Sep 10, 2026
29 checks passed
@nwparker
nwparker deleted the nwparker/perf-followups-structured-items branch September 10, 2026 05:12
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