Backtestsvuerun-20261021-133314#15070

Issue #15070 Merged fix PR #15071 Run 21 Oct 2026 · run-20261021-133314 vuejs/core

SSR memory leak after a render error in a dynamic component

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches fix the reported leak and pass all four independent tests, so the decision rests on robustness and completeness. The root cause is that a throw inside the vdom fallback path (renderSlot/withCtx under a dynamic component) leaves `blockStack`/`currentBlock` populated, so every later `createVNode` is pushed into a stale, module-level block array and retained forever.

Patch A adds a `resetBlocks()` helper that clears both `blockStack` and `currentBlock`, and calls it at the two component render boundaries: `renderComponentRoot` (client/render-function path) and the SSR `renderComponentSubTree` ssrRender path. This follows the pre-existing design in `renderComponentRoot`, which already reset `blockStack.length = 0` on error, and it fixes that reset's latent incompleteness (it never cleared `currentBlock`, so vnodes created afterwards still went into the stale block until the next `closeBlock`). Because it resets at the boundary, it is a catch-all for any helper that opens a block and throws, not just the two helpers identified. In SSR no blocks are legitimately open when a component subtree renders (render functions run to completion before the buffer is walked), so a full reset is safe. Tests are thorough: a runtime-core unit test checking `blockStack`/`currentBlock` after a throwing render, an SSR test reproducing the issue and asserting block state directly, and a GC test wired into the `--expose-gc` project.

Patch B unwinds blocks locally in `renderSlot` (with a try/catch plus moving `_d = true` into a finally, which is good craft) and in `withCtx`. This is precise and preserves outer blocks, and its v-if test is a nice addition. However, it only covers the two openers it identified; any other block-opening path that throws during SSR vdom fallback would still leak, and it leaves the incomplete `blockStack.length = 0` reset in `renderComponentRoot` untouched, so `currentBlock` can still be stale there on the client. Its test coverage is a single GC file with no direct assertion on block state.

A addresses the problem at the boundary where errors are already handled, fixes the pre-existing partial reset, and ships more diagnostic tests, so it is the more complete and robust fix. B is a reasonable, targeted alternative but narrower.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

12m 14s

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

140vs 152 merged

Changed lines, ours vs merged

Vue 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

Our patch+136 −4
packages/runtime-core/__tests__/errorHandling.spec.tsindex 0cd3efa58..efa57eacb 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,36 @@ describe('error handling', () => {     expect(fn).toHaveBeenCalledWith(err, 'render function')   }) +  test('in render function after opening a block', () => {+    const err = new Error('foo')+    const fn = vi.fn()++    const Comp = {+      setup() {+        onErrorCaptured((err, instance, info) => {+          fn(err, info)+          return false+        })+        return () => h(Child)+      },+    }++    const Child = {+      setup() {+        return () => {+          openBlock()+          throw err+        }+      },+    }++    render(h(Comp), nodeOps.createElement('div'))+    expect(fn).toHaveBeenCalledWith(err, 'render function')+    // the block left open by the failed render must be discarded+    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..266d91327 100644@@ -8,11 +8,11 @@ import {   Comment,   type VNode,   type VNodeArrayChildren,-  blockStack,   cloneVNode,   createVNode,   isVNode,   normalizeVNode,+  resetBlocks, } from './vnode' import { ErrorCodes, handleError } from './errorHandling' import {@@ -141,7 +141,7 @@ export function renderComponentRoot(         : getFunctionalFallthrough(attrs)     }   } catch (err) {-    blockStack.length = 0+    resetBlocks()     handleError(err, instance, ErrorCodes.RENDER_FUNCTION)     result = createVNode(Comment)   }packages/runtime-core/src/index.tsindex 792a28b25..5d557e1f6 100644@@ -401,7 +401,7 @@ import { } from './component' import { renderComponentRoot } from './componentRenderUtils' import { setCurrentRenderingInstance } from './componentRenderContext'-import { isVNode, normalizeVNode } from './vnode'+import { isVNode, normalizeVNode, resetBlocks } 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+  resetBlocks: typeof resetBlocks } = {   createComponentInstance,   setupComponent,@@ -427,6 +428,7 @@ const _ssrUtils: {   ensureValidVNode,   pushWarningContext,   popWarningContext,+  resetBlocks, }  /**packages/runtime-core/src/vnode.tsindex b4fe6f237..cce42ef74 100644@@ -290,6 +290,17 @@ export function closeBlock(): void {   currentBlock = blockStack[blockStack.length - 1] || null } +/**+ * Discard any blocks left open by a render that threw before its blocks could+ * be closed, so that later renders don't track their dynamic children into+ * (and retain) the stale block.+ * @internal+ */+export function resetBlocks(): 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..9b322e4bf 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,29 @@ describe('ssr: dynamic component', () => {       ),     ).toBe(`<div id="test"><span>slot</span></div>`)   })++  test('render error in slot of dynamic component should not leave stale blocks', async () => {+    const Card = {+      props: { tag: { type: String, default: 'div' } },+      template: `<component :is="tag" class="card"><slot /></component>`,+    }+    const createAppWithPayload = (payload: any) =>+      createApp({+        components: { Card },+        data: () => ({ payload }),+        template: `<main><Card>{{ payload.title }}</Card></main>`,+      })++    await expect(renderToString(createAppWithPayload(null))).rejects.toThrow(+      /title/,+    )+    expect(blockStack.length).toBe(0)+    expect(currentBlock).toBe(null)++    expect(await renderToString(createAppWithPayload({ title: 'ok' }))).toBe(+      `<main><div class="card"><!--[-->ok<!--]--></div></main>`,+    )+    expect(blockStack.length).toBe(0)+    expect(currentBlock).toBe(null)+  }) })packages/server-renderer/__tests__/ssrGc.spec.tsnew file mode 100644index 000000000..4b6ba28fb@@ -0,0 +1,50 @@+import { createApp } from 'vue'+import { renderToString } from '../src'++const gc = () =>+  new Promise<void>(resolve => {+    setTimeout(() => {+      global.gc!()+      resolve()+    })+  })++describe.skipIf(!global.gc)('ssr: gc', () => {+  test('should not retain apps rendered after a render error in a dynamic component slot', async () => {+    const weakRefs: { deref(): unknown | undefined }[] = []++    const Card = {+      props: { tag: { type: String, default: 'div' } },+      template: `<component :is="tag" class="card"><slot /></component>`,+    }+    const createAppWithPayload = (payload: any) =>+      createApp({+        components: { Card },+        data: () => ({ payload }),+        template: `<main><Card>{{ payload.title }}</Card></main>`,+      })++    await expect(renderToString(createAppWithPayload(null))).rejects.toThrow(+      /title/,+    )++    async function renderOnce() {+      const app = createAppWithPayload({ title: 'ok' })+      // @ts-expect-error ES2021 API+      weakRefs.push(new WeakRef(app))+      expect(await renderToString(app)).toBe(+        `<main><div class="card"><!--[-->ok<!--]--></div></main>`,+      )+    }++    for (let i = 0; i < 10; i++) {+      await renderOnce()+    }++    for (let i = 0; i < 5; i++) {+      await gc()+    }++    expect(weakRefs.filter(ref => ref.deref()).length).toBe(0)+  })+})packages/server-renderer/src/render.tsindex 8fc9b0128..4a3df4d84 100644@@ -38,6 +38,7 @@ const {   normalizeVNode,   pushWarningContext,   popWarningContext,+  resetBlocks, } = ssrUtils  export type SSRBuffer = SSRBufferItem[] & { hasAsync?: boolean }@@ -201,6 +202,12 @@ function renderComponentSubTree(           instance.data,           instance.ctx,         )+      } catch (err) {+        // the render may have thrown inside vdom code (e.g. a non-SSR slot+        // rendered via renderSlot()) after opening a block; discard it so it+        // doesn't leak into and retain subsequent renders+        resetBlocks()+        throw err       } finally {         setCurrentRenderingInstance(prev)       }vitest.config.tsindex 2fbc92f92..7e1814cfd 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__/ssrGc.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__/ssrGc.spec.ts',+          ],           execArgv: ['--expose-gc'],         },       }, 
Merged fix · PR #15071+128 −24
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'],         },       },