Repository: nodejs/node
Pull request: sea: only assert snapshot main function for main threads

Snapshot main functions are only loaded for main threads in single executable applications. Update the check to avoid asserting it in worker threads - this allows worker threads to be spawned in snapshot main functions bundled into a single executable application.

(Also noticed that worker_threads cannot be loaded in the snapshot builder script, which is to be expected currently since we haven't vetted the worker_threads module for snapshot building. I left a FIXME on how to vet the worker internals and make it loadable in the snapshot builder).

Fixes: https://github.com/nodejs/node/issues/56077

<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: src/node.cc
patch: @@ -320,7 +320,8 @@ MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
   CHECK(!env->isolate_data()->is_building_snapshot());
 
 #ifndef DISABLE_SINGLE_EXECUTABLE_APPLICATION
-  if (sea::IsSingleExecutable()) {
+  // Snapshot in SEA is only loaded for the main thread.
+  if (sea::IsSingleExecutable() && env->is_main_thread()) {
     sea::SeaResource sea = sea::FindSingleExecutableResource();
     // The SEA preparation blob building process should already enforce this,
     // this check is just here to guard against the unlikely case where
@@ -342,6 +343,9 @@ MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
   // move the pre-execution part into a different file that can be
   // reused when dealing with user-defined main functions.
   if (!env->snapshot_deserialize_main().IsEmpty()) {
+    // Custom worker snapshot is not supported yet,
+    // so workers can't have deserialize main functions.
+    CHECK(env->is_main_thread());
     return env->RunSnapshotDeserializeMain();
   }
 

filename: test/sequential/test-single-executable-application-snapshot-worker.js
patch: @@ -0,0 +1,80 @@
+'use strict';
+
+require('../common');
+
+const {
+  generateSEA,
+  skipIfSingleExecutableIsNotSupported,
+} = require('../common/sea');
+
+skipIfSingleExecutableIsNotSupported();
+
+// This tests the snapshot support in single executable applications.
+
+const tmpdir = require('../common/tmpdir');
+const { writeFileSync, existsSync } = require('fs');
+const {
+  spawnSyncAndAssert, spawnSyncAndExitWithoutError,
+} = require('../common/child_process');
+const assert = require('assert');
+
+const configFile = tmpdir.resolve('sea-config.json');
+const seaPrepBlob = tmpdir.resolve('sea-prep.blob');
+const outputFile = tmpdir.resolve(process.platform === 'win32' ? 'sea.exe' : 'sea');
+
+{
+  tmpdir.refresh();
+
+  // FIXME(joyeecheung): currently `worker_threads` cannot be loaded during the
+  // snapshot building process because internal/worker.js is accessing isMainThread at
+  // the top level (and there are maybe more code that access these at the top-level),
+  // and have to be loaded in the deserialized snapshot main function.
+  // Change these states to be accessed on-demand.
+  const code = `
+  const {
+    setDeserializeMainFunction,
+  } = require('v8').startupSnapshot;
+  setDeserializeMainFunction(() => {
+    const { Worker } = require('worker_threads');
+    new Worker("console.log('Hello from Worker')", { eval: true });
+  });
+  `;
+
+  writeFileSync(tmpdir.resolve('snapshot.js'), code, 'utf-8');
+  writeFileSync(configFile, `
+  {
+    "main": "snapshot.js",
+    "output": "sea-prep.blob",
+    "useSnapshot": true
+  }
+  `);
+
+  spawnSyncAndExitWithoutError(
+    process.execPath,
+    ['--experimental-sea-config', 'sea-config.json'],
+    {
+      cwd: tmpdir.path,
+      env: {
+        NODE_DEBUG_NATIVE: 'SEA',
+        ...process.env,
+      },
+    });
+
+  assert(existsSync(seaPrepBlob));
+
+  generateSEA(outputFile, process.execPath, seaPrepBlob);
+
+  spawnSyncAndAssert(
+    outputFile,
+    {
+      env: {
+        NODE_DEBUG_NATIVE: 'SEA',
+        ...process.env,
+      }
+    },
+    {
+      trim: true,
+      stdout: 'Hello from Worker'
+    }
+  );
+}