Repository navigation
Studio: bound the Shiki token cache so a streamed code fence stops retaining every prefix - #9228
danielhanchen wants to merge 16 commits into
Conversation
Follow-up measurement: does the retained heap cost frames? On this evidence, no.The PR body deliberately claims a memory result and nothing else. This is the measurement that Method
Two independent clocks, because either alone can lie:
The recorder is calibrated before it is believed. Every run blocks the main thread for a known Control: a The arms really were separatedA 23x separation in retained heap. That is the whole point: if hundreds of megabytes of retained ResultEvery code-cell ratio is within 25% of 1.0, and the control's own Conclusion: the retained heap costs bytes, not frames. With 223 MB retained against 9.6 MB, What this does and does not changeIt does not weaken the case for merging. +329 MB per four slow replies is a crash risk on a It also means that if slow-thread frame rate is the problem being chased, this is not the fix for Limits of this measurement
Reproduce with: |
|
Follow-up for the three call sites still on the old path, with tool-code-cell.tsx as the one that streams: #9230 |
CI found a live-lock in this PR. Fixed, with the reproduction and a regression test.
What was wrongThe token cache evicted prefixes in BOTH directions: storing code A miss returns Two misses per round, forever, with the cache pinned at one entry. The fixEviction is now ONE-DIRECTIONAL: storing Three misses total, then stable. Regression coverNew test, The memory numbers in the PR body are unaffected: the streamed-fence measurements exercise one The other failing check
The remaining four failures ( |
Every number in this PR re-measured on the shipped one-directional cacheThe headlines in the description were taken against the BIDIRECTIONAL eviction that turned out to Same protocol as before: sample after the reply is UNMOUNTED and after three Fast rate, 96 updates 40 ms apartSlow rate, 300 updates, the case the 82 MB figure comes fromThe control holds flat across both rates on both arms, and the head arm was run with its ladder New arm: two fences alive at once, one a strict prefix of the otherThis is the shape that exposed the live-lock, and no single-fence arm can produce it. It is now in Two readings worth making explicit. Base pays roughly double its single-fence cost (16.13 against What this changes about the claimsNothing in direction, a little in magnitude: 13.40x becomes 13.03x, 7.11x becomes 6.88x, 133x One limit, named rather than buriedThe frame-timing null posted earlier rests on a 23x heap separation (223.2 MB against 9.6 MB) |
|
CI after the live-lock fix: The four that remain, |
|
Correction to my own bookkeeping: I posted The diff is still the same 13 files. I checked with a three-dot diff ( |
|
Confirmed main still routes every fence through the upstream module level cache in code-plugin.ts, so a streamed reply keeps one tokenisation per refresh window, and the bounded cache here matches the single update floor. Could you get the red checks on this branch green so it can be reviewed against a clean run? |
|
Closing this. Superseded by #8935, which is merged and bounds the token cache on the incremental tokenization path. This branch also conflicts with main. Rather than rebase a change whose subject is already handled, closing it. |
Streaming a markdown code fence into the chat retains JS heap forever. The cost is about
0.28 MB per 250 ms refresh window for a 32 KB fence, so it scales with how LONG the reply took,
not with the size of the fence alone:
Please quote the per-window figure rather than the 81.97 MB one. Measure a fast reply expecting
82 MB and you will find a tenth of it and conclude this is oversold.
Every number here is live V8 heap measured after the reply is unmounted and after three forced
collections. Four slow replies leave +329.51 MB behind. The retained bytes are V8 heap, not
DOM, which is why DOM-level work never moved RSS here.
This PR claims a memory result and nothing else. It makes no claim about frame time,
responsiveness or perceived speed, because retained heap is all that was measured.
What happened before
@streamdown/code1.1.1 memoises every tokenisation in a module-levelMapand never removesanything from it.
studio/frontend/node_modules/@streamdown/code/dist/index.jsis one minifiedline; the relevant columns are:
and the key is built by
The key embeds the code's length plus its first and last 100 characters. A streamed fence
reaches the highlighter once per refresh window with a longer prefix each time, so every window
mints a fresh key and a fresh full tokenisation of that prefix, and the package has no eviction
path of any kind. A finished reply therefore keeps one tokenisation per refresh window instead of
one per fence.
Streamdown itself is not at fault. Every
MapandWeakMapinstreamdown2.5.0's dist isbounded: its unified-processor cache is an LRU of 100 keyed on plugin identity (the literal
string
"default"when no custom plugins are passed, so it holds one entry), and its other twomaps are regex caches keyed on HTML tag name. The unbounded cache is one package over, in
@streamdown/code. Please do not file this against streamdown.@streamdown/code1.1.1 is the newest published version (1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.1.0,1.1.1, last publish 2026-03-17), and its public surface is
createCodePlugin,codeand types.There is no clear, no size option and no way to reach
pfrom outside the module, so an upgradeor a call-site tweak cannot fix it.
The cost is per refresh window, not per fence, so it scales with how long the reply took:
The invariant is about 0.28 MB retained per 250 ms refresh window for a 32 KB fence. The
82.71 MB figure is the slow-reply instance of that invariant, not a constant per fence.
What happens after
Studio drives Shiki itself and holds the result in a cache that is bounded and that evicts the
prefixes of a fence as the fence grows, so a streaming reply occupies one entry rather than one
per window. New file
code-token-cache.ts;code-plugin.tsgains atokenize()with the sameengine, the same language resolution and the same "cached result synchronously, else
nullplus acallback" contract the package has. The per-fence slot throttle in that file is untouched.
Arms were interleaved base, head, base, head, base, head rather than run one after the other,
and the fixtures were censused per cell per rep before anything was compared. These are
medians of paired ratios, not ratios of medians:
At the slow rate that produced 81.97 MB/fence, head is 0.60 MB/fence, a 136.6x reduction.
And for two fences alive at once where one is a strict prefix of the other, the shape that exposed
a live-lock in an earlier revision of this branch: base 16.13, head 0.87, 18.96x.
Head pays 0.87 there rather than 0.69, and that is the fix working rather than a wart. Two live
prefix-related fences legitimately hold TWO cache entries where the old code kept one, and keeping
one WAS the live-lock. A fix that costs a little more in the shape that used to hang is a fix.
Please do not "optimise" that entry back out; it puts the hang back.
The number worth reading is not the multiplier. It is that the head streamed 32 KB fence
(0.69) now costs the same as the head single-update 32 KB fence (0.67). Streaming no longer
costs anything above pasting, which is the floor: one finished fence keeps one tokenisation, and
that is what makes a remount paint highlighted code in the same tick.
Is this real
Yes. Every sample is taken after the rendered reply is unmounted and after three
HeapProfiler.collectGarbagepasses, read with CDPRuntime.getHeapUsage.usedSize, which is V8'slive bytes and does not count Blink DOM nodes at all. The DOM node count read at the same instant
is flat at 28 to 29 across every fence in every arm, so this cannot be detached nodes.
Controls, which are what make the number credible:
instead of many. The gap between this and 9.21 is the prefix keying and nothing else.
goes flat.
0.00, while the streamed arm rises 6.39 to 26.76 over the same ladder. A control that moved
with the rate would mean the ladder was measuring the harness.
Discrimination, because a retention metric that does not respond to the thing it measures is not
measuring anything: retention rises 1.93 to 9.21 MB/fence going from an 8 KB fence to a 32 KB
fence, and rises with stream duration as the ladder above shows. The harness exits non-zero if
that size ladder fails to rise.
Does merging break anything
The rendered output is byte-for-byte identical.
tests/studio/probe_shiki_render_parity.pystarts a vite in each of two checkouts, renders the same sources on both and compares
#rootinnerHTMLincluding every Shiki inline style.The negative control comes first, because a parity check without one proves nothing: two
different sources come back 24.09% identical, so the comparator demonstrably sees a
difference when there is one. With that established:
The one regression, stated plainly. The
32 KB in one updatecell is 0.95x, meaning headholds about 5% more for a single-shot fence: 0.67 against 0.64. That is deliberate and it is
bought for correctness. The new key holds the whole source; the old key held a length plus 200
characters, which means two different fences of equal length that share their first and last 100
characters aliased to one another and one was highlighted with the other's tokens. That is a
latent wrong-highlighting bug in the old path, and 30 KB of extra key string against 550 KB of
tokens is a good price to close it.
Desktop CSP. The new path uses
createJavaScriptRegexEngine, the same engine the packagealready uses. No WASM enters the module graph, so
studio/src-tauri/tauri.conf.json'sdefault-src 'self'with nowasm-unsafe-evalis unaffected.Bundle.
npm run bundle:checkreports the same spare as before the change, 132.9 KB transferand 493.5 KB raw, because
@streamdown/codealready importsshikiandshiki/engine/javascriptand no new module is added.
Existing behaviour.
tests/code-plugin-remount.test.ts, which pins "a remount gets alreadyhighlighted code back in the same tick", stays green. That property is exactly what the bounded
cache still provides.
Tests
Nine new assertions across
tests/code-token-cache.test.ts(7) andtests/code-plugin-language-fallback.test.ts(2). Each is proved non-vacuous individually bytests/mutants/code-token-cache-mutants.mjsandtests/mutants/code-plugin-language-mutants.mjs:one mutant per property, each naming the single test that must go red, and both runners also fail
if any test in their file is nobody's named victim, so a vacuous check cannot hide. All nine
mutants killed, none survived. Three of the seven cache mutants also redden other tests as
collateral, because they break a primitive every test reads through; that is reported by the
runner rather than hidden. The runners mutate the working tree and restore it, and are not wired
into
npm testor CI.The language tests exist because owning the Shiki call means owning the language resolution the
package used to do, and
createHighlighterrejects on a grammar it does not have, with therejection landing in a
catch. Without a plaintext fallback an unknown fence tag would be leftsilently unstyled forever.
Gates
The single failure is
tests/queued-model-capabilities.test.ts, which fails identically onunmodified
origin/mainand is unrelated to this change.Reproducing the numbers
The harness reports; it does not gate. It exits non-zero only when it is itself broken: a fixture
that did not stream, a highlighter that was never called, a size ladder that did not rise, or DOM
nodes accumulating across unmounted replies.
Not covered here
Three call sites still on the old path.
src/components/assistant-ui/tool-code-cell.tsx:10imports the default upstream plugin, and thatsurface streams, so it leaks identically. It is the one that matters.
src/components/markdown/markdown-preview.tsx:9andsrc/features/hub/catalog/model-readme.tsx:17import it too but render static content, one entryeach, so they are low priority. All three are left out on purpose: extending the fix there is a
small change, but it has not been measured or parity-checked on those surfaces, and an unverified
extension does not belong inside an otherwise fully verified one. Follow-up issue to come.
Chromium only. Every number above was taken in Playwright's headless Chromium. Nothing here
speaks for WKWebView or WebKitGTK, which is what Unsloth Desktop embeds on macOS and Linux, and
those are the platforms where memory pressure actually hurts. The mechanism is a plain JavaScript
Mapwith no eviction, so it is not engine-specific and the fix cannot make matters worseelsewhere, but the megabyte figures should be re-measured before anyone quotes them for Desktop.
No frame-time measurement. Whether reclaiming this heap changes frame rate or p95 frame time
is not established by anything in this PR. That is being measured separately and will be posted as
a comment here whichever way it comes out.