Backtestsvuerun-20261001-022054#15070
SSR memory leak after a render error in a dynamic component
The merged fix was judged better than our patch.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches target the root cause. When the slot function throws inside `renderSlot` after `openBlock()`, the block is never closed. `currentBlock` then stays pointing at a stale array, and every vnode created by later renders gets pushed into it and retained. Both fixes resolve the exact scenario in the issue, where text slot content throws inside a `<component :is>` forwarding `<slot />`. Patch A is more robust in two ways: 1. It records `blockStack.length` before opening and unwinds back to that size on error. This also correctly closes nested blocks the slot content may have opened before throwing. Patch B calls `closeBlock()` exactly once. If the slot content contains an inline block, such as `(openBlock(), createElementBlock(...))` from `v-if`, and throws while evaluating its children, B pops only that inner block and leaves `renderSlot`'s own block dangling, so the leak persists. 2. Patch A applies the same unwinding in `withCtx`. That covers inline blocks inside compiled slot functions even when they are not wrapped by `renderSlot`. A also moves the `_d` restoration into `finally`, which is cleaner than B's duplicated reset in the catch branch. Tests: Patch A adds real GC-based leak tests using WeakRefs and wires them into the existing `unit-gc` vitest project with `--expose-gc`. The tests cover both the issue's repro and the `v-if` inline-block variant, and they directly assert the reported symptom (apps not collected). Patch B's test is reasonable: a probe `createBlock` at top level shows non-empty `dynamicChildren` if a block was leaked, so it would fail before the fix. However, it calls `createBlock` without a matching `openBlock`, which pops the block stack unbalanced and could disturb shared state. It also does not exercise the nested-block case that B's fix misses. Scope: A's extra `withCtx` change is a directly related hardening of the same failure mode and adds little risk. Overall A is the more correct and better-tested fix.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
4m 47s14 turns
Wall-clock time in the container
Full test suite
No new failures
3,612 passed · 6 skipped · 3,618 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
55vs 152 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.39
Link to minimal reproduction
https://stackblitz.com/edit/vitejs-vite-qfkzyzwp?file=leak.mjs
Steps to reproduce
- download the reproduction from stackblitz (won't work there, needs to be run locally)
- run
pnpm i && pnpm leak - see the heap size & alive app instances grow with each request after the single failed render
The script renders 500 fresh SSR apps, which all get garbage-collected. Then renders one app whose slot content throws, then renders 500 more identical healthy apps, which will never be garbage collected afterwards.
A dynamic component <component :is> with a <slot /> is needed for this to reproduce.
Card
<script setup>
defineProps({ tag: { type: String, default: 'div' } })
</script>
<template>
<component :is="tag" class="card">
<slot />
</component>
</template>
app:
<script setup>
defineProps(['payload']) // one request renders with `payload: null` → throws
</script>
<template>
<main>
<Card>{{ payload.title }}</Card>
</main>
</template>
What is expected?
A failed renderToString should not affect subsequent renders and all apps rendered after it should get garbage collected.
What is actually happening?
Every app created after the single failed render is kept in memory forever.
--- phase 1: 500 healthy renders ---
after 500: created=500 finalized=500 alive=0 heap=20.6MB
--- one crashing render (SSR render error) ---
render rejected as expected: Cannot read properties of null (reading 'title')
--- phase 2: 500 healthy renders (identical to phase 1) ---
after 500: created=1001 finalized=500 alive=501 heap=29.0MB
FINAL: created=1001 finalized=500 alive=501
System Info
Any additional comments?
_No response_
The two patches
packages/runtime-core/src/helpers/renderSlot.tsindex 2f1296bb1..c3bfffa1f 100644@@ -9,6 +9,7 @@ import { Fragment, type VNode, type VNodeArrayChildren,+ closeBlock, createBlock, createVNode, isVNode,@@ -72,7 +73,20 @@ export function renderSlot( ;(slot as ContextualRenderFn)._d = false } openBlock()- const validSlotContent = slot && ensureValidVNode(slot(props))+ let validSlotContent: VNodeArrayChildren | null | undefined+ let children: VNodeArrayChildren+ try {+ validSlotContent = slot && ensureValidVNode(slot(props))+ children = validSlotContent || (fallback ? fallback() : [])+ } catch (e) {+ // ensure the block opened above is closed so block tracking is not left+ // in a stale state (which would leak vnodes, especially in SSR)+ closeBlock()+ if (slot && (slot as ContextualRenderFn)._c) {+ ;(slot as ContextualRenderFn)._d = true+ }+ throw e+ } const slotKey = props.key || // slot content array of a dynamic conditional slot may have a branch@@ -86,7 +100,7 @@ export function renderSlot( // #7256 force differentiate fallback content from actual content (!validSlotContent && fallback ? '_fb' : ''), },- validSlotContent || (fallback ? fallback() : []),+ children, validSlotContent && (slots as RawSlots)._ === SlotFlags.STABLE ? PatchFlags.STABLE_FRAGMENT : PatchFlags.BAIL,packages/server-renderer/__tests__/render.spec.tsindex 268c7dc1e..01126ff44 100644@@ -4,6 +4,7 @@ import { Transition, computed, createApp,+ createBlock, createCommentVNode, createSSRApp, createStaticVNode,@@ -824,6 +825,42 @@ function testRender(type: string, render: typeof renderToString) { expect(getCurrentInstance()).toBe(prev) }) + test('reset block tracking after rendering error in slot', async () => {+ const Card = {+ props: { tag: { type: String, default: 'div' } },+ template: `<component :is="tag" class="card"><slot /></component>`,+ }+ try {+ await render(+ createApp({+ components: { Card },+ data() {+ return { payload: null }+ },+ template: `<main><Card>{{ payload.title }}</Card></main>`,+ }),+ )+ } catch {}++ // subsequent healthy renders must still work+ expect(+ await render(+ createApp({+ components: { Card },+ data() {+ return { payload: { title: 'ok' } }+ },+ template: `<main><Card>{{ payload.title }}</Card></main>`,+ }),+ ),+ ).toBe(`<main><div class="card"><!--[-->ok<!--]--></div></main>`)++ // no block should be left open: a block created at the top level+ // must not collect vnodes created by previous renders+ const probe = createBlock('div')+ expect(probe.dynamicChildren).toHaveLength(0)+ })+ // #7733 test('reset current instance after error in data', async () => { const prev = getCurrentInstance()
packages/runtime-core/src/componentRenderContext.tsindex b1fc70c03..d10eba648 100644@@ -1,6 +1,6 @@ import type { ComponentInternalInstance } from './component' import { devtoolsComponentUpdated } from './devtools'-import { setBlockTracking } from './vnode'+import { blockStack, closeBlock, setBlockTracking } from './vnode' /** * mark the current rendering instance for asset resolution (e.g.@@ -89,10 +89,14 @@ export function withCtx( setBlockTracking(-1) } const prevInstance = setCurrentRenderingInstance(ctx)+ const prevStackSize = blockStack.length let res try { res = fn(...args) } finally {+ // close blocks left dangling when the slot throws mid-block+ // inline blocks (for example `v-if`) have no helper to unwind themselves (#15070)+ for (let i = blockStack.length; i > prevStackSize; i--) closeBlock() setCurrentRenderingInstance(prevInstance) if (renderFnWithContext._d) { setBlockTracking(1)packages/runtime-core/src/helpers/renderSlot.tsindex 2f1296bb1..8f65f8af4 100644@@ -9,6 +9,8 @@ import { Fragment, type VNode, type VNodeArrayChildren,+ blockStack,+ closeBlock, createBlock, createVNode, isVNode,@@ -71,32 +73,42 @@ export function renderSlot( if (slot && (slot as ContextualRenderFn)._c) { ;(slot as ContextualRenderFn)._d = false }+ const prevStackSize = blockStack.length openBlock()- const validSlotContent = slot && ensureValidVNode(slot(props))- const slotKey =- props.key ||- // slot content array of a dynamic conditional slot may have a branch- // key attached in the `createSlots` helper, respect that- (validSlotContent && (validSlotContent as any).key)- const rendered = createBlock(- Fragment,- {- key:- (slotKey && !isSymbol(slotKey) ? slotKey : `_${name}`) +- // #7256 force differentiate fallback content from actual content- (!validSlotContent && fallback ? '_fb' : ''),- },- validSlotContent || (fallback ? fallback() : []),- validSlotContent && (slots as RawSlots)._ === SlotFlags.STABLE- ? PatchFlags.STABLE_FRAGMENT- : PatchFlags.BAIL,- )+ let rendered: VNode+ try {+ const validSlotContent = slot && ensureValidVNode(slot(props))+ const slotKey =+ props.key ||+ // slot content array of a dynamic conditional slot may have a branch+ // key attached in the `createSlots` helper, respect that+ (validSlotContent && (validSlotContent as any).key)+ rendered = createBlock(+ Fragment,+ {+ key:+ (slotKey && !isSymbol(slotKey) ? slotKey : `_${name}`) ++ // #7256 force differentiate fallback content from actual content+ (!validSlotContent && fallback ? '_fb' : ''),+ },+ validSlotContent || (fallback ? fallback() : []),+ validSlotContent && (slots as RawSlots)._ === SlotFlags.STABLE+ ? PatchFlags.STABLE_FRAGMENT+ : PatchFlags.BAIL,+ )+ } catch (err) {+ // close blocks left dangling when the slot throws mid-block+ // they would otherwise retain every vnode created afterwards (#15070)+ for (let i = blockStack.length; i > prevStackSize; i--) closeBlock()+ throw err+ } finally {+ if (slot && (slot as ContextualRenderFn)._c) {+ ;(slot as ContextualRenderFn)._d = true+ }+ } if (!noSlotted && rendered.scopeId) { rendered.slotScopeIds = [rendered.scopeId + '-s'] }- if (slot && (slot as ContextualRenderFn)._c) {- ;(slot as ContextualRenderFn)._d = true- } return rendered } packages/server-renderer/__tests__/ssrRender.spec.tsnew file mode 100644index 000000000..2d23452a3@@ -0,0 +1,84 @@+import { createSSRApp } from 'vue'+import { renderToString } from '../src/renderToString'++const gc = () =>+ new Promise<void>(resolve => {+ setTimeout(() => {+ global.gc!()+ resolve()+ })+ })++const Card = {+ props: { tag: { type: String, default: 'div' } },+ template: `<component :is="tag" class="card"><slot /></component>`,+}++const Page = {+ components: { Card },+ props: ['payload'],+ template: `<main><Card>{{ payload.title }}</Card></main>`,+}++describe.skipIf(!global.gc)('ssr: render error leak', () => {+ // #15070+ test('should GC apps created after a render error in a forwarded slot', async () => {+ const createApp = (payload: any) => createSSRApp(Page, { payload })++ expect(await renderToString(createApp({ title: 'ok' }))).toContain('ok')++ await expect(renderToString(createApp(null))).rejects.toThrow(+ `Cannot read properties of null`,+ )++ const weakRefs: { deref(): unknown | undefined }[] = []+ const renderOnce = async () => {+ const app = createApp({ title: 'ok' })+ // @ts-expect-error ES2021 API+ weakRefs.push(new WeakRef(app))+ expect(await renderToString(app)).toContain('ok')+ }+ for (let i = 0; i < 20; i++) {+ await renderOnce()+ }++ for (let i = 0; i < 5; i++) {+ await gc()+ }++ expect(weakRefs.filter(ref => ref.deref()).length).toBe(0)+ })++ test('should GC apps created after a render error in an inline block (`v-if`)', async () => {+ const PageIf = {+ props: ['payload'],+ template: `<component :is="'div'"><div v-if="payload.list">{{ payload.list.missing.x }}</div></component>`,+ }+ const createApp = (payload: any) => createSSRApp(PageIf, { payload })++ expect(+ await renderToString(createApp({ list: { missing: { x: 'ok' } } })),+ ).toContain('ok')++ await expect(renderToString(createApp({ list: {} }))).rejects.toThrow(+ `Cannot read properties of undefined`,+ )++ const weakRefs: { deref(): unknown | undefined }[] = []+ const renderOnce = async () => {+ const app = createApp({ list: { missing: { x: 'ok' } } })+ // @ts-expect-error ES2021 API+ weakRefs.push(new WeakRef(app))+ expect(await renderToString(app)).toContain('ok')+ }+ for (let i = 0; i < 20; i++) {+ await renderOnce()+ }++ for (let i = 0; i < 5; i++) {+ await gc()+ }++ expect(weakRefs.filter(ref => ref.deref()).length).toBe(0)+ })+})vitest.config.tsindex 2fbc92f92..8e1f5bec8 100644@@ -58,6 +58,7 @@ export default defineConfig({ '**/e2e/**', '**/{vue,vue-compat,runtime-dom}/**', 'packages/server-renderer/__tests__/ssrWatch.spec.ts',+ 'packages/server-renderer/__tests__/ssrRender.spec.ts', ], }, },@@ -66,7 +67,10 @@ export default defineConfig({ test: { name: 'unit-gc', pool: 'forks',- include: ['packages/server-renderer/__tests__/ssrWatch.spec.ts'],+ include: [+ 'packages/server-renderer/__tests__/ssrWatch.spec.ts',+ 'packages/server-renderer/__tests__/ssrRender.spec.ts',+ ], execArgv: ['--expose-gc'], }, },
What the agent reported
A slot that throws during SSR no longer leaves block tracking open, so apps rendered after a failed renderToString are no longer held in memory. The fix is in packages/runtime-core/src/helpers/renderSlot.ts, and the new regression test fails without it and passes with it.
What was wrong: In SSR, <component :is="tag"> with a string tag builds an element vnode, and building it calls the default slot through the runtime helper renderSlot. renderSlot calls openBlock(), then runs the slot (and the fallback, if any), then calls createBlock(), which is the step that closes the block. When the slot threw (payload.title on null), the block was never closed. That left currentBlock in packages/runtime-core/src/vnode.ts pointing at a stale array. SSR-compiled code never opens or closes blocks itself, so nothing reset it. Every component vnode created by later renders, starting with the root vnode renderToString creates, was pushed into that array. Those vnodes hold their component instances and app contexts, so every later app stayed reachable. That matches the report's "alive=501".
What I changed: In renderSlot.ts, running the slot and the fallback is now wrapped in a try/catch. On error it calls closeBlock(), resets the slot's _d flag (which was also left wrong on the error path), and rethrows. The normal path builds the same vnode as before.
Test evidence:
- New test:
reset block tracking after rendering error in slotinpackages/server-renderer/__tests__/render.spec.ts. It uses the report's exact Card and App templates and first renders withpayload: null, which throws. It then checks that a healthy render still outputs<main><div class="card"><!--[-->ok<!--]--></div></main>. Finally it checks that no block was left open: a fresh top-levelcreateBlock('div')must not collect any vnodes from earlier renders. - Before the fix: it failed in all three render modes (renderToString, renderToNodeStream, pipeToNodeWritable) with "expected … to have a length of +0 but got 3".
- After the fix: it passes in all three modes.
- Wider check:
renderSlotis used by client rendering as well as SSR, so I ran./bt-test packages/runtime-core packages/server-renderer: 60 files and 1339 tests passed.tsc --noEmitreported nothing for the changed files. - Review: the reviewer found nothing blocking and confirmed no unrelated changes.
git diff --statshows only the two files above.
Requirements:
- A failed
renderToStringshould not affect later renders: done. The new test checks that a healthy render after the failure produces the correct HTML. - Apps rendered after the failure should be garbage collected: done. The test asserts that the stale block which kept those apps alive is gone. It does not measure garbage collection or heap size directly, the way the reproduction script does.
- Reproduction with
<component :is>plus<slot />: done. The test uses exactly that Card and App.
One related gap I left alone: the custom-element branch of renderSlot (around lines 46–54) has the same openBlock() → fallback() pattern with no protection. It is not involved in this SSR scenario, so I did not change it.
All changes are uncommitted in the working tree.