Commit 50ba1ec6c2b for nodejs

commit 50ba1ec6c2b33bf18f21958af500d9e0e8144c7f
Author: Paolo Insogna <paolo@cowtech.it>
Date:   Fri Nov 20 07:53:49 2026 +0100

    worker: add diagnostic channel 'worker_threads.main.registry'

    Signed-off-by: Paolo Insogna <paolo@cowtech.it>
    Assisted-By: OpenAI:GPT-6.1 Sol <openai/gpt-6.1-sol>
    PR-URL: https://github.com/nodejs/node/pull/67311
    Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
    Reviewed-By: James M Snell <jasnell@gmail.com>

diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md
index 242f8259c87..c40feab5dae 100644
--- a/doc/api/diagnostics_channel.md
+++ b/doc/api/diagnostics_channel.md
@@ -2021,6 +2021,20 @@ added: v16.18.0

 Emitted when a new thread is created.

+##### Event: `'worker_threads.main.registry'`
+
+* `threadIds` {number\[]} A snapshot of the registered worker thread IDs.
+
+Emitted only on the main thread whenever the worker thread registry changes,
+including workers created by other workers. Each event contains a snapshot of
+the registered worker thread IDs. The main thread's ID (`0`) is not included.
+
+The registry tracks workers through their internal messaging ports. Registration
+can occur before a worker is online. Removal occurs when the parent thread
+processes the worker's exit and can be delayed if the parent thread is blocked.
+Consequently, a snapshot does not guarantee that every listed worker is ready or
+still running.
+
 #### SQLite

 <!-- YAML
diff --git a/lib/internal/worker/messaging.js b/lib/internal/worker/messaging.js
index d1573b870ef..df590efe537 100644
--- a/lib/internal/worker/messaging.js
+++ b/lib/internal/worker/messaging.js
@@ -1,6 +1,7 @@
 'use strict';

 const {
+  ArrayFrom,
   AtomicsNotify,
   AtomicsStore,
   AtomicsWaitAsync,
@@ -30,6 +31,8 @@ const { MessageChannel } = require('internal/worker/io');

 const { validateNumber } = require('internal/validators');

+const registryChannel = require('diagnostics_channel').channel('worker_threads.main.registry');
+
 const messageTypes = {
   REGISTER_MAIN_THREAD_PORT: 'registerMainThreadPort',
   UNREGISTER_MAIN_THREAD_PORT: 'unregisterMainThreadPort',
@@ -72,12 +75,26 @@ function handleMessageFromThread(message) {

         // Never block the thread on this port
         port.unref();
+
+        if (registryChannel.hasSubscribers) {
+          registryChannel.publish({
+            __proto__: null,
+            threadIds: ArrayFrom(threadsPorts.keys()),
+          });
+        }
       }

       break;
     case messageTypes.UNREGISTER_MAIN_THREAD_PORT:
       threadsPorts.get(message.threadId).close();
       threadsPorts.delete(message.threadId);
+
+      if (registryChannel.hasSubscribers) {
+        registryChannel.publish({
+          __proto__: null,
+          threadIds: ArrayFrom(threadsPorts.keys()),
+        });
+      }
       break;
     case messageTypes.SEND_MESSAGE_TO_WORKER:
       {
diff --git a/test/parallel/test-diagnostics-channel-worker-threads-registry.js b/test/parallel/test-diagnostics-channel-worker-threads-registry.js
new file mode 100644
index 00000000000..cd28c0926c2
--- /dev/null
+++ b/test/parallel/test-diagnostics-channel-worker-threads-registry.js
@@ -0,0 +1,87 @@
+'use strict';
+const common = require('../common');
+const assert = require('assert');
+const { once } = require('events');
+const dc = require('diagnostics_channel');
+const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
+
+// Only the main thread publishes registry updates; allow the test's own workers.
+if (!isMainThread && workerData !== 'parent' && workerData !== 'child') {
+  common.skip('This test must be started on the main thread');
+}
+
+const channelName = 'worker_threads.main.registry';
+
+if (isMainThread) {
+  // Expect one snapshot for each registration and removal in the worker tree.
+  const snapshots = [];
+  const childRegistered = Promise.withResolvers();
+  const childRemoved = Promise.withResolvers();
+
+  dc.subscribe(channelName, common.mustCall((message) => {
+    assert.strictEqual(Object.getPrototypeOf(message), null);
+    assert.deepStrictEqual(Object.keys(message), ['threadIds']);
+    snapshots.push(message.threadIds);
+
+    if (snapshots.length === 2) {
+      childRegistered.resolve();
+    }
+    if (snapshots.length === 3) {
+      childRemoved.resolve();
+    }
+  }, 4));
+
+  async function test() {
+    const worker = new Worker(__filename, { workerData: 'parent' });
+    const threadId = worker.threadId;
+
+    // The child ID and its registry update arrive on independent channels.
+    const [[childId]] = await Promise.all([
+      once(worker, 'message'),
+      once(worker, 'online'),
+      childRegistered.promise,
+    ]);
+
+    assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId]]);
+
+    // Remove the nested worker first, keeping its parent alive for the update.
+    worker.postMessage('stop');
+    await childRemoved.promise;
+
+    assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId], [threadId]]);
+
+    // Let the parent exit naturally, then check that earlier snapshots are intact.
+    const exited = once(worker, 'exit');
+    worker.postMessage('finish');
+    const [code] = await exited;
+
+    assert.strictEqual(code, 0);
+    assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId], [threadId], []]);
+  }
+
+  test().then(common.mustCall());
+} else {
+  // Neither the parent worker nor its child should publish this channel locally.
+  dc.subscribe(channelName, common.mustNotCall());
+
+  if (workerData === 'child') {
+    // Keep the child alive until its parent explicitly terminates it.
+    parentPort.on('message', common.mustNotCall());
+  } else {
+    async function run() {
+      const worker = new Worker(__filename, { workerData: 'child' });
+      await once(worker, 'online');
+      parentPort.postMessage(worker.threadId);
+
+      // The main thread requests termination after observing both registrations.
+      await once(parentPort, 'message');
+      assert.strictEqual(await worker.terminate(), 1);
+
+      // Wait until the main thread observes the child's removal before exiting.
+      await once(parentPort, 'message');
+      parentPort.close();
+    }
+
+    run().then(common.mustCall());
+  }
+}