Skip to content

Studio: stabilize long reasoning streams - #9066

Closed
wasimysaid wants to merge 10 commits into
unslothai:mainfrom
wasimysaid:fix/studio-streaming-markdown-performance
Closed

wasimysaid wants to merge 10 commits into
unslothai:mainfrom
wasimysaid:fix/studio-streaming-markdown-performance

Conversation

@wasimysaid

Copy link
Copy Markdown
Collaborator

Depends on #8935 by @oobabooga.

This is a stacked follow-up built directly on #8935 head f961eb48a4db2cbc3fe405dad2d6b1a3b4db38db; it preserves all of that PR's commits and authorship. While #8935 is open, please review only f961eb48..d695635d7 (the three commits added here). After #8935 merges, I will update this branch so GitHub shows only the follow-up diff.

Why this follow-up

#8935 substantially reduces Shiki tokenization work by resuming from saved grammar state, but long reasoning streams still accumulated Markdown parsing, React reconciliation, mounted DOM, highlighted spans, layout work, and WebKit memory.

The retained #8935 Tauri run fell from about 60 FPS at 20K reasoning characters to 16.4 FPS at 90K, while WebKit RSS reached 3.04 GB at 290 seconds. A follow-up ablation that suppressed Shiki still fell from 63.9 FPS to 12.7 FPS by 151 seconds, confirming syntax highlighting was only one contributor.

What changed

  • Incrementally retain completed Markdown blocks and reparse only the active rollback tail during ordinary append-only answer streams.
  • Virtualize large Markdown block lists and large code blocks, retaining stable block/line identities and bounded mounted DOM.
  • Keep Studio: incrementally tokenize streaming code fences #8935's incremental Shiki cache and prevent pending callbacks from updating an unmounted fence.
  • Stabilize reasoning autoscroll so user detachment is preserved and bottom pinning happens before paint.
  • Stream long reasoning as stable 4 KiB plain-text chunks, so only the final chunk changes while generation is active.
  • On reasoning completion, render the full formatted Markdown through the bounded/virtualized renderer.
  • Update assistant-ui runtime packages and their compatibility APIs in a separate first commit.

Streaming reasoning tradeoff

Reasoning remains plain text while it is actively streaming. Markdown markers and backticks may therefore be visible temporarily. Full Markdown formatting and syntax highlighting appear when reasoning completes.

This is intentional: keeping live Streamdown while disabling most syntax highlighting still degraded to 12.7 FPS. The plain-chunk path was the only tested path that kept the application responsive through a long real Tauri generation.

Normal answer Markdown continues through the incremental formatted block renderer.

Tauri/WebKit evidence

Same cached Qwen 27B model and in-page WebKit instrumentation:

Path Early FPS Late FPS Reasoning size Reasoning DOM Mutations
Full live Markdown follow-up 64.5 3.6 at 304 s (2.9 minimum) run-dependent 466 elements at final sample 577,120
Live Markdown, Shiki suppressed 63.9 12.7 at 151 s run-dependent 49 elements at final sample 54,079
Stable plain reasoning chunks 64.1 57.0 at 221 s (56.0 minimum) 64,473 chars 17 elements 2,052

The plain-chunk run remained approximately 56–64 FPS through 220 seconds. At 60 seconds, a separate bounded confirmation held 61.9–63.7 FPS with 20,726 reasoning characters and seven reasoning descendants.

No benchmark artifacts are included in the source diff.

Commits added after #8935

  1. b89420a2e — Studio: update assistant runtime dependencies
  2. afc81e24c — Studio: bound streaming Markdown rendering
  3. d695635d7 — Studio: stabilize long reasoning streams

Checks

  • Focused streaming/highlighting tests: 52 passed
  • Full frontend test suite: passed
  • Typecheck: passed
  • Production frontend build: passed
  • git diff --check f961eb48..HEAD: passed

oobabooga and others added 10 commits August 15, 2026 13:43
The incremental tokenization here is correct, including for the cases the
existing tests do not reach. These add coverage for the three gaps.

Embedded grammars. Every existing fixture is python, json or typescript,
where one grammar spans the whole fence, so resuming from a saved
GrammarState is never asked to restore a stack more than one level deep.
Five fixtures that are: HTML with embedded script and style, TSX with JSX
children, markdown with a multi-line HTML comment, shell heredocs with
runtime terminators, and nested template literals.

The engine. The desktop app's CSP is default-src 'self' with no
wasm-unsafe-eval, and the packaged frontend is this same bundle, so
switching to shiki's Oniguruma engine would pass every test and every
browser and fail only in the shipped desktop app. Nothing in CI builds
the desktop bundle and drives its webview, so this pins the JS engine.

The cache budget. MAX_CACHED_CHARACTERS is 512,000 and the largest
existing fixture is about 36 KB, so the character-budget branch, its
never-evict-the-only-fence carve-out and the running character count
were all unreachable.

Each test was checked against a deliberately broken tree rather than
assumed to discriminate, and two did not until they were rebuilt:

- The evict-then-resume test spent 22 of 23 comparisons on the throttled
  approximation, which renders the uncommitted tail plain and never
  reads the grammar state, so it could not fail however the resume broke.
  It now waits out REFRESH_MS between updates.
- The same test used a python triple-quoted string, whose tokens are
  byte-identical with the resumed state dropped. It now uses HTML with an
  embedded script, where the grammar is several levels deep at the resume
  point, and fails at character 2907 of 4414 when the state is dropped.

Tests only, no source changes. 32 passed, 0 failed on this head.
@wasimysaid
wasimysaid marked this pull request as draft August 17, 2026 05:07
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for this, and for the evidence pack behind it. The mechanism you landed on matches what we measured independently this week, and one row in your table is more interesting than I think you realise. Notes below in the order I would act on them.

1. The dependency bump should come out of this PR

Commit b89420a2e moves @assistant-ui/react 0.12.28 to 0.14.29, core 0.1.17 to 0.2.23, tap 0.5.10 to 0.9.6, radix-ui 1.4.3 to 1.6.7, zustand 5.0.11 to 5.0.14, and nanoid 5 to 6.

We evaluated that exact upgrade on its own and declined it. 27 interleaved A/B runs on our heavy-thread harness: the headline rows moved 0 to 1 percent, and keystroke latency regressed 1.36x to 1.54x on all three engines with zero overlap between the arms. It is also the same version set that a user reported to us as still choppy on Linux, which is part of why we did not take it.

That is not an argument against your rendering work, it is an argument for separating them. As it stands, if this merges and something regresses, we cannot tell which half did it. Please split the bump into its own PR so each can be judged on its own numbers. If the reasoning changes genuinely require APIs only present in 0.14.x, say which ones and we will look at that specifically.

2. Your second row is the most valuable number in the table

Path Late FPS Reasoning DOM Mutations
Full live Markdown follow-up 3.6 at 304 s 466 elements 577,120
Stable plain reasoning chunks 57.0 at 221 s 17 elements 2,052

The first row bounds the DOM to 466 elements and still reaches 3.6 FPS, which is worse than the 16.4 FPS you measured on 8935 alone with tens of thousands of elements mounted. So bounding the DOM did not help there. The 577,120 mutations say why: that path trades node count for churn.

That matters because it means there are two separate cost regimes, and a fix has to avoid both. We measured the other one directly. Filtering our capture to windows with almost no DOM churn:

mutations per 5 s elements fps
63 16,958 18.9
49 22,789 14.6

At roughly 10 mutations a second, with nothing being built, parsed or tokenized, the page still runs at 14.6 FPS, and average frame time is a uniform 68 ms rather than spiky. Pearson r between reasoning elements and FPS is -0.883 over 62 samples. So the baseline regime is bound by the standing presence of the nodes, and your virtualized-live-Markdown regime is bound by churn. Your plain-chunk path escapes both, which is why it works.

3. There may be a cheaper path to the same place

We ranked four candidates on a streaming reasoning fixture at 130,000 characters on Firefox, measuring calibrated main-thread busy time because on an idle machine FPS is not sensitive enough to discriminate:

arm busy early to late late fps peak spans peak elements
baseline 19.1 to 57.4 percent 53.0 16,107 17,482
content-visibility: auto 20.5 to 60.2 percent 51.6 16,065 17,440
no Shiki in reasoning 19.0 to 49.3 percent 55.3 2,515 3,890
cap what stays mounted 20.4 to 36.2 percent 55.7 2,894 3,168
both of the last two 19.6 to 24.2 percent 58.7 511 785

One run per arm, Vite dev server, Firefox only, so treat these as ranking rather than precise figures.

content-visibility does nothing, which is consistent with node count being the cost rather than offscreen paint. But capping what stays mounted, on its own, takes 37 percent off late busy time and 5.5x off node count while the pane keeps rendering full Markdown and highlighting. It renders the last ~12,000 characters during streaming, sliding in coarse steps aligned to block boundaries outside fences so the incremental Markdown cache is not defeated, and swaps to the full text shortly after the stream ends, by which point the group has usually collapsed and unmounted anyway.

The reason I raise it: it costs no visible change. Your plain-chunk path is the strongest result in your table and I am not disputing the measurement, but it makes Markdown markers and backticks visible during reasoning, which is a change every user sees on every reasoning generation. We are trying to hold UI and UX at least 95 percent unchanged through this performance work. If capping the mounted window gets most of the way with nothing visible, that is the better trade, and if it does not, your evidence for the stronger measure is much easier to accept.

4. Methodology

The three rows have different reasoning sizes, two of them marked run-dependent, and are single runs. We found matched-size comparison to be essential here, since FPS is a strong function of accumulated reasoning characters, so two paths sampled at different sizes are not directly comparable. Two things that cost us real time and may save you some: the arrival rate has to match a real generation, because saturating the event loop from t=0 understates the effect by roughly 3x, and on a mostly idle machine FPS does not discriminate, so main-thread busy time or a CPU throttle is needed.

Also worth flagging for anyone reading the earlier evidence: the baseline arm in the retained comparison is main plus the assistant-ui upgrade, while the 8935 arm is the older stack plus the PR, so the cross-arm deltas there are a double diff of the upgrade and the PR together. The within-arm trajectory is the sound part, and it is the same in both arms.

5. Smaller items

  • The branch is currently in conflict with main and will need a rebase.
  • main has moved since you built this. A contract test that was failing on Repo tests (CPU) is now fixed, so a rebase should clear that too.
  • 14 files at +3285/-3096 is a lot to review as one unit. Splitting the dependency bump out gets it a long way down on its own.

Happy to run your branch on our heavy-thread harness across chromium, webkit and firefox once the bump is separated, so we can give you matched-size before and after on the rendering changes alone.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d695635d75

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1062 to +1064
parseMarkdownIntoBlocks(processedText).map((content, index) => ({
id: index + 1,
content,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve block IDs when finalizing the stream

When a virtualized reply changes from running to complete, this branch discards the IDs assigned by IncrementalMarkdownCache and replaces them with 1..N. Since IDs are consumed whenever a live block changes, a final ID can refer to a different currently mounted block—or to an earlier measured version—in React and TanStack Virtual's key-based measurement cache. For replies with at least 24 blocks, finalization can therefore reuse the wrong row state and height, producing jumps, gaps, or overlapping rows until those blocks are remeasured. Reconcile the completed contents against the cache snapshots, or reset the virtualizer with a genuinely new key generation instead of recycling positional IDs.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

Flagging a blocking defect before this goes further, with the isolation behind it.

On a real Unsloth Desktop run (Linux WebKitGTK 2.52.5 under Tauri, not a container), a build carrying this PR loses rendered text after generation has finished. Frozen main on the same machine and the same prompts lost nothing across six trials.

I then isolated it away from the desktop lane, because that lane mixes two PRs. Three arms on the same frozen main c675be1ad, the same scripted SSE reply of 13,065 characters, no model loaded so the build is the only variable, Chromium, 11 trials per arm:

arm peak rendered final lost
frozen main 12,273 12,273 0 in 11 of 11
#8935 alone 12,273 12,273 0 in 11 of 11
#8935 + this PR 4,026 to 4,631 3,863 to 4,032 damaged in 11 of 11

So this is not #8935. That arm is byte-for-byte identical to frozen main across every trial.

Two details worth having:

The "lost after completion" framing understates it. The combined arm never renders more than about a third of the reply in the first place, so the peak is already wrong before anything disappears.

The harness is not blind to a passing arm. A control build made of the #8935 arm plus a synthetic "drop 30 percent after completion" mutation reported 3,570 to 3,594 characters lost, so the detector fires on that build shape when there is genuinely something to detect.

Two things I could not explain and am not going to assert:

The desktop lane emitted useClientLookup: Clamped stale index 19 to 18 (length: 19) at 174 to 177 occurrences per size, which is what first pointed me here. That identifier is not in this repository at all, it is in @assistant-ui/core, and the warning did not reproduce in any of my three arms. It may be a symptom of the same root cause or unrelated.

Chromium is a proxy here, not the packaged webview, so the isolation establishes which PR owns the behaviour rather than reproducing the exact desktop failure mode.

Happy to hand over the harness and the per-trial JSON if that is useful for tracking it down. The direction this PR is going is right and the reasoning-pane problem is real, so I would rather see this fixed than the PR dropped.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the long reasoning path in studio/frontend/src/components/assistant-ui/reasoning.tsx does keep growing the mounted DOM and mutation count during a long generation, and the plain 4 KiB chunking keeps it responsive. The direction is right, but this also lands the assistant-ui dependency bump, markdown and code virtualization, and the autoscroll change on top of an unmerged branch; could you rebase once #8935 lands and split the dependency update and the reasoning streaming change into separate PRs?

@danielhanchen

Copy link
Copy Markdown
Member

Closing this in favour of #9477, which you opened as its successor.

Your own summary there states the case better than I could: raw markdown while streaming is fast, but headings, lists, math, code containers, selection and general readability disappear. That is the right call, and #9477 is the version worth landing.

Recording what I measured here, so none of the work is lost and nobody re-derives it later.

The rendering ideas are not the problem. Three things made this branch unlandable in its current shape:

The dependency bump. b89420a2e moves @assistant-ui/react 0.12.28 to 0.14.29 along with core, tap and assistant-stream. That bump was evaluated separately and declined on keystroke latency, 1.36x to 1.54x worse on all three engines with no overlap. If it is still wanted it belongs in its own PR with its own measurement.

Content loss. On frozen main with a scripted 13,065-character SSE reply, 11 trials per arm: main and #8935 alone rendered 12,273 characters in 11 of 11. This branch peaked at 4,026 to 4,631 and finished at 3,863 to 4,032, damaged in 11 of 11. A synthetic-drop control confirmed the detector fires. I re-ran the equivalent rig against #9477 this week and it is clean there, identical to base to the character, so the successor does not carry this.

Two visible changes, one of them undisclosed. Reasoning renders as plain 4 KiB chunks while streaming, so markdown markers and backticks show on every generation. Separately max-h-64 becomes unconditional, so a completed reasoning pane stays a 256 px scrollbox instead of expanding. The second is not mentioned in the summary. I checked #9477 specifically for that one and it is clean: the class string is byte-identical to base and the settled pane measures max-height: none, not scrollable.

There is also a mechanical reason not to revive this branch as-is: 7 of its 10 commits are #8935, which merged as 531bc481a, and it now conflicts in all six source files plus three add/add test files. #9462 and #9567 have since landed off-screen fence deferral in the same region, solving the same offscreen-mounting problem differently, and this branch's index.css deletion would revert part of it.

Thanks for the work here, and for superseding it yourself rather than pushing it through. Continuing on #9477.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants