Backtestsvuerun-20261003-231210#15070
SSR memory leak after a render error in a dynamic component
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
The leak happens because `openBlock()` runs, the content throws before `createBlock()`/`closeBlock()`, and a stale `currentBlock` is left behind. That block then collects every block-tracked vnode created later. Both patches stop this for the reported case, but in different ways. Patch B handles it at the error boundaries. It adds `resetBlockStack()`, which clears both `blockStack` and `currentBlock`, and calls it in two places: when `ssrRender` throws inside `renderComponentSubTree`, and in `renderComponentRoot`'s catch. The second call fixes a real latent bug: that catch previously did only `blockStack.length = 0` and left `currentBlock` stale. So B covers the reported dynamic-component slot case plus any other open-block-then-throw path, including render-function components and inline `v-if` blocks. It does this without touching hot paths. Resetting the whole stack is safe here. Blocks are opened and closed synchronously, and the error propagates to reject the render anyway. Patch A unwinds locally. It adds try/catch to `renderSlot` and stack-size bookkeeping in a `finally` inside `withCtx`. That fixes slot-originated errors, and it also restores `_d` correctly. However: - It adds work to two very hot runtime paths (`renderSlot`, and every `withCtx` call). - It leaves the stale-`currentBlock` bug in `renderComponentRoot` untouched, so an open block thrown from a render function outside a slot can still leak. Tests: B's tests check `blockStack` and `currentBlock` directly after a failed render, both in SSR (including the `v-if` case) and in runtime-core. They are deterministic, run in the normal suite, and would fail before the fix. A's tests are GC-based. They need `--expose-gc` and a vitest config change, and they are skipped when GC isn't exposed. They are closer to the issue's symptom but more brittle. Overall, B is the more complete fix at the root cause, with lower runtime cost and more reliable tests.
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
10m 29s
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
110vs 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/__tests__/errorHandling.spec.tsindex 0cd3efa58..3a8ce8fff 100644@@ -8,12 +8,14 @@ import { nodeOps, onErrorCaptured, onMounted,+ openBlock, ref, render, watch, watchEffect, } from '@vue/runtime-test' import { ErrorCodes, ErrorTypeStrings } from '../src/errorHandling'+import { blockStack, currentBlock } from '../src/vnode' describe('error handling', () => { test('propagation', () => {@@ -246,6 +248,38 @@ describe('error handling', () => { expect(fn).toHaveBeenCalledWith(err, 'render function') }) + test('should discard blocks left open by an error in render function', () => {+ const err = new Error('foo')+ const fn = vi.fn()++ const Comp = {+ setup() {+ onErrorCaptured(err => {+ fn(err)+ return false+ })+ return () => h(Child)+ },+ }++ const Child = {+ setup() {+ return () => {+ // simulates a compiled `(openBlock(), createBlock(...))` whose+ // children throw before the block is closed+ openBlock()+ throw err+ }+ },+ }++ render(h(Comp), nodeOps.createElement('div'))+ expect(fn).toHaveBeenCalledWith(err)+ // a stale current block would retain every vnode created afterwards+ expect(blockStack.length).toBe(0)+ expect(currentBlock).toBe(null)+ })+ test('in function ref', () => { const err = new Error('foo') const ref = () => {packages/runtime-core/src/componentRenderUtils.tsindex 0b46130c0..39b0b7233 100644@@ -8,11 +8,11 @@ import { Comment, type VNode, type VNodeArrayChildren,- blockStack, cloneVNode, createVNode, isVNode, normalizeVNode,+ resetBlockStack, } from './vnode' import { ErrorCodes, handleError } from './errorHandling' import {@@ -141,7 +141,7 @@ export function renderComponentRoot( : getFunctionalFallthrough(attrs) } } catch (err) {- blockStack.length = 0+ resetBlockStack() handleError(err, instance, ErrorCodes.RENDER_FUNCTION) result = createVNode(Comment) }packages/runtime-core/src/index.tsindex 792a28b25..fbc252555 100644@@ -401,7 +401,7 @@ import { } from './component' import { renderComponentRoot } from './componentRenderUtils' import { setCurrentRenderingInstance } from './componentRenderContext'-import { isVNode, normalizeVNode } from './vnode'+import { isVNode, normalizeVNode, resetBlockStack } from './vnode' import { ensureValidVNode } from './helpers/renderSlot' import { popWarningContext, pushWarningContext } from './warning' @@ -416,6 +416,7 @@ const _ssrUtils: { ensureValidVNode: typeof ensureValidVNode pushWarningContext: typeof pushWarningContext popWarningContext: typeof popWarningContext+ resetBlockStack: typeof resetBlockStack } = { createComponentInstance, setupComponent,@@ -427,6 +428,7 @@ const _ssrUtils: { ensureValidVNode, pushWarningContext, popWarningContext,+ resetBlockStack, } /**packages/runtime-core/src/vnode.tsindex b4fe6f237..6a8ba61ab 100644@@ -290,6 +290,17 @@ export function closeBlock(): void { currentBlock = blockStack[blockStack.length - 1] || null } +/**+ * Discard all open blocks. Used to recover after a render error thrown between+ * `openBlock()` and `createBlock()`, which would otherwise leave a stale+ * `currentBlock` collecting (and retaining) every vnode created afterwards.+ * @internal+ */+export function resetBlockStack(): void {+ blockStack.length = 0+ currentBlock = null+}+ // Whether we should be tracking dynamic child nodes inside a block. // Only tracks when this value is > 0 // We are not using a simple boolean because this value may need to bepackages/server-renderer/__tests__/ssrDynamicComponent.spec.tsindex 0679c8216..b7558ccf1 100644@@ -1,5 +1,6 @@ import { createApp, createVNode } from 'vue' import { renderToString } from '../src'+import { blockStack, currentBlock } from '../../runtime-core/src/vnode' describe('ssr: dynamic component', () => { test('resolved to component', async () => {@@ -77,4 +78,53 @@ describe('ssr: dynamic component', () => { ), ).toBe(`<div id="test"><span>slot</span></div>`) })++ describe('render error in slot content of dynamic component', () => {+ const Card = {+ props: { tag: { type: String, default: 'div' } },+ template: `<component :is="tag" class="card"><slot /></component>`,+ }++ const createTestApp = (template: string, payload: any) =>+ createApp({+ components: { Card },+ data: () => ({ payload }),+ template,+ })++ const expectBlockStackReset = () => {+ // a block left open by the failed render would retain every vnode (and+ // thus every app) created by subsequent renders+ expect(blockStack.length).toBe(0)+ expect(currentBlock).toBe(null)+ }++ test('should not leak blocks after a failed render', async () => {+ const template = `<main><Card>{{ payload.title }}</Card></main>`++ await expect(+ renderToString(createTestApp(template, null)),+ ).rejects.toThrow()+ expectBlockStackReset()++ expect(+ await renderToString(createTestApp(template, { title: 'ok' })),+ ).toBe(`<main><div class="card"><!--[-->ok<!--]--></div></main>`)+ expectBlockStackReset()+ })++ test('should not leak blocks after a failed render inside v-if', async () => {+ const template = `<main><Card><span v-if="true">{{ payload.title }}</span></Card></main>`++ await expect(+ renderToString(createTestApp(template, null)),+ ).rejects.toThrow()+ expectBlockStackReset()++ expect(+ await renderToString(createTestApp(template, { title: 'ok' })),+ ).toBe(`<main><div class="card"><!--[--><span>ok</span><!--]--></div></main>`)+ expectBlockStackReset()+ })+ }) })packages/server-renderer/src/render.tsindex 8fc9b0128..8381df685 100644@@ -38,6 +38,7 @@ const { normalizeVNode, pushWarningContext, popWarningContext,+ resetBlockStack, } = ssrUtils export type SSRBuffer = SSRBufferItem[] & { hasAsync?: boolean }@@ -201,6 +202,12 @@ function renderComponentSubTree( instance.data, instance.ctx, )+ } catch (err) {+ // vnode-based fallbacks (e.g. slots of dynamic components) may have+ // opened a block that was never closed due to the error. Discard it so+ // it doesn't retain every vnode created by subsequent renders.+ resetBlockStack()+ throw err } finally { setCurrentRenderingInstance(prev) }
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'], }, },