Backtestsvuerun-20261013-093701#15070

Issue #15070 Merged fix PR #15071 Run 13 Oct 2026 · run-20261013-093701 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: a block opened via openBlock() in vnode-mode slot code (renderSlot inside `<component :is>`) is never closed when the slot throws. The leftover currentBlock then collects every vnode created afterwards.

Patch B fixes this where the block is opened. renderSlot gets a try/catch that unwinds the stack, and withCtx unwinds blocks left by inline blocks such as v-if. That is a precise fix and also helps the client. However, it leaves renderComponentRoot's existing `blockStack.length = 0`, which empties the array without resetting `currentBlock`. So a render-function or functional component that throws mid-block still leaves a stale currentBlock that retains later vnodes. That is the same leak class through a sibling path. B also adds bookkeeping to withCtx, which runs on every slot invocation on the client.

Patch A closes the blocks left open at the SSR ssrRender boundary, recording the depth before render and unwinding to it on throw. This covers the issue scenario, the v-if variant and any other vnode-mode code that throws mid-block. It also replaces `blockStack.length = 0` with `closeBlocksAbove(0)`, which properly resets currentBlock and fixes the render-function path that B misses. It restores currentRenderingInstance when handleError rethrows, preventing the failed instance and its scope id from leaking. It also wraps renderComponentSubTree in try/finally so the dev warning context is popped. These are directly related leak paths from a failed SSR render, not unrelated churn. The re-indentation of renderComponentSubTree obscures the diff somewhat, but the logic is clear.

Tests: B's GC/WeakRef tests directly measure the reported symptom, which is strong evidence. A's tests use `createBlock('div').dynamicChildren` to detect a leaked open block. They would fail before the fix, and they cover four scenarios: the issue case, v-if, the stale warning context, and the render-function path that leaks the rendering instance. B's tests are slightly more faithful to the symptom; A's cover more failure modes.

Overall, A fixes the reported case plus closely related leak paths that B leaves open, so A is the more complete and robust 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

10m 19s

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

315vs 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+234 −81
packages/runtime-core/src/componentRenderUtils.tsindex 0b46130c0..8b4feac91 100644@@ -8,8 +8,8 @@ import {   Comment,   type VNode,   type VNodeArrayChildren,-  blockStack,   cloneVNode,+  closeBlocksAbove,   createVNode,   isVNode,   normalizeVNode,@@ -141,8 +141,15 @@ export function renderComponentRoot(         : getFunctionalFallthrough(attrs)     }   } catch (err) {-    blockStack.length = 0-    handleError(err, instance, ErrorCodes.RENDER_FUNCTION)+    closeBlocksAbove(0)+    try {+      handleError(err, instance, ErrorCodes.RENDER_FUNCTION)+    } catch (e) {+      // restore the rendering instance if the error is re-thrown, otherwise+      // the failed instance stays referenced and leaks into later renders+      setCurrentRenderingInstance(prev)+      throw e+    }     result = createVNode(Comment)   } packages/runtime-core/src/index.tsindex 792a28b25..384fb1234 100644@@ -401,7 +401,12 @@ import { } from './component' import { renderComponentRoot } from './componentRenderUtils' import { setCurrentRenderingInstance } from './componentRenderContext'-import { isVNode, normalizeVNode } from './vnode'+import {+  closeBlocksAbove,+  getBlockStackDepth,+  isVNode,+  normalizeVNode,+} from './vnode' import { ensureValidVNode } from './helpers/renderSlot' import { popWarningContext, pushWarningContext } from './warning' @@ -416,6 +421,8 @@ const _ssrUtils: {   ensureValidVNode: typeof ensureValidVNode   pushWarningContext: typeof pushWarningContext   popWarningContext: typeof popWarningContext+  getBlockStackDepth: typeof getBlockStackDepth+  closeBlocksAbove: typeof closeBlocksAbove } = {   createComponentInstance,   setupComponent,@@ -427,6 +434,8 @@ const _ssrUtils: {   ensureValidVNode,   pushWarningContext,   popWarningContext,+  getBlockStackDepth,+  closeBlocksAbove, }  /**packages/runtime-core/src/vnode.tsindex b4fe6f237..28a0dacbf 100644@@ -290,6 +290,26 @@ export function closeBlock(): void {   currentBlock = blockStack[blockStack.length - 1] || null } +/**+ * Close all blocks opened beyond the given stack depth. Used to restore the+ * block stack when a render throws between `openBlock()` and `createBlock()`,+ * otherwise the leftover `currentBlock` would collect every vnode created+ * afterwards.+ * @internal+ */+export function closeBlocksAbove(depth: number = 0): void {+  while (blockStack.length > depth) {+    closeBlock()+  }+}++/**+ * @internal+ */+export function getBlockStackDepth(): number {+  return blockStack.length+}+ // 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..df8caf8ba 100644@@ -1,4 +1,10 @@-import { createApp, createVNode } from 'vue'+import {+  createApp,+  createBlock,+  createVNode,+  resolveDynamicComponent,+  warn,+} from 'vue' import { renderToString } from '../src'  describe('ssr: dynamic component', () => {@@ -77,4 +83,100 @@ describe('ssr: dynamic component', () => {       ),     ).toBe(`<div id="test"><span>slot</span></div>`)   })++  describe('render error recovery', () => {+    // a block created without a matching openBlock() collects whatever block+    // was left open on the global block stack+    const getLeakedBlockChildren = () => createBlock('div').dynamicChildren++    const Card = {+      props: { tag: { type: String, default: 'div' } },+      template: `<component :is="tag" class="card"><slot /></component>`,+    }++    const renderHealthy = (template: string) =>+      renderToString(+        createApp(+          { components: { Card }, props: ['payload'], template },+          { payload: { title: 'ok' } },+        ),+      )++    test('slot of a dynamic component throws', async () => {+      const template = `<main><Card>{{ payload.title }}</Card></main>`+      await expect(+        renderToString(+          createApp(+            { components: { Card }, props: ['payload'], template },+            { payload: null },+          ),+        ),+      ).rejects.toThrow(`Cannot read properties of null`)++      expect(await renderHealthy(template)).toBe(+        `<main><div class="card"><!--[-->ok<!--]--></div></main>`,+      )+      // vnodes from subsequent renders must not be retained+      expect(getLeakedBlockChildren()).toEqual([])+    })++    test('v-if content of a dynamic component throws', async () => {+      const template =+        `<main><component :is="'div'">` ++        `<span v-if="payload">{{ payload.missing.title }}</span>` ++        `</component></main>`+      await expect(+        renderToString(+          createApp(+            { props: ['payload'], template },+            { payload: { missing: null } },+          ),+        ),+      ).rejects.toThrow(`Cannot read properties of null`)++      expect(await renderHealthy(template.replace('missing.', ''))).toBe(+        `<main><div><span>ok</span></div></main>`,+      )+      expect(getLeakedBlockChildren()).toEqual([])+    })++    test('failed render does not leave a stale warning context', async () => {+      const warnHandler = vi.fn()+      const app = createApp({+        components: { Card },+        template: `<Card>{{ payload.title }}</Card>`,+        data: () => ({ payload: null }),+      })+      app.config.warnHandler = warnHandler+      await expect(renderToString(app)).rejects.toThrow(+        `Cannot read properties of null`,+      )++      // a warning issued outside of any render must not be attributed to+      // the component of the failed render+      warn('outside of render')+      expect(warnHandler).not.toHaveBeenCalled()+      expect(`outside of render`).toHaveBeenWarned()+    })++    test('render function of a scoped component throws', async () => {+      const Broken = {+        __scopeId: 'data-v-broken',+        props: ['payload'],+        render: (ctx: any) =>+          createVNode(resolveDynamicComponent('div'), null, ctx.payload.title),+      }+      await expect(+        renderToString(createApp(Broken, { payload: null })),+      ).rejects.toThrow(`Cannot read properties of null`)+      expect(`Unhandled error during execution of render`).toHaveBeenWarned()++      // the failed instance must not stay the current rendering instance,+      // which would leak it and its scope id into subsequent renders+      expect(+        await renderToString(createApp({ template: `<div>ok</div>` })),+      ).toBe(`<div>ok</div>`)+      expect(getLeakedBlockChildren()).toEqual([])+    })+  }) })packages/server-renderer/src/render.tsindex 8fc9b0128..a0ee5efdd 100644@@ -38,6 +38,8 @@ const {   normalizeVNode,   pushWarningContext,   popWarningContext,+  getBlockStackDepth,+  closeBlocksAbove, } = ssrUtils  export type SSRBuffer = SSRBufferItem[] & { hasAsync?: boolean }@@ -128,97 +130,110 @@ function renderComponentSubTree(   slotScopeId?: string, ): SSRBuffer | Promise<SSRBuffer> {   if (__DEV__) pushWarningContext(instance.vnode)-  const comp = instance.type as Component-  const { getBuffer, push } = createBuffer()-  if (isFunction(comp)) {-    let root = renderComponentRoot(instance)-    // #5817 scope ID attrs not falling through if functional component doesn't-    // have props-    if (!(comp as FunctionalComponent).props) {-      for (const key in instance.attrs) {-        if (key.startsWith(`data-v-`)) {-          ;(root.props || (root.props = {}))[key] = ``+  try {+    const comp = instance.type as Component+    const { getBuffer, push } = createBuffer()+    if (isFunction(comp)) {+      let root = renderComponentRoot(instance)+      // #5817 scope ID attrs not falling through if functional component+      // doesn't have props+      if (!(comp as FunctionalComponent).props) {+        for (const key in instance.attrs) {+          if (key.startsWith(`data-v-`)) {+            ;(root.props || (root.props = {}))[key] = ``+          }         }       }-    }-    renderVNode(push, (instance.subTree = root), instance, slotScopeId)-  } else {-    if (-      (!instance.render || instance.render === NOOP) &&-      !instance.ssrRender &&-      !comp.ssrRender &&-      isString(comp.template)-    ) {-      comp.ssrRender = ssrCompile(comp.template, instance)-    }+      renderVNode(push, (instance.subTree = root), instance, slotScopeId)+    } else {+      if (+        (!instance.render || instance.render === NOOP) &&+        !instance.ssrRender &&+        !comp.ssrRender &&+        isString(comp.template)+      ) {+        comp.ssrRender = ssrCompile(comp.template, instance)+      } -    const ssrRender = instance.ssrRender || comp.ssrRender-    if (ssrRender) {-      // optimized-      // resolve fallthrough attrs-      let attrs = instance.inheritAttrs !== false ? instance.attrs : undefined-      let hasCloned = false+      const ssrRender = instance.ssrRender || comp.ssrRender+      if (ssrRender) {+        // optimized+        // resolve fallthrough attrs+        let attrs = instance.inheritAttrs !== false ? instance.attrs : undefined+        let hasCloned = false -      let cur = instance-      while (true) {-        const scopeId = cur.vnode.scopeId-        if (scopeId) {-          if (!hasCloned) {-            attrs = { ...attrs }-            hasCloned = true+        let cur = instance+        while (true) {+          const scopeId = cur.vnode.scopeId+          if (scopeId) {+            if (!hasCloned) {+              attrs = { ...attrs }+              hasCloned = true+            }+            attrs![scopeId] = ''+          }+          const parent = cur.parent+          if (parent && parent.subTree && parent.subTree === cur.vnode) {+            // parent is a non-SSR compiled component and is rendering this+            // component as root. inherit its scopeId if present.+            cur = parent+          } else {+            break           }-          attrs![scopeId] = ''-        }-        const parent = cur.parent-        if (parent && parent.subTree && parent.subTree === cur.vnode) {-          // parent is a non-SSR compiled component and is rendering this-          // component as root. inherit its scopeId if present.-          cur = parent-        } else {-          break         }-      } -      if (slotScopeId) {-        if (!hasCloned) attrs = { ...attrs }-        const slotScopeIdList = slotScopeId.trim().split(' ')-        for (let i = 0; i < slotScopeIdList.length; i++) {-          attrs![slotScopeIdList[i]] = ''+        if (slotScopeId) {+          if (!hasCloned) attrs = { ...attrs }+          const slotScopeIdList = slotScopeId.trim().split(' ')+          for (let i = 0; i < slotScopeIdList.length; i++) {+            attrs![slotScopeIdList[i]] = ''+          }         }-      } -      // set current rendering instance for asset resolution-      const prev = setCurrentRenderingInstance(instance)-      try {-        ssrRender(-          instance.proxy,+        // set current rendering instance for asset resolution+        const prev = setCurrentRenderingInstance(instance)+        const prevBlockDepth = getBlockStackDepth()+        try {+          ssrRender(+            instance.proxy,+            push,+            instance,+            attrs,+            // compiler-optimized bindings+            instance.props,+            instance.setupState,+            instance.data,+            instance.ctx,+          )+        } catch (err) {+          // vnode-based render code (e.g. a slot rendered by `<component :is>`)+          // may throw between openBlock() and createBlock(). Close the blocks+          // left open so that subsequent renders don't keep pushing vnodes+          // into a leaked block.+          closeBlocksAbove(prevBlockDepth)+          throw err+        } finally {+          setCurrentRenderingInstance(prev)+        }+      } else if (instance.render && instance.render !== NOOP) {+        renderVNode(           push,+          (instance.subTree = renderComponentRoot(instance)),           instance,-          attrs,-          // compiler-optimized bindings-          instance.props,-          instance.setupState,-          instance.data,-          instance.ctx,+          slotScopeId,+        )+      } else {+        const componentName = comp.name || comp.__file || `<Anonymous>`+        warn(+          `Component ${componentName} is missing template or render function.`,         )-      } finally {-        setCurrentRenderingInstance(prev)+        push(`<!---->`)       }-    } else if (instance.render && instance.render !== NOOP) {-      renderVNode(-        push,-        (instance.subTree = renderComponentRoot(instance)),-        instance,-        slotScopeId,-      )-    } else {-      const componentName = comp.name || comp.__file || `<Anonymous>`-      warn(`Component ${componentName} is missing template or render function.`)-      push(`<!---->`)     }+    return getBuffer()+  } finally {+    if (__DEV__) popWarningContext()   }-  if (__DEV__) popWarningContext()-  return getBuffer() }  export function renderVNode( 
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'],         },       },