From 8a8e44c6d32aeec74335e3b17b9d4d09e9dd7584 Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Sun, 22 Nov 2026 14:33:48 -0800 Subject: [PATCH 1/4] Turbopack: scale down the Node.js pool after the module graph is built in production In production builds, whole_app_module_graphs connected the module graph operation without waiting for it, then scaled the Node.js process pool to zero. The scale-down ran before the graph's loaders had spawned any processes, so they all stayed alive until the build exited. Wait for the graph first, as development mode already does. --- crates/next-api/src/project.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/next-api/src/project.rs b/crates/next-api/src/project.rs index 56643da3986..f956a31e5a6 100644 --- a/crates/next-api/src/project.rs +++ b/crates/next-api/src/project.rs @@ -1854,6 +1854,12 @@ impl Project { ) -> Result> { let module_graphs_op = whole_app_module_graph_operation(self); let module_graphs_vc = if self.next_mode().await?.is_production() { + // Wait for the graph, and everything computed under it, before scaling down the + // Node.js pool below. `connect()` alone doesn't wait, so the pool would be scaled + // down before the graph's loaders spawn their processes, which then stay alive until + // the build exits. Connect it rather than returning the read value so its issues + // still reach the caller. + module_graphs_op.resolve().strongly_consistent().await?; module_graphs_op.connect() } else { let vc = module_graphs_op.resolve().strongly_consistent().await?; From 21766c4989a6f3ede967bd7c3304f9112e19bb37 Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Sun, 22 Nov 2026 16:31:43 -0800 Subject: [PATCH 2/4] Turbopack: also wait for the graph in whole_app_module_graphs_without_dropping_issues, add regression test Use the Vc returned by resolve() (which already connects the operation) instead of connecting again, apply the same wait to the MCP variant, and check from runAfterProductionCompile that no loader processes outlive compilation. --- crates/next-api/src/project.rs | 25 ++++++-------- .../next.config.mjs | 33 +++++++++++++++++++ .../webpack-loader-traced-imports.test.ts | 9 +++++ 3 files changed, 52 insertions(+), 15 deletions(-) diff --git a/crates/next-api/src/project.rs b/crates/next-api/src/project.rs index f956a31e5a6..130e802e9cc 100644 --- a/crates/next-api/src/project.rs +++ b/crates/next-api/src/project.rs @@ -1841,9 +1841,10 @@ impl Project { self: ResolvedVc, ) -> Result> { let module_graphs_op = whole_app_module_graph_operation(self); - let module_graphs_vc = module_graphs_op.connect(); + // Wait for the graph before scaling down the Node.js pool, see `whole_app_module_graphs`. + let module_graphs_vc = module_graphs_op.resolve().strongly_consistent().await?; scale_down_node_pool(self).await?; - Ok(module_graphs_vc) + Ok(*module_graphs_vc) } /// Computes the whole app module graph, dropping issues in development mode so that @@ -1853,21 +1854,15 @@ impl Project { self: ResolvedVc, ) -> Result> { let module_graphs_op = whole_app_module_graph_operation(self); - let module_graphs_vc = if self.next_mode().await?.is_production() { - // Wait for the graph, and everything computed under it, before scaling down the - // Node.js pool below. `connect()` alone doesn't wait, so the pool would be scaled - // down before the graph's loaders spawn their processes, which then stay alive until - // the build exits. Connect it rather than returning the read value so its issues - // still reach the caller. - module_graphs_op.resolve().strongly_consistent().await?; - module_graphs_op.connect() - } else { - let vc = module_graphs_op.resolve().strongly_consistent().await?; + // Wait for the graph, and everything computed under it, before scaling down the Node.js + // pool below. Otherwise the pool would be scaled down before the graph's loaders spawn + // their processes, which would then stay alive until the build exits. + let module_graphs_vc = module_graphs_op.resolve().strongly_consistent().await?; + if !self.next_mode().await?.is_production() { module_graphs_op.drop_issues(); - *vc - }; + } scale_down_node_pool(self).await?; - Ok(module_graphs_vc) + Ok(*module_graphs_vc) } #[turbo_tasks::function] diff --git a/test/production/app-dir/webpack-loader-traced-imports/next.config.mjs b/test/production/app-dir/webpack-loader-traced-imports/next.config.mjs index 1a221408600..49b407d5b29 100644 --- a/test/production/app-dir/webpack-loader-traced-imports/next.config.mjs +++ b/test/production/app-dir/webpack-loader-traced-imports/next.config.mjs @@ -1,8 +1,33 @@ +import { execFileSync } from 'node:child_process' +import fs from 'node:fs/promises' import path from 'node:path' import { fileURLToPath } from 'node:url' const dirname = path.dirname(fileURLToPath(import.meta.url)) +/** + * Counts Turbopack's Node.js loader processes that are still running. They are + * children of the build process, so this only sees this build's processes. + */ +function countLoaderProcesses() { + try { + return execFileSync('ps', ['-A', '-ww', '-o', 'ppid=,command='], { + encoding: 'utf8', + }) + .split('\n') + .map((line) => line.trim().match(/^(\d+)\s+(.*)$/)) + .filter( + (match) => + match && + Number(match[1]) === process.pid && + match[2].includes('[turbopack-node]') + ).length + } catch { + // `ps` isn't available, e.g. on Windows. + return 'unknown' + } +} + export default { turbopack: { rules: { @@ -11,4 +36,12 @@ export default { }, }, }, + compiler: { + async runAfterProductionCompile({ distDir }) { + await fs.writeFile( + path.join(distDir, 'loader-processes.txt'), + String(countLoaderProcesses()) + ) + }, + }, } diff --git a/test/production/app-dir/webpack-loader-traced-imports/webpack-loader-traced-imports.test.ts b/test/production/app-dir/webpack-loader-traced-imports/webpack-loader-traced-imports.test.ts index 847b733bad1..e878c21575a 100644 --- a/test/production/app-dir/webpack-loader-traced-imports/webpack-loader-traced-imports.test.ts +++ b/test/production/app-dir/webpack-loader-traced-imports/webpack-loader-traced-imports.test.ts @@ -9,4 +9,13 @@ describe('webpack-loader-traced-imports', () => { const $ = await next.render$('/') expect($('main').text()).toBe('Webpack loader traced imports') }) + + // Turbopack's Node.js loader processes should exit once the module graph is + // built, instead of staying alive (and holding memory) until the build exits. + // `runAfterProductionCompile` in next.config.mjs counts them right after + // compilation. Webpack has no such processes, and counting needs `ps`. + // @force-gate turbopack && !windows + it('stops loader processes after compilation', async () => { + expect(await next.readFile('.next/loader-processes.txt')).toBe('0') + }) }) From f282410cd67ab38e966bd4a74063900a1c6f5454 Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Sun, 22 Nov 2026 17:07:40 -0800 Subject: [PATCH 3/4] Turbopack: scale down the Node.js pool in warm builds too Mark whole_app_module_graphs session dependent. With a warm cache, loaders run again for changed modules, but the graph's own tasks don't execute again, so the pool was never scaled down and their processes stayed alive until the build exited. Also scale down when computing the graph fails. Make the backends' scale_down/scale_zero infallible (they never failed), and debug-assert at shutdown that no idle Node.js processes are left in builds that don't watch the file system. --- crates/next-api/src/project.rs | 26 +++++++++---- .../src/next_api/project.rs | 12 ++++++ .../webpack-loader-traced-imports.test.ts | 18 +++++++++ .../crates/turbopack-node/src/backend.rs | 6 ++- turbopack/crates/turbopack-node/src/lib.rs | 11 ++++++ .../src/process_pool/heap_queue.rs | 4 ++ .../turbopack-node/src/process_pool/mod.rs | 37 ++++++++++-------- .../turbopack-node/src/worker_pool/mod.rs | 21 ++++------ .../src/worker_pool/operation.rs | 39 ++++++++++--------- 9 files changed, 115 insertions(+), 59 deletions(-) diff --git a/crates/next-api/src/project.rs b/crates/next-api/src/project.rs index 130e802e9cc..e0d622720bc 100644 --- a/crates/next-api/src/project.rs +++ b/crates/next-api/src/project.rs @@ -1836,20 +1836,28 @@ impl Project { /// /// Use this instead of [Self::whole_app_module_graphs] when you need to collect issues from /// the computation (e.g. for the `get_compilation_issues` MCP tool). - #[turbo_tasks::function] + /// + /// Session dependent so that it scales down the Node.js pool in every session, see + /// [Self::whole_app_module_graphs]. + #[turbo_tasks::function(session_dependent)] pub async fn whole_app_module_graphs_without_dropping_issues( self: ResolvedVc, ) -> Result> { let module_graphs_op = whole_app_module_graph_operation(self); // Wait for the graph before scaling down the Node.js pool, see `whole_app_module_graphs`. - let module_graphs_vc = module_graphs_op.resolve().strongly_consistent().await?; + let module_graphs_vc = module_graphs_op.resolve().strongly_consistent().await; scale_down_node_pool(self).await?; - Ok(*module_graphs_vc) + Ok(*module_graphs_vc?) } /// Computes the whole app module graph, dropping issues in development mode so that /// individual routes don't each report every issue from the shared graph. - #[turbo_tasks::function(root)] + /// + /// Session dependent so that it executes, and scales down the Node.js pool, in every session. + /// With a warm cache, loaders run again for changed modules, but the graph's own tasks don't + /// necessarily execute again. Executing it again is cheap: the graph is read from the cache, + /// and its result doesn't change unless the graph did. + #[turbo_tasks::function(root, session_dependent)] pub async fn whole_app_module_graphs( self: ResolvedVc, ) -> Result> { @@ -1857,11 +1865,13 @@ impl Project { // Wait for the graph, and everything computed under it, before scaling down the Node.js // pool below. Otherwise the pool would be scaled down before the graph's loaders spawn // their processes, which would then stay alive until the build exits. - let module_graphs_vc = module_graphs_op.resolve().strongly_consistent().await?; + // Scale down even if computing the graph failed, so a failed build doesn't keep them. + let module_graphs_vc = module_graphs_op.resolve().strongly_consistent().await; + scale_down_node_pool(self).await?; + let module_graphs_vc = module_graphs_vc?; if !self.next_mode().await?.is_production() { module_graphs_op.drop_issues(); } - scale_down_node_pool(self).await?; Ok(*module_graphs_vc) } @@ -3199,9 +3209,9 @@ async fn scale_down_node_pool(project: ResolvedVc) -> Result<()> { let execution_context = project.execution_context().await?; let node_backend = execution_context.node_backend.into_trait_ref().await?; if *project.is_watch_enabled().await? { - node_backend.scale_down()?; + node_backend.scale_down(); } else { - node_backend.scale_zero()?; + node_backend.scale_zero(); } Ok(()) } diff --git a/crates/next-napi-bindings/src/next_api/project.rs b/crates/next-napi-bindings/src/next_api/project.rs index e81bb59df61..cde2bd089fd 100644 --- a/crates/next-napi-bindings/src/next_api/project.rs +++ b/crates/next-napi-bindings/src/next_api/project.rs @@ -422,6 +422,8 @@ pub struct ProjectInstance { // Never locked across an await point. exit_receiver: Mutex>, shutdown: Arc, + /// Whether the file system is watched, i.e. whether the Node.js pools are kept warm. + watch: bool, // Pin the ProjectContainer for as long as this struct survives. _container_gc_root: GcRoot, } @@ -651,6 +653,7 @@ pub fn project_new<'env>( let options = options.into_project_options(); let is_dev = options.dev; + let watch = options.watch.enable; let root_path = options.root_path.clone(); let shutdown = Arc::new(ShutdownHooks::default()); let shutdown_hooks = shutdown.clone(); @@ -717,6 +720,7 @@ pub fn project_new<'env>( container, exit_receiver: Mutex::new(Some(exit_receiver)), shutdown, + watch, _container_gc_root: container_gc_root, }), }, @@ -939,6 +943,14 @@ pub async fn project_shutdown( #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External, ) -> napi::Result<()> { let tt = project.turbopack_ctx.turbo_tasks(); + // Without watching, the pools were scaled to zero once the module graph was built (see + // `Project::whole_app_module_graphs`), so no Node.js process should still be holding memory. + debug_assert!( + project.watch || turbopack_node::idle_node_process_count() == 0, + "{} idle Node.js processes are still running at shutdown, but they should have been \ + stopped after building the module graph", + turbopack_node::idle_node_process_count() + ); let eager_purge = TurboMalloc::enter_eager_purge_mode(); run_shutdown_hooks(project).await; tt.stop_and_wait().await; diff --git a/test/production/app-dir/webpack-loader-traced-imports/webpack-loader-traced-imports.test.ts b/test/production/app-dir/webpack-loader-traced-imports/webpack-loader-traced-imports.test.ts index e878c21575a..0e0f39ea481 100644 --- a/test/production/app-dir/webpack-loader-traced-imports/webpack-loader-traced-imports.test.ts +++ b/test/production/app-dir/webpack-loader-traced-imports/webpack-loader-traced-imports.test.ts @@ -3,6 +3,11 @@ import { nextTestSetup } from 'e2e-utils' describe('webpack-loader-traced-imports', () => { const { next } = nextTestSetup({ files: __dirname, + env: { + // Locally built native bindings disable the persistent cache in a dirty + // checkout, which the warm build below relies on. + TURBO_ENGINE_IGNORE_DIRTY: '1', + }, }) it('builds when a loader resolves a module with a dynamic require', async () => { @@ -18,4 +23,17 @@ describe('webpack-loader-traced-imports', () => { it('stops loader processes after compilation', async () => { expect(await next.readFile('.next/loader-processes.txt')).toBe('0') }) + + // A warm build runs the loader again for the edited page, without + // necessarily executing the module graph's own tasks again. + // @force-gate turbopack && !windows + it('stops loader processes after compilation in a warm build', async () => { + await next.stop() + await next.patchFile('app/page.tsx', (content) => + content!.replace('', ' (edited)') + ) + const { exitCode } = await next.build() + expect(exitCode).toBe(0) + expect(await next.readFile('.next/loader-processes.txt')).toBe('0') + }) }) diff --git a/turbopack/crates/turbopack-node/src/backend.rs b/turbopack/crates/turbopack-node/src/backend.rs index 8e3ea209c66..a05a96e4a09 100644 --- a/turbopack/crates/turbopack-node/src/backend.rs +++ b/turbopack/crates/turbopack-node/src/backend.rs @@ -48,7 +48,9 @@ pub trait NodeBackend: sealed::Sealed { fn create_pool(&self, options: CreatePoolOptions) -> CreatePoolFuture; - fn scale_down(&self) -> Result<()>; + /// Stops all idle processes of each pool except one. + fn scale_down(&self); - fn scale_zero(&self) -> Result<()>; + /// Stops all idle processes of each pool. + fn scale_zero(&self); } diff --git a/turbopack/crates/turbopack-node/src/lib.rs b/turbopack/crates/turbopack-node/src/lib.rs index 28ee9737374..729524ab41b 100644 --- a/turbopack/crates/turbopack-node/src/lib.rs +++ b/turbopack/crates/turbopack-node/src/lib.rs @@ -38,6 +38,17 @@ pub fn worker_threads_backend() -> Vc> { Vc::upcast(worker_pool::WorkerThreadsBackend.cell()) } +/// The number of idle Node.js processes and worker threads across all pools. Pools are scaled +/// to zero after building the module graph when not watching, so this should be 0 at shutdown. +pub fn idle_node_process_count() -> usize { + let count = 0; + #[cfg(all(feature = "process_pool", not(target_family = "wasm")))] + let count = count + process_pool::idle_process_count(); + #[cfg(feature = "worker_pool")] + let count = count + worker_pool::idle_worker_count(); + count +} + #[turbo_tasks::function] async fn emit( intermediate_asset: Vc>, diff --git a/turbopack/crates/turbopack-node/src/process_pool/heap_queue.rs b/turbopack/crates/turbopack-node/src/process_pool/heap_queue.rs index f35750b077d..e2469fb6784 100644 --- a/turbopack/crates/turbopack-node/src/process_pool/heap_queue.rs +++ b/turbopack/crates/turbopack-node/src/process_pool/heap_queue.rs @@ -46,6 +46,10 @@ impl HeapQueue { Ok(item) } + pub(super) fn len(&self) -> usize { + self.heap.lock().len() + } + pub(super) fn reduce_to_one(&self) { // Drain the semaphore permits let mut n = self.semaphore.forget_permits(usize::MAX); diff --git a/turbopack/crates/turbopack-node/src/process_pool/mod.rs b/turbopack/crates/turbopack-node/src/process_pool/mod.rs index f86ffe7f883..f5643f7e822 100644 --- a/turbopack/crates/turbopack-node/src/process_pool/mod.rs +++ b/turbopack/crates/turbopack-node/src/process_pool/mod.rs @@ -733,14 +733,12 @@ impl NodeBackend for ChildProcessesBackend { }) } - fn scale_down(&self) -> Result<()> { - ChildProcessPool::scale_down(); - Ok(()) + fn scale_down(&self) { + scale_down(); } - fn scale_zero(&self) -> Result<()> { - ChildProcessPool::scale_zero(); - Ok(()) + fn scale_zero(&self) { + scale_zero(); } } @@ -867,19 +865,26 @@ impl ChildProcessPool { .await .context("creating new process") } +} - fn scale_down() { - let pools = ACTIVE_POOLS.lock().clone(); - for pool in pools { - pool.reduce_to_one(); - } +/// The number of idle processes across all pools. +pub(crate) fn idle_process_count() -> usize { + ACTIVE_POOLS.lock().iter().map(|pool| pool.len()).sum() +} + +/// Stops all idle processes of each pool except one. +fn scale_down() { + let pools = ACTIVE_POOLS.lock().clone(); + for pool in pools { + pool.reduce_to_one(); } +} - fn scale_zero() { - let pools = ACTIVE_POOLS.lock().clone(); - for pool in pools { - pool.reduce_to_zero(&ACTIVE_POOLS); - } +/// Stops all idle processes of each pool. +fn scale_zero() { + let pools = ACTIVE_POOLS.lock().clone(); + for pool in pools { + pool.reduce_to_zero(&ACTIVE_POOLS); } } diff --git a/turbopack/crates/turbopack-node/src/worker_pool/mod.rs b/turbopack/crates/turbopack-node/src/worker_pool/mod.rs index 7e8c045e4ad..7703c4c2427 100644 --- a/turbopack/crates/turbopack-node/src/worker_pool/mod.rs +++ b/turbopack/crates/turbopack-node/src/worker_pool/mod.rs @@ -197,25 +197,18 @@ impl NodeBackend for WorkerThreadsBackend { }) } - fn scale_down(&self) -> Result<()> { - WorkerThreadPool::scale_down(); - Ok(()) + fn scale_down(&self) { + WORKER_POOL_OPERATION.scale_down(); } - fn scale_zero(&self) -> Result<()> { - WorkerThreadPool::scale_zero(); - Ok(()) + fn scale_zero(&self) { + WORKER_POOL_OPERATION.scale_zero(); } } -impl WorkerThreadPool { - fn scale_down() { - let _ = WORKER_POOL_OPERATION.scale_down(); - } - - fn scale_zero() { - let _ = WORKER_POOL_OPERATION.scale_zero(); - } +/// The number of idle workers across all pools. +pub(crate) fn idle_worker_count() -> usize { + WORKER_POOL_OPERATION.idle_worker_count() } #[async_trait::async_trait] diff --git a/turbopack/crates/turbopack-node/src/worker_pool/operation.rs b/turbopack/crates/turbopack-node/src/worker_pool/operation.rs index 101a382137b..96eb18bb9fe 100644 --- a/turbopack/crates/turbopack-node/src/worker_pool/operation.rs +++ b/turbopack/crates/turbopack-node/src/worker_pool/operation.rs @@ -93,7 +93,15 @@ impl WorkerPoolOperation { self.pools.lock().entry(worker_options).or_default().clone() } - pub(super) fn scale_down(&self) -> Result<()> { + pub(super) fn idle_worker_count(&self) -> usize { + self.pools + .lock() + .values() + .map(|state| state.idle_workers.lock().len()) + .sum() + } + + pub(super) fn scale_down(&self) { let mut to_terminate = Vec::new(); { @@ -111,15 +119,12 @@ impl WorkerPoolOperation { } } - to_terminate - .into_iter() - .map(|(worker_options, worker_id)| self.terminate_worker(worker_options, worker_id)) - .collect::>>()?; - - Ok(()) + for (worker_options, worker_id) in to_terminate { + self.terminate_worker(worker_options, worker_id); + } } - pub(super) fn scale_zero(&self) -> Result<()> { + pub(super) fn scale_zero(&self) { let mut to_terminate = Vec::new(); { @@ -135,18 +140,14 @@ impl WorkerPoolOperation { } } - to_terminate - .into_iter() - .map(|(worker_options, worker_id)| self.terminate_worker(worker_options, worker_id)) - .collect::>>()?; - - Ok(()) + for (worker_options, worker_id) in to_terminate { + self.terminate_worker(worker_options, worker_id); + } } - fn terminate_worker(&self, worker_options: Arc, worker_id: u32) -> Result<()> { + fn terminate_worker(&self, worker_options: Arc, worker_id: u32) { self.remove_worker_channel(worker_id); worker_thread::terminate_worker(worker_options, worker_id); - Ok(()) } fn remove_worker_channel(&self, worker_id: u32) { @@ -182,7 +183,7 @@ impl WorkerPoolOperation { pub(super) static WORKER_POOL_OPERATION: LazyLock = LazyLock::new(WorkerPoolOperation::default); -fn terminate_worker(worker_options: Arc, worker_id: u32) -> Result<()> { +fn terminate_worker(worker_options: Arc, worker_id: u32) { WORKER_POOL_OPERATION.terminate_worker(worker_options, worker_id) } @@ -286,7 +287,7 @@ impl Operation for WorkerOperation { self.state.stats.lock().remove_worker(); self.on_drop = None; } - terminate_worker(self.worker_options.clone(), self.worker_id)?; + terminate_worker(self.worker_options.clone(), self.worker_id); Ok(ExitStatus::default()) } @@ -295,7 +296,7 @@ impl Operation for WorkerOperation { self.state.stats.lock().remove_worker(); self.on_drop = None; // Clearing the return-to-pool callback does not stop the underlying Node.js worker. - let _ = terminate_worker(self.worker_options.clone(), self.worker_id); + terminate_worker(self.worker_options.clone(), self.worker_id); } } } From 8f27b967ff45c7aad82c28529eba012c9ff32eb2 Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Sun, 22 Nov 2026 19:24:36 -0800 Subject: [PATCH 4/4] Turbopack: avoid a lock-order inversion when counting idle Node.js processes HeapQueue locks its heap before ACTIVE_POOLS, so release ACTIVE_POOLS before reading the heaps, as scale_down/scale_zero already do. --- turbopack/crates/turbopack-node/src/process_pool/mod.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/turbopack/crates/turbopack-node/src/process_pool/mod.rs b/turbopack/crates/turbopack-node/src/process_pool/mod.rs index f5643f7e822..5faa6abd94a 100644 --- a/turbopack/crates/turbopack-node/src/process_pool/mod.rs +++ b/turbopack/crates/turbopack-node/src/process_pool/mod.rs @@ -869,7 +869,10 @@ impl ChildProcessPool { /// The number of idle processes across all pools. pub(crate) fn idle_process_count() -> usize { - ACTIVE_POOLS.lock().iter().map(|pool| pool.len()).sum() + // Release `ACTIVE_POOLS` before locking the heaps: `HeapQueue` locks its heap first, then + // `ACTIVE_POOLS`, so holding both in the other order could deadlock. + let pools = ACTIVE_POOLS.lock().clone(); + pools.iter().map(|pool| pool.len()).sum() } /// Stops all idle processes of each pool except one.