Backtestsvuerun-20261005-155915#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.
**Root cause.** In SSR, a dynamic component that resolves to an element renders its slot children in vnode mode, which goes through `renderSlot` → `openBlock()`. If the slot throws before `createBlock()`, the module-level `blockStack` and `currentBlock` are left pointing at a stale array. Every vnode created by later renders is pushed into that array and kept alive. SSR has no client-style re-render that would later reset the block state. **Patch A** unwinds blocks locally in `renderSlot` (on throw) and in `withCtx` (in `finally`). This fixes the reported slot scenario and inline `v-if` blocks inside slots. However: - It only covers slot paths. Any other throw between `openBlock()` and `createBlock()` in SSR still leaves `currentBlock` stale. One example is a non-compiled render function. `renderComponentRoot`'s catch only does `blockStack.length = 0` and never clears `currentBlock`, and Patch A leaves that untouched. - It adds work to `withCtx`, which runs on every slot invocation on the client. That adds risk and overhead to a hot path for an SSR-specific problem. - Its tests are GC-based and are skipped when `--expose-gc` isn't available. They are faithful to the issue, but they need a vitest config change and depend on GC timing. **Patch B** fixes the state at the SSR boundary. - It adds `resetBlockStack()`, which clears both `blockStack` and `currentBlock`, so the stale `currentBlock` bug is actually fixed. - It calls this from `renderComponentSubTree`'s catch, so any synchronous render error during SSR, from any source, leaves no block state behind. - It also corrects `renderComponentRoot`, which previously reset only the stack and not `currentBlock`. - It restores the rendering instance when `handleError` rethrows, and pops the dev warning context via `finally`. Both are closely related retention leaks on the same error path. - The client hot path is unchanged; only error paths are touched. - Its tests directly assert `blockStack.length === 0`, `currentBlock === null`, and that the rendering instance and scope id are reset after the failed render. These would fail before the fix, run deterministically without GC, and cover the issue scenario, a `v-if` inside the slot, a non-compiled render function, and warning-context leakage. - Splitting out `doRenderComponentSubTree` is a small, clear refactor. A full reset could in theory discard outer blocks if a caller caught the error mid-render, but SSR aborts the whole render on such errors, so this risk is minimal. **Verdict.** Patch B addresses the root cause more completely, with deterministic and more thorough tests and less risk to client performance.
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
12m 1s
Wall-clock time in the container
Full test suite
No new failures
3,613 passed · 6 skipped · 3,619 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
173vs 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/componentRenderUtils.tsindex 0b46130c0..a7859016d 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,8 +141,15 @@ export function renderComponentRoot( : getFunctionalFallthrough(attrs) } } catch (err) {- blockStack.length = 0- handleError(err, instance, ErrorCodes.RENDER_FUNCTION)+ resetBlockStack()+ try {+ handleError(err, instance, ErrorCodes.RENDER_FUNCTION)+ } catch (e) {+ // the error is rethrown (e.g. in dev) - restore the rendering context+ // so it doesn't leak into (and retain) subsequent renders+ setCurrentRenderingInstance(prev)+ throw e+ } 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..9236f7044 100644@@ -290,6 +290,18 @@ export function closeBlock(): void { currentBlock = blockStack[blockStack.length - 1] || null } +/**+ * Discard all open blocks. Used for recovery when a render function throws+ * after `openBlock()` but before the matching `createBlock()`, which would+ * otherwise leave a stale `currentBlock` collecting 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..85199e80e 100644@@ -1,5 +1,7 @@-import { createApp, createVNode } from 'vue'+import { createApp, createVNode, h, renderSlot, warn } from 'vue' import { renderToString } from '../src'+import * as vnodeModule from '../../runtime-core/src/vnode'+import * as renderContextModule from '../../runtime-core/src/componentRenderContext' describe('ssr: dynamic component', () => { test('resolved to component', async () => {@@ -77,4 +79,114 @@ describe('ssr: dynamic component', () => { ), ).toBe(`<div id="test"><span>slot</span></div>`) })++ describe('render error recovery', () => {+ // slot content of a dynamic component resolved to an element is+ // rendered in vnode mode, which goes through `renderSlot` ->+ // `openBlock()`. A throw before `createBlock()` must not leave a stale+ // block behind, otherwise every vnode created by later renders is pushed+ // into it and retained forever.+ const expectNoOpenBlock = () => {+ expect(vnodeModule.blockStack.length).toBe(0)+ expect(vnodeModule.currentBlock).toBe(null)+ }++ const Card = {+ props: { tag: { type: String, default: 'div' } },+ template: `<component :is="tag" class="card"><slot /></component>`,+ }++ const createHealthyApp = () =>+ createApp({+ components: { Card },+ data: () => ({ payload: { title: 'ok' } }),+ template: `<main><Card>{{ payload.title }}</Card></main>`,+ })++ const healthyHtml = `<main><div class="card"><!--[-->ok<!--]--></div></main>`++ test('slot content throwing inside a dynamic element', async () => {+ await expect(+ renderToString(+ createApp({+ components: { Card },+ data: () => ({ payload: null }),+ template: `<main><Card>{{ payload.title }}</Card></main>`,+ }),+ ),+ ).rejects.toThrow(`Cannot read properties of null`)+ expectNoOpenBlock()++ expect(await renderToString(createHealthyApp())).toBe(healthyHtml)+ expectNoOpenBlock()+ })++ test('block inside slot content throwing inside a dynamic element', async () => {+ await expect(+ renderToString(+ createApp({+ components: { Card },+ data: () => ({ payload: null, show: true }),+ template: `<main><Card><span v-if="show">{{ payload.title }}</span></Card></main>`,+ }),+ ),+ ).rejects.toThrow(`Cannot read properties of null`)+ expectNoOpenBlock()++ expect(await renderToString(createHealthyApp())).toBe(healthyHtml)+ expectNoOpenBlock()+ })++ test('render error does not leak the dev warning context', async () => {+ const failedApp = createApp({+ components: { Card },+ data: () => ({ payload: null }),+ template: `<main><Card>{{ payload.title }}</Card></main>`,+ })+ const failedAppWarnHandler = vi.fn()+ failedApp.config.warnHandler = failedAppWarnHandler+ await expect(renderToString(failedApp)).rejects.toThrow(+ `Cannot read properties of null`,+ )++ // a warning emitted outside of any component must not be attributed to+ // (and keep alive) a component of the failed render+ warn('outside of any component')+ expect(failedAppWarnHandler).not.toHaveBeenCalled()+ expect(`outside of any component`).toHaveBeenWarned()+ })++ test('slot throwing inside a non-compiled render function', async () => {+ const RenderFnCard = {+ __scopeId: 'data-v-failed',+ render(this: any) {+ return h('div', { class: 'card' }, [+ renderSlot(this.$slots, 'default'),+ ])+ },+ }+ await expect(+ renderToString(+ createApp({+ render: () =>+ h(RenderFnCard, null, {+ default: () => {+ throw new Error('slot error')+ },+ }),+ }),+ ),+ ).rejects.toThrow(`slot error`)+ expect(+ `Unhandled error during execution of render function`,+ ).toHaveBeenWarned()+ expectNoOpenBlock()+ // the rendering context of the failed component must not leak+ expect(renderContextModule.currentRenderingInstance).toBe(null)+ expect(renderContextModule.currentScopeId).toBe(null)++ expect(await renderToString(createHealthyApp())).toBe(healthyHtml)+ expectNoOpenBlock()+ })+ }) })packages/server-renderer/src/render.tsindex 8fc9b0128..3118c41f4 100644@@ -38,6 +38,7 @@ const { normalizeVNode, pushWarningContext, popWarningContext,+ resetBlockStack, } = ssrUtils export type SSRBuffer = SSRBufferItem[] & { hasAsync?: boolean }@@ -100,8 +101,12 @@ export function renderComponentVNode( null, )) if (__DEV__) pushWarningContext(vnode)- const res = setupComponent(instance, true /* isSSR */)- if (__DEV__) popWarningContext()+ let res: Promise<void> | undefined+ try {+ res = setupComponent(instance, true /* isSSR */)+ } finally {+ if (__DEV__) popWarningContext()+ } const hasAsyncSetup = isPromise(res) let prefetches = instance.sp /* LifecycleHooks.SERVER_PREFETCH */ if (hasAsyncSetup || prefetches) {@@ -128,6 +133,26 @@ function renderComponentSubTree( slotScopeId?: string, ): SSRBuffer | Promise<SSRBuffer> { if (__DEV__) pushWarningContext(instance.vnode)+ try {+ return doRenderComponentSubTree(instance, slotScopeId)+ } catch (err) {+ // a render error may have been thrown between `openBlock()` and the+ // matching `createBlock()` (e.g. inside a slot rendered via `renderSlot`+ // in vnode mode), leaving module-level block state behind. Since SSR+ // renders are not followed by a client-style re-render that would close+ // it, reset it here so later renders don't push their vnodes into the+ // stale block and keep them (and their apps) alive forever.+ resetBlockStack()+ throw err+ } finally {+ if (__DEV__) popWarningContext()+ }+}++function doRenderComponentSubTree(+ instance: ComponentInternalInstance,+ slotScopeId?: string,+): SSRBuffer | Promise<SSRBuffer> { const comp = instance.type as Component const { getBuffer, push } = createBuffer() if (isFunction(comp)) {@@ -217,7 +242,6 @@ function renderComponentSubTree( push(`<!---->`) } }- if (__DEV__) popWarningContext() return getBuffer() }
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'], }, },