Skip to content

Studio: bound the Shiki token cache so a streamed code fence stops retaining every prefix - #9228

Closed
danielhanchen wants to merge 16 commits into
mainfrom
sd-shiki-fix
Closed

danielhanchen wants to merge 16 commits into
mainfrom
sd-shiki-fix

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

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:

  • a 32 KB fence arriving over ~83 seconds retains +81.97 MB
  • the same fence arriving over ~5 seconds retains +8.94 MB
  • the same fence pasted in a single update retains +0.64 MB

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/code 1.1.1 memoises every tokenisation in a module-level Map and never removes
anything from it. studio/frontend/node_modules/@streamdown/code/dist/index.js is one minified
line; the relevant columns are:

col 426    p = new Map()                    module level, no size cap, no clear, no unmount hook
col 1127   if (p.has(a)) return p.get(a)
col 1356   p.set(a, L)                      L is the full dual-theme codeToTokens result

and the key is built by

x = (e, n, t) => `${n}:${t[0]}:${t[1]}:${e.length}:${e.slice(0, 100)}:${e.slice(-100)}`

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 Map and WeakMap in streamdown 2.5.0's dist is
bounded: 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 two
maps 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/code 1.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, code and types.
There is no clear, no size option and no way to reach p from outside the module, so an upgrade
or 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:

32 KB fence delivered as retained MB/fence R² n
300 updates x 260 ms, a ~83 s reply 81.97 1.000 3
300 updates x 120 ms, a ~41 s reply 47.49 1.000 3
96 updates x 300 ms 26.76 1.000 4
96 updates x 40 ms, a ~5 s reply 8.94 1.000 6
one single update 0.64 0.997 6

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.ts gains a tokenize() with the same
engine, the same language resolution and the same "cached result synchronously, else null plus a
callback" 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:

cell base MB/fence head MB/fence ratio per-rep pairs base/head
streamed 32 KB 8.94 0.69 13.03x 8.94/0.69, 9.05/0.69, 8.30/0.69
streamed 8 KB 1.90 0.27 6.88x 1.93/0.28, 1.90/0.27, 1.85/0.27
32 KB in one update 0.64 0.67 0.95x 0.64/0.67 x3

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.collectGarbage passes, read with CDP Runtime.getHeapUsage.usedSize, which is V8's
live 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:

  • 32 KB in one update: 0.64 MB/fence. Same content, same DOM, same React work, one cache key
    instead of many. The gap between this and 9.21 is the prefix keying and nothing else.
  • 32 KB of prose, no fence: 0.12 MB/fence. The highlighter is never called, and the metric
    goes flat.
  • Tick-rate ladder: the single-update control holds at 0.68 at every tick rate, spread
    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.py
starts a vite in each of two checkouts, renders the same sources on both and compares #root
innerHTML including 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:

identical: streamed 32 KB fence                            1,085,218 chars of HTML
identical: streamed 8 KB fence                               283,434 chars
identical: streamed fence below MIN_INCREMENTAL_CHARS          42,514 chars
identical: 32 KB fence delivered whole                     1,100,778 chars
identical: small fence delivered whole                        44,926 chars
identical: prose, no fence                                    16,540 chars

The one regression, stated plainly. The 32 KB in one update cell is 0.95x, meaning head
holds 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 package
already uses. No WASM enters the module graph, so studio/src-tauri/tauri.conf.json's
default-src 'self' with no wasm-unsafe-eval is unaffected.

Bundle. npm run bundle:check reports the same spare as before the change, 132.9 KB transfer
and 493.5 KB raw, because @streamdown/code already imports shiki and shiki/engine/javascript
and no new module is added.

Existing behaviour. tests/code-plugin-remount.test.ts, which pins "a remount gets already
highlighted 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) and
tests/code-plugin-language-fallback.test.ts (2). Each is proved non-vacuous individually by
tests/mutants/code-token-cache-mutants.mjs and tests/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 test or CI.

The language tests exist because owning the Shiki call means owning the language resolution the
package used to do, and createHighlighter rejects on a grammar it does not have, with the
rejection landing in a catch. Without a plaintext fallback an unknown fence tag would be left
silently unstyled forever.

Gates

npm run typecheck        clean, both tsc projects
npx eslint               clean on every changed file
npm run build            clean
npm run bundle:check     within budget, same spare as before
npm test                 3786 pass, 1 fail

The single failure is tests/queued-model-capabilities.test.ts, which fails identically on
unmodified origin/main and is unrelated to this change.

Reproducing the numbers

# one arm
python tests/studio/playwright_shiki_retention.py

# the tick-rate ladder with its flat control
SMOKE_SD_MODE=ladder python tests/studio/playwright_shiki_retention.py

# paired base/head, interleaved; see the docstring for the loop
python tests/studio/shiki_retention_compare.py <dir>

# rendered output, two checkouts, byte for byte
python tests/studio/probe_shiki_render_parity.py --base <dir> --head <dir>

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:10 imports the default upstream plugin, and that
surface streams, so it leaks identically. It is the one that matters.
src/components/markdown/markdown-preview.tsx:9 and
src/features/hub/catalog/model-readme.tsx:17 import it too but render static content, one entry
each, 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
Map with no eviction, so it is not engine-specific and the fix cannot make matters worse
elsewhere, 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

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
would have justified a wider claim, and it does not. Posting it because a null here is worth as
much as a win would have been: it says where this change helps and where it does not, and it
means the responsiveness work has to come from somewhere else.

Method

tests/studio/playwright_shiki_jank.py, added in this PR. It fills the cache the way a session
does, by streaming 40 replies of a 32 KB python fence through the real markdown pipeline and
unmounting each one, and then records frame timing while one more reply streams at a realistic
pace, three times per cell, reporting the median. Arms interleaved base, head, base, head, base,
head. Three pairs.

Two independent clocks, because either alone can lie:

  • requestAnimationFrame gaps, for fps, p95 frame ms, worst frame ms and frames over 33 ms
  • a 1 ms setTimeout loop, for longest stall. This one exists because rAF stops being
    scheduled when the compositor decides nothing is visible, which reads as "no dropped frames"
    rather than as "no measurement". The timer keeps ticking regardless, and the gap between its
    ticks is the block.

The recorder is calibrated before it is believed. Every run blocks the main thread for a known
120 ms inside a recording window, and the run fails outright unless the recorder saw at least
100 ms of it. All six runs passed that check. A frame recorder that cannot see a stall it was told
about would report every arm as smooth, which is the most comfortable wrong answer available here.

Control: a prose cell that accumulates and measures replies with no code fence, so the
highlighter is never called and neither arm retains anything. Its numbers must not separate. They
did not, so the code cell's numbers are usable.

The arms really were separated

cell     base retained    head retained
code           223.2 MB          9.6 MB
prose            1.5 MB          1.5 MB

A 23x separation in retained heap. That is the whole point: if hundreds of megabytes of retained
tokens cost frames, this is where it would show.

Result

code cell (32 KB fence, 40 replies accumulated)
metric                 base     head   ratio  direction       per-rep pairs
p95_frame_ms           66.6     66.6    1.00  lower better    50.0/66.6  66.6/66.6  66.7/50.1
worst_frame_ms        133.4    133.3    1.00  lower better    133.4/133.3  133.4/116.7  133.3/150.0
frames_over_33ms       49.0     49.0    0.96  lower better    43.0/49.0  49.0/51.0  53.0/40.0
longest_stall_ms      172.6    175.3    0.98  lower better    172.6/176.6  162.0/166.1  174.0/175.3
fps                    44.0     43.9    1.02  higher better   45.5/43.9  44.0/43.1  41.0/45.3

prose cell (CONTROL, highlighter never called)
metric                 base     head   ratio  direction       per-rep pairs
p95_frame_ms           50.0     50.0    1.00  lower better    49.9/50.0  50.0/50.0  50.0/33.4
worst_frame_ms         83.4     83.3    0.80  lower better    66.7/83.3  83.4/116.6  116.7/66.7
frames_over_33ms       48.0     45.0    1.00  lower better    48.0/50.0  45.0/45.0  50.0/40.0
longest_stall_ms      107.8     96.8    1.01  lower better    97.5/96.8  107.8/133.6  140.6/86.4
fps                    48.2     48.3    1.01  higher better   48.8/48.3  48.2/48.0  46.1/51.5

Every code-cell ratio is within 25% of 1.0, and the control's own worst_frame_ms wanders 0.80x
between two arms that are doing identical work, which is a fair measure of how much of that 25%
band is just noise.

Conclusion: the retained heap costs bytes, not frames. With 223 MB retained against 9.6 MB,
nothing in the frame record moves. That is a plausible outcome rather than a surprising one: these
are long-lived, never-mutated token objects sitting in V8's old space, where a generational
collector skips them cheaply. Reclaiming them does not make the main thread do less work per
frame, because the per-frame work was never the tokens that were already cached.

What this does and does not change

It does not weaken the case for merging. +329 MB per four slow replies is a crash risk on a
memory-constrained machine at zero frame cost, and Desktop is exactly such a machine. It does mean
this PR should not be cited for responsiveness, and the body does not cite it for that.

It also means that if slow-thread frame rate is the problem being chased, this is not the fix for
it, and node-count work is where that has to come from. Worth stating plainly so the two are not
credited to each other.

Limits of this measurement

  • n = 3 pairs, on a shared 192-core box under load. A small real effect, say 10%, would not be
    visible here. This rules out a large effect, not any effect.
  • p95 and worst frame are quantized to whole frames. The values land on multiples of about
    16.7 ms because that is the vsync interval, so the metric cannot resolve a difference smaller
    than one whole frame.
  • No GC pause attribution. I did not instrument major GC directly, so this says the frames did
    not move; it does not say why with certainty.
  • Chromium only, like everything else in this PR. WKWebView and WebKitGTK use different
    collectors, and this result should not be assumed to carry to Desktop.

Reproduce with:

SMOKE_SD_LABEL=base python tests/studio/playwright_shiki_jank.py

@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up for the three call sites still on the old path, with tool-code-cell.tsx as the one that streams: #9230

@danielhanchen

Copy link
Copy Markdown
Member Author

CI found a live-lock in this PR. Fixed, with the reproduction and a regression test.

Chat UI Tests (picker) hung for 30 minutes and was cancelled on this branch. The same job passes
in 3 to 10 minutes on every other branch running right now, so I treated it as mine rather than as
a collision, and it was mine.

What was wrong

The token cache evicted prefixes in BOTH directions: storing code X dropped any cached entry
whose source was a prefix of X, and any entry that X was a prefix of. That is fine while a
single fence grows. It live-locks the moment two fences are on screen at once and one extends the
other, which is what a page showing the same snippet at two lengths does:

store long   -> evicts short
short renders -> miss -> store short -> evicts long
long renders  -> miss -> store long  -> evicts short
...

A miss returns null to the renderer, which schedules an asynchronous tokenisation, whose callback
re-renders and asks again. So it is not merely a cache that thrashes; it is a render loop that
never goes idle. Reproduced at the cache level, no browser needed:

round 0: entries=1 misses=2
round 1: entries=1 misses=4
round 2: entries=1 misses=6
...

Two misses per round, forever, with the cache pinned at one entry.

The fix

Eviction is now ONE-DIRECTIONAL: storing X drops only entries whose source X extends, never
entries that extend X. That is the direction the memory result actually needs, because every
earlier frame of a growing fence is a prefix of the current one, so a streamed reply still collapses
onto one entry. A source that SHRINKS is left to the size cap. Same repro after the change:

round 0: entries=2 misses=3
round 1: entries=2 misses=3
...
round 7: entries=2 misses=3

Three misses total, then stable.

Regression cover

New test, two fences on screen at once, one extending the other, both stay cached, which runs
eight rounds and fails if the cache does not settle. It has its own mutant in
tests/mutants/code-token-cache-mutants.mjs that restores the two-directional check, and the
mutant kills exactly that test. The gate is now 8 cache mutants plus 2 language mutants, all
killed, with every test in both files somebody's named target.

The memory numbers in the PR body are unaffected: the streamed-fence measurements exercise one
growing fence, which is the direction that was kept. I re-ran the unit suite, typecheck, build and
bundle check; npm test is 3787 pass, 1 fail, the same unrelated
tests/queued-model-capabilities.test.ts that fails on unmodified main.

The other failing check

workflow-trigger lint was also mine and is fixed in the same push: the repo requires every
Playwright driver under tests/studio to be either invoked by CI or listed in NOT_IN_CI with a
reason. playwright_shiki_retention.py and playwright_shiki_jank.py are measurement harnesses
that set no budget and cost tens of minutes, so they are registered as exempt with that reason
written out rather than wired into a job they would only slow down.

The remaining four failures ((Python 3.13), Frontend build + bundle sanity,
Frontend unit tests (Windows), Repo tests (CPU)) are main-side and fail identically on every
open PR.

@danielhanchen

Copy link
Copy Markdown
Member Author

Every number in this PR re-measured on the shipped one-directional cache

The headlines in the description were taken against the BIDIRECTIONAL eviction that turned out to
live-lock. They have all been re-measured on what is actually on this branch. A reader cannot tell
a preserved result from a plausible-sounding one, so none of them are being carried over on the
argument that the change "should not" have moved them.

Same protocol as before: sample after the reply is UNMOUNTED and after three
HeapProfiler.collectGarbage passes, read Runtime.getHeapUsage.usedSize, arms INTERLEAVED base,
head, base, head, base, head, fixtures censused per cell per rep, and the table is the MEDIAN OF
PAIRED RATIOS. Six runs, all exit 0, zero harness failures.

Fast rate, 96 updates 40 ms apart

cell                base MB/fence   head MB/fence     ratio    was
stream@32768                 8.94            0.69    13.03x    13.40x
stream@8192                  1.90            0.27     6.88x     7.11x
whole@32768 (control)        0.64            0.67     0.95x     0.95x
prose@32768 (control)        0.12            0.09     1.25x     1.32x

per-rep pairs, base/head
stream@32768   8.94/0.69   9.05/0.69   8.30/0.69
stream@8192    1.93/0.28   1.90/0.27   1.85/0.27

Slow rate, 300 updates, the case the 82 MB figure comes from

rate                base MB/fence   head MB/fence     ratio    R^2 base/head
300 x 260 ms                81.97            0.60   136.6x     1.000/1.000
300 x 120 ms                47.49            0.71    66.9x     1.000/0.993
whole (control)              0.66            0.69     0.95x     0.996/0.996

The control holds flat across both rates on both arms, and the head arm was run with its ladder
gate set to expect FLAT rather than rising; it passed, which is the fix working stated as a
falsifiable check rather than as an absence of failure.

New arm: two fences alive at once, one a strict prefix of the other

This is the shape that exposed the live-lock, and no single-fence arm can produce it. It is now in
the fixture set rather than only in the regression test, because retention under it is a number
nobody had.

cell                base MB/fence   head MB/fence     ratio    R^2 base/head
pair@32768                  16.13            0.87    18.96x    1.000/0.992

per-rep pairs   16.13/0.85   15.82/0.91   16.83/0.87

Two readings worth making explicit. Base pays roughly double its single-fence cost (16.13 against
8.94), because both fences retain their own prefix chain. Head pays 0.87 against 0.69, which is
the honest cost of one-directional eviction: two live prefix-related fences legitimately occupy TWO
entries where the old code kept one, and keeping one was the bug.

What this changes about the claims

Nothing in direction, a little in magnitude: 13.40x becomes 13.03x, 7.11x becomes 6.88x, 133x
becomes 136.6x, and the 82.4 MB/fence figure the whole investigation started from re-measures at
81.97 MB/fence with R^2 = 1.000. The description will be updated to these values.

One limit, named rather than buried

The frame-timing null posted earlier rests on a 23x heap separation (223.2 MB against 9.6 MB)
produced by the OLD cache. I have not re-run that comparison against the new one. The reason I
think it still stands is measurable rather than rhetorical: the jank harness accumulates single
GROWING fences, and for that shape head retention is byte-identical between the two evictions
(0.69 MB/fence both times, across three interleaved pairs each). So the separation the null was
measured across is unchanged. If anyone wants that re-run rather than argued, say so and I will
run it; it is about fifty minutes.

@danielhanchen

Copy link
Copy Markdown
Member Author

CI after the live-lock fix: Chat UI Tests (picker) now passes in 3m54s (it was cancelled at 30m before), and workflow-trigger lint passes. Those were the two failures caused by this branch.

The four that remain, (Python 3.13), Frontend build + bundle sanity, Frontend unit tests (Windows) and Repo tests (CPU), fail identically on main itself; I checked main's own check runs rather than assuming it. Nothing left on this branch is red because of this branch.

@danielhanchen

Copy link
Copy Markdown
Member Author

Correction to my own bookkeeping: I posted pair@32768 numbers before the arm that produces them was actually on this branch. It was sitting in the local worktree I measure from and had not been pushed. It is here now, in smoke-shiki-retention-main.tsx and playwright_shiki_retention.py, so the fixture set matches the numbers reported against it.

The diff is still the same 13 files. I checked with a three-dot diff (origin/main...HEAD) rather than a two-dot one; two-dot showed 20 files, of which 7 were changes main had gained since this branch was cut and which this PR does not touch. Three-dot is the correct comparison for "what does this PR contain" and it agrees with GitHub's own file list.

@danielhanchen

Copy link
Copy Markdown
Member Author

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?

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

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.

@danielhanchen
danielhanchen deleted the sd-shiki-fix branch August 21, 2026 06:32
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.

1 participant