Backtestsvuerun-20261001-022054#15113
SSR memory leak - options API watchers are created and never stopped with async setup()
The merged fix was judged better than our patch.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches make the same source change in component.ts. In the async-setup `.then` branch, each wraps `handleSetupResult` in `setInSSRSetupState(true)`/`finally setInSSRSetupState(false)`. This restores the SSR setup flag that `applyOptions` (reached through `finishComponentSetup`) relies on to skip creating options-API watchers on the server. The root cause is therefore fixed identically, so correctness is equal. Patch B adds an explanatory comment, which is a small plus for craft. On tests, both add the issue's reproduction test, which fails before the fix and passes after it. Patch A also adds a GC-based regression test in the existing `ssr: watch gc` suite, matching that suite's existing pattern. That test checks that apps with async setup plus a watcher on global state are no longer retained, which targets the memory leak the issue actually reports. The extra test makes Patch A's coverage meaningfully stronger, and that outweighs Patch B's comment.
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
2m 33s8 turns
Wall-clock time in the container
Full test suite
No new failures
3,627 passed · 6 skipped · 3,633 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
36vs 76 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.40
Steps to reproduce
originally reported in https://github.com/nuxt/nuxt/issues/30782
- create an options API component with an
async setup(), acomputedproperty that reads shared module-level state, and awatchon that - render it on the server and then mutate the shared state after the render is done
- see that the watcher is still active on the server
Reproduction
test('options-api watchers should not be created for async setup components', async () => {
const open = ref(true)
const spy = vi.fn()
const App = defineComponent({
setup: () => Promise.resolve({}),
computed: {
isOpen() {
return open.value
},
},
watch: {
isOpen: spy,
},
render() {
return h('div', String(this.isOpen))
},
})
const html = await renderToString(createSSRApp(App))
expect(html).toBe('<div>true</div>')
// mutating the state after the request is done should not trigger the watcher
open.value = false
await nextTick()
expect(spy).not.toHaveBeenCalled()
})
What is expected?
the same behavior as with a synchronous setup: regular watchers declared via the watch option don't run during SSR and don't survive the render
mutating the shared state after renderToString resolves should not trigger anything
What is actually happening?
when setup() returns a Promise, the watch option creates a live watcher on the server that is never stopped
if this subscribes to state that outlives the request, it keeps the entire component instance (and app) reachable forever
System Info
Any additional comments?
_No response_
The two patches
packages/runtime-core/src/component.tsindex c46741bee..202565644 100644@@ -894,7 +894,13 @@ function setupStatefulComponent( // return the promise so server-renderer can wait on it return setupResult .then((resolvedResult: unknown) => {- handleSetupResult(instance, resolvedResult, isSSR)+ // restore SSR setup state so options API watchers are not created+ setInSSRSetupState(true)+ try {+ handleSetupResult(instance, resolvedResult, isSSR)+ } finally {+ setInSSRSetupState(false)+ } }) .catch(e => { handleError(e, instance, ErrorCodes.SETUP_FUNCTION)packages/server-renderer/__tests__/ssrWatch.spec.tsindex 2b1ad98d2..fbcda7142 100644@@ -212,6 +212,34 @@ describe('ssr: watch', () => { expect(beforeAwaitTriggered).toBe(false) expect(afterAwaitTriggered).toBe(false) })++ test('options-api watchers should not be created for async setup components', async () => {+ const open = ref(true)+ const spy = vi.fn()++ const App = defineComponent({+ setup: () => Promise.resolve({}),+ computed: {+ isOpen() {+ return open.value+ },+ },+ watch: {+ isOpen: spy,+ },+ render() {+ return h('div', String(this.isOpen))+ },+ })++ const html = await renderToString(createSSRApp(App))+ expect(html).toBe('<div>true</div>')++ // mutating the state after the request is done should not trigger the watcher+ open.value = false+ await nextTick()+ expect(spy).not.toHaveBeenCalled()+ }) }) describe('ssr: watchEffect', () => {
packages/runtime-core/src/component.tsindex c46741bee..162a6ad44 100644@@ -894,7 +894,12 @@ function setupStatefulComponent( // return the promise so server-renderer can wait on it return setupResult .then((resolvedResult: unknown) => {- handleSetupResult(instance, resolvedResult, isSSR)+ setInSSRSetupState(true)+ try {+ handleSetupResult(instance, resolvedResult, isSSR)+ } finally {+ setInSSRSetupState(false)+ } }) .catch(e => { handleError(e, instance, ErrorCodes.SETUP_FUNCTION)packages/server-renderer/__tests__/ssrWatch.spec.tsindex 2b1ad98d2..2dad83cd2 100644@@ -130,6 +130,35 @@ describe('ssr: watch', () => { expect(msg).toBe('start') }) + // #15113+ test('options-api watchers should not be created for async setup components', async () => {+ const open = ref(true)+ const spy = vi.fn()++ const App = defineComponent({+ setup: () => Promise.resolve({}),+ computed: {+ isOpen() {+ return open.value+ },+ },+ watch: {+ isOpen: spy,+ },+ render() {+ return h('div', String(this.isOpen))+ },+ })++ const html = await renderToString(createSSRApp(App))+ expect(html).toBe('<div>true</div>')++ // mutating the state after the request is done should not trigger the watcher+ open.value = false+ await nextTick()+ expect(spy).not.toHaveBeenCalled()+ })+ test('should not run non-immediate watchers registered after async context restore', async () => { const text = ref('start') let beforeAwaitTriggered = false@@ -351,4 +380,44 @@ describe.skipIf(!global.gc)('ssr: watch gc', () => { expect(weakRefs.filter(ref => ref.deref()).length).toBe(0) })++ // #15113+ test('options-api should not retain apps with async setup + watcher on global state', async () => {+ const weakRefs: { deref(): unknown | undefined }[] = []++ const open = ref(true)++ const App = defineComponent({+ setup: () => Promise.resolve({}),+ computed: {+ isOpen() {+ return open.value+ },+ },+ watch: {+ isOpen() {},+ },+ render() {+ return h('div', String(this.isOpen))+ },+ })++ async function renderOnce() {+ const app = createSSRApp(App)+ // @ts-expect-error ES2021 API+ weakRefs.push(new WeakRef(app))+ const html = await renderToString(app)+ expect(html).toBe('<div>true</div>')+ }++ 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)+ }) })
What the agent reported
When a component had an async setup(), watchers from its watch option stayed live on the server after renderToString finished. That's fixed now, and the regression test from the report failed before the change and passes after it.
What was wrong: setupComponent turns off the "inside SSR setup" flag as soon as setup() returns. With an async setup(), the options API (computed, watch, lifecycle hooks) is only applied later, after the promise resolves, and by then the flag is already off. So the guard in apiWatch.ts that skips non-immediate watchers during SSR never kicked in. A live watcher was created, never stopped, and kept the component instance and app reachable through any shared state it read.
What I changed:
- The fix (
packages/runtime-core/src/component.ts,setupStatefulComponent): in the server-side async-setup branch, the flag is turned back on aroundhandleSetupResult(...)and turned off again in afinally. The options API is now applied in the same SSR mode as with a synchronoussetup(). - Side effects: the same as the sync path. Options-API computed properties don't cache on the server,
mounted-style hooks are dropped during SSR, andserverPrefetchstill registers. Watchers withflush: 'sync'are still collected and stopped after the render. - The test (
packages/server-renderer/__tests__/ssrWatch.spec.ts): the test from the report, added to thessr: watchblock unchanged.
Test evidence:
- Before the fix: the new test failed with "expected vi.fn() to not be called at all, but actually been called 1 times", with arguments
(false, true, cleanup). - After the fix:
./bt-teston all ofpackages/server-renderer, plus runtime-core'sapiOptions,apiWatch,Suspenseandhydrationspecs, passed 611 of 611 in 21 files. No existing test was changed. - Review: the reviewer found no blocking issues. It suggested also testing a
flush: 'sync'option watcher, which I didn't add.
Requirements:
- Watchers from the
watchoption are not live after rendering a component with an asyncsetup(): done; the regression test covers it. - Same behaviour as a synchronous
setup()(non-immediate watchers don't run during SSR and don't outlast the render): done. The async path now goes through the same SSR guard as the sync path, and the existing SSR watch, computed and suspense tests still pass. - Changing the shared state after
renderToStringresolves triggers nothing: done; the test asserts the spy is never called afteropen.value = falseandnextTick().
All changes are uncommitted in the working tree.