Skip to content

Stop repeated row walks while chat text streams - #49422

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/chat-streaming-scan-fixes
Nov 26, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/chat-streaming-scan-fixes

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

While a chat streams, a few places were walking the whole list of rows again for every small update, even when only one row had changed. This PR makes those places touch only the row that changed. What you see in the chat stays the same.

Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​7 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​6
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​92 $\color{#cf222e}{\Huge{\mathbf{−}}}$​38 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​54

What Changed

  • Hidden chat window (STA-18484): a minimized or hidden chat holds streamed batches until it's shown again. Each new batch used to rebuild the whole held set, so N held batches cost about N²/2 row visits. Held rows and submissions now live in maps that are only written to, and the list is built once when the batch is drawn. A single held batch is emitted unchanged, as before.
  • Streaming thought inside a work run (STA-18485): the slot index now stores each member's position in its run, so the patch no longer runs indexOf. The patched run also records which positions changed since the run was laid out, so the run's reader takes the direct path instead of walking every member. Before, the reader missed that path on every window.
  • New transcript base (STA-18487): when the rows being drawn are the saved rows themselves, or are the same list as the last window, the patch now returns at once instead of comparing every row with itself.
  • Snapshot on a session with no live stream (STA-18488): the row-ID set used to scope live text is now built only when a live source actually asks for it. An inactive session no longer builds it.

Why

These are mechanical fixes. Each keeps the existing data flow and output and removes the repeated full walk. No comparable: mechanical.

Linked Issue

Fixes STA-18484, STA-18485, STA-18487, STA-18488. STA-18486 was looked at and isn't fixed here: the fix needs a new viewer-interest field on the wire (see the ticket comment).

Visual Proof

N/A: no visual or interaction change. Only the internal work per update changed.

Testing

Bench on the exact paths: a throwaway vitest bench run on Linux, first on main and then with this change. The four changed files have no diff between the bench base and this head.

Path main this PR
Hidden viewer, 1,024 held one-row batches 20.6 ms 1.6 ms
Hidden viewer, 10,240 held one-row batches 1,968.8 ms 7.7 ms
Work run of 2,000 members, 10 streamed windows: reader takes the direct path 0/10 10/10
1,000-row new base compared with itself (row reads) 2,000 0
200-row snapshot with no live stream (row reads for the ID set) 200 0
  • Existing tests pass: streamed-slots performance, work-run performance, coalescer held-text, and subscriber live-text/live-growth (29 tests).

  • The streamed-slots perf contract now asserts that the run records the streamed member's position. It fails without the fix.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • Every added test fails without this change and avoids the test anti-patterns

Performance

This removes work and adds none. Per held batch the cost goes from O(held rows) to O(rows in that batch). Per streamed window in a work run it goes from three passes over the run to one copy. The new-base self-compare and the inactive-snapshot ID set are skipped entirely.

Risk

The riskiest part is the held-batch merge: if the order or revision rules were wrong, a chat shown again after being hidden could draw an older row revision. The maps keep the same insertion order and the same rule that an older revision never wins, and header fields merge exactly as before. Phones and older hosts see no wire change. Backing out is a plain revert.

Level: Low

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

- Hidden viewers keep held rows keyed once instead of rebuilding them on every push (STA-18484)
- A streaming thought inside a work run records its position, so the run doesn't rescan its members (STA-18485)
- A fresh transcript base no longer compares its rows with themselves (STA-18487)
- A snapshot builds its row-ID set only if a live sink asks for it (STA-18488)
@brennanb2025
brennanb2025 force-pushed the brennanb2025/chat-streaming-scan-fixes branch from 4550b52 to 26b5628 Compare November 26, 2026 02:23
@brennanb2025

brennanb2025 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Perf scan: PR #49422 at 26b5628

Verdict: PASS. No blocking perf findings. Graded on the head source (git diff origin/main 26b56285994, 4 files; the force-push from 4550b52 only reflows 3 lines with oxfmt). The PR body was not taken as evidence.

What the diff adds or changes

# Work Trigger / rate Population Bound at head (base)
1 Coalescer holds batches in HeldBatches (items / submissions Maps, keyed once). addToHeld per push, heldEvent at flush. structured-agent-session-coalescer.ts:40-76,201-205 Each streamed assistant or reasoning batch the desktop or phone reader gets. While visible, it flushes every 48 ms. While hidden, nothing flushes until the viewer shows, a bypass event arrives or the reader is disposed. H = distinct rows held; k = rows in the push Per push: O(k) Map writes plus a fixed header merge (mergeBatchHeader: three small restatements, sized by right only). Per flush: O(H) once. Base: each push rebuilt the Map from all held rows and copied the output array, so O(H) per push and N(N-1)/2 over N pushes (523,776 visits at N=1,024; 52.4M at N=10,240). STA-18484 is fixed.
2 withSubscriberLiveText gets the item-ID Set lazily (() => Set, memoized with ??=). agent-session-subscriber-live-text.ts:133-135,197-200,210 Each durable batch or snapshot page sent to a subscriber ≤200 rows per page Snapshot path (pageWithSubscriberLiveText): the Set is built only when a live source calls takes. If there is no sink, the sink is held, or the sink is closed, readLiveText returns [] and builds nothing. Base: it always built a 200-entry array and Set. STA-18488 is fixed. Batch path: forgetEndedLiveRows(..., itemIds()) still builds the Set after the read. Base did this too, so this is not a regression (see note below).
3 withStreamedRows returns early when built === rows. native-chat-transcript-streamed-slots.ts:154-156. The caller passes revisedAt=[] when last.rows === rows (:241-245). Each renderer transcript rebuild: a new base build, or the memo re-running with the same rows N messages O(1). Base: N identity comparisons per qualifying rebuild (1,000 at N=1,000; 10,000 at 10×). STA-18487 is fixed. Slot identity is unchanged: the hook destructures slots, so the fresh {...base.built, slots} wrapper costs one allocation and is not used as a memo key.
4 The work-run member position is stored in the slot index (SlotPlace.member). withStreamedRunMember looks it up instead of calling indexOf, then records noteRevisedInPlace(workRun, laidOut, earlier ∪ {at}). :28,48-50,59-84,182 Each between-save reasoning delta on a thought inside a work run (about 16 Hz while streaming) M run members; E = members changed since layout Per delta: one O(M) slice (the new immutable run array, which is the required output), plus O(E) for earlier.includes and the spread. The consumer useNativeChatWorkRunStreamed (use-native-chat-work-run.tsx:64-72) now takes the positionsRevisedFrom branch and visits E entries instead of M. Base: three M-wide passes per delta (indexOf, slice, consumer walk), about 10k / 100k visits/s at M=200 / 2,000. Head does one M-wide reference copy: about 3.2k at M=200 or 32k at M=2,000 pointer copies per second while one thought streams. E stays small because a thought's state change regroups the run and does a full build (before.state !== current.state returns null), so earlier resets. STA-18485 is fixed.
5 Added one assertion to the streamed-slots perf test (the run reader resolves [3] by position) test only n/a n/a

Subscriptions and publications: the diff adds no subscription, listener, emit site or publication. The coalescer's subscribeShown registration and its 48 ms / 300 ms timers are unchanged. Listener census: one shown-listener per coalescer (one per open session reader), the same as base. Publish rate: one emit per 48 ms window while visible and one per show while hidden, the same as base. Idle wakeups/s per process (main, renderer, daemon): 0 before and 0 after. Timers are armed only by a push.

Regression classes touched

  • Streaming re-processes the whole message / hot-path rescans: matched. The diff removes them: per-push held rescans (1), the per-delta indexOf and consumer member walk (4), and the self-comparison (3). The only remaining per-delta O(M) work is the required immutable copy.
  • Hidden owners keep working: matched and disproved. A hidden coalescer now does O(k) per push instead of O(H). Retention is unchanged: H distinct rows are held until the viewer shows, the same as base. This is pre-existing, has no cap, and the rows must be applied when the viewer shows. held.first also keeps the first batch's original rows until flush. That is one batch's payload, a fixed bound that does not grow.
  • Expensive work before the skip gate: matched. The diff fixes it for snapshots (2).
  • Fixed-cadence poll / new idle wakeups: no matching code. No timer changes.

Six questions

  1. Unused work before the gate: reviewed. The snapshot ID Set is now built after the sink check. Batch path: pre-existing, see the note.
  2. Ownership multiplication: reviewed. There is still one coalescer per reader and one streamed-transcript closure per transcript hook (useState initializer). Nothing new per row.
  3. Thread / storage: renderer and shared code on the reader's thread, plus main-process subscriber delivery (no sync I/O, no SQLite). Not applicable beyond that.
  4. Growth / progress: reviewed. Per-push cost no longer grows with the held count. A flush drains everything. earlier resets on regroup.
  5. Execution host: pure in-memory JS, so it is the same on mac, Linux, Windows and remote hosts. Remote viewers use the same coalescer.
  6. Obsolete work stops: reviewed. dispose clears timers and pending. Old WeakRef / WeakMap revision links are weak and do not grow.

Evidence

  • Source-proven work counts at head. These are not runtime timings, and the scan makes no CPU or heap claim.
  • Ran on a remote check machine: the coalescer held-text tests, the streamed-slots perf tests, and the subscriber live-text suites (including the fan-out perf contract). All 9 files and 41 tests pass. They ran at 4550b52; 26b56285 differs only in formatting.

Notes (non-blocking)

  • Pre-existing: batchWithSubscriberLiveText (agent-session-subscriber-live-text.ts:183) calls itemIds() on every durable batch, including when subscriber.liveSent is empty. forgetEndedLiveRows returns early in that case and never reads the Set. That costs O(batch rows) per durable batch per subscriber, the same as base. Building the Set inside forgetEndedLiveRows after its sent.size === 0 check would remove it.
  • Guard gap: only STA-18485 gets a new assertion. The coalescer (O(k) per push at N vs 10N held), the cursorless-snapshot Set and the built === rows early return have no count guard. A coalescer check that counts per-push visits at H=1,024 vs 10,240 would catch a revert of the fix.

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The live-text reader now resolves item IDs on demand. Streamed transcript updates track work-run member positions and revised positions. The structured-session coalescer accumulates batch rows and submissions in keyed maps and materializes them when flushing.

Merge Risk: Minimal · up to 26b56

This change reduces repeated list scans while chat text streams, and the output should be unchanged. No concrete defects were found, so merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "Stop repeated row walks while chat text streams" matches the main theme of the changeset: the four changed paths remove repeated full-list walks during streaming (held-batch maps in the coa…
Description check Passed The description follows the template closely. It has an ELI5 section, a What Changed section with before and after and mechanisms for four paths, a Why section, a Linked Issue section with four issues…
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: Title check

Explanation

The title "Stop repeated row walks while chat text streams" matches the main theme of the changeset: the four changed paths remove repeated full-list walks during streaming (held-batch maps in the coalescer, work-run member positions, the transcript early return, and the lazy row-ID set). It is specific and concise, and it does not describe anything absent from the changes. It does not name each path, which is expected for a short title.

Full details: Description check

Explanation

The description follows the template closely. It has an ELI5 section, a What Changed section with before and after and mechanisms for four paths, a Why section, a Linked Issue section with four issues cited, a Visual Proof section marked N/A with a reason, a Testing section with a bench table and test results, a Performance section that explains the cost change, a Risk section with a level and a revert plan, and the remaining template sections. Gaps: the Performance section does not begin with the required 'None, because' line and instead gives a full explanation, which is acceptable here. The AI Disclosure and Review sections are empty. The Linked Issue section uses 'Fixes' for four issues, while the template's linked-issue requirement and the template's 'Fixes #' placeholder are satisfied by the ticket IDs. The lint, typecheck, test, and build checklist item is unchecked, and manual local testing is unchecked, which the author should confirm or explain.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d633bfe3-aef8-4f2c-b02c-81e0e9e81e3c
Commits

Reviewing files that changed from the base of the PR and between 4550b52 and 26b5628.

Files selected for processing: 1

  • src/main/native-chat/agent-session-wire/publication/subscribers/agent-session-subscriber-live-text.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status for 26b56285

Problem: four chat streaming paths walked a whole list again for each small update: a hidden chat holding streamed batches, a thought streaming inside a work run, a new transcript base, and a snapshot of a session with no live stream.

Change for users: nothing visible. A chat that streams while hidden, or that has long work runs, does far less work per update. For example, 10,240 held batches dropped from 1,969 ms to 7.7 ms.

Verified:

  • Two independent code reviews came back clean, and a regression audit came back SAFE. The audit compared 30,000 batch deliveries against main, covering order, dedup, revisions, submissions and headers.
  • A perf scan passed; its report is in the comment above.
  • check:changed passes, and so do the existing coalescer, streamed-slot, work-run and live-text tests.
  • No app QA was run. Every changed path is pure in-memory logic that the tests above drive directly.

Deferred, non-blocking:

  • A durable batch still builds its row-ID set even when nothing ends up reading it. Main did the same, so this is not a regression.
  • Of the four fixes, only the work-run one has a perf contract test.

@brennanb2025
brennanb2025 merged commit 5ae7183 into main Nov 26, 2026
60 checks passed
registered2nd pushed a commit to registered2nd/orca that referenced this pull request Nov 26, 2026
…#49422)

- Hidden viewers keep held rows keyed once instead of rebuilding them on every push (STA-18484)
- A streaming thought inside a work run records its position, so the run doesn't rescan its members (STA-18485)
- A fresh transcript base no longer compares its rows with themselves (STA-18487)
- A snapshot builds its row-ID set only if a live sink asks for it (STA-18488)

(cherry picked from commit 5ae7183)
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