Backtestsvuerun-20261003-231210#15113
SSR memory leak - options API watchers are created and never stopped with async setup()
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches fix the root cause the same way. They set the SSR-setup flag around `handleSetupResult` in the async-setup `.then` branch. As a result, `applyOptions` (options API `watch`, `$watch` in `created`, etc.) runs with `isInSSRComponentSetup` true, just as it does for sync setup. Non-immediate watchers are then skipped, and sync/immediate watchers get registered into `__watcherHandles` for cleanup. The core difference is how the flag is reset. Patch A unconditionally sets it to `false` afterwards. Patch B saves and restores the previous value. Patch B is the more defensive choice: if this continuation runs while the flag is already `true` for another reason, such as a nested or concurrent setup or a `withAsyncContext` restore, A would clobber it and B would not. The added risk in A is small but real, and B's comment explains why it restores. On tests, both include the issue's reproduction. A adds a GC-based retention test, which only runs with `--expose-gc` and so is skipped in many environments. B adds tests for `$watch` called in `created` and for a `flush: 'sync'` options watcher being tracked in `ctx.__watcherHandles` and stopped after render. Those exercise more of the paths affected by the fix and run unconditionally. Scope is equivalent and both diffs are minimal. B wins on slightly safer state handling and broader meaningful test coverage.
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
5m 23s
Wall-clock time in the container
Full test suite
No new failures
3,629 passed · 6 skipped · 3,635 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
92vs 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..a1a25e2a4 100644@@ -894,7 +894,18 @@ 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 that options API (watch, computed,+ // lifecycle hooks) applied after async setup behaves the same as+ // with a sync setup - e.g. non-immediate watchers are not created+ // (restore the previous value afterwards, since a concurrent+ // withAsyncContext continuation may still rely on it)+ const prevInSSRSetup = isInSSRComponentSetup+ setInSSRSetupState(true)+ try {+ handleSetupResult(instance, resolvedResult, isSSR)+ } finally {+ setInSSRSetupState(prevInSSRSetup)+ } }) .catch(e => { handleError(e, instance, ErrorCodes.SETUP_FUNCTION)packages/server-renderer/__tests__/ssrWatch.spec.tsindex 2b1ad98d2..ecf8e8a8f 100644@@ -292,6 +292,85 @@ describe('ssr: watchEffect', () => { await nextTick() expect(msg).toBe('unchanged') })++ 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('$watch in created should not be created for async setup components', async () => {+ const open = ref(true)+ const spy = vi.fn()++ const App = defineComponent({+ setup: () => Promise.resolve({}),+ created() {+ this.$watch(() => open.value, spy)+ },+ render() {+ return h('div', String(open.value))+ },+ })++ const html = await renderToString(createSSRApp(App))+ expect(html).toBe('<div>true</div>')++ open.value = false+ await nextTick()+ expect(spy).not.toHaveBeenCalled()+ })++ test('options-api flush: sync watchers should be stopped after render for async setup components', async () => {+ const count = ref(0)+ const spy = vi.fn()++ const App = defineComponent({+ setup: () => Promise.resolve({}),+ watch: {+ count: { handler: spy, flush: 'sync' },+ },+ computed: {+ count() {+ return count.value+ },+ },+ render() {+ return h('div', String(this.count))+ },+ })++ const ctx: SSRContext = {}+ const html = await renderToString(createSSRApp(App), ctx)+ expect(html).toBe('<div>0</div>')+ expect(ctx.__watcherHandles!.length).toBe(1)++ count.value = 1+ await nextTick()+ expect(spy).not.toHaveBeenCalled()+ }) }) describe.skipIf(!global.gc)('ssr: watch gc', () => {
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)+ }) })