Repository: nodejs/node
Pull request: test: fix flaky test-watch-mode-kill-signal-*

After the write triggers a restart of the grandchild, the newly spawned second grandchild can post another 'script ready' message before the stdout from the first grandchild is relayed by the watcher and processed by this parent process to kill the watcher. If we write again and trigger another restart, we can end up in an infinite loop and never receive the stdout of the grandchildren in time.
Only write once to verify the first grandchild process receives the expected signal. We don't care about the subsequent grandchild processes.

Drive-by: add some logs to aid debugging in case they fail again in the CI.

Refs: https://github.com/nodejs/node/issues/60297
Refs: https://github.com/nodejs/node/pull/60391

<!--
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: test/fixtures/kill-signal-for-watch.js
patch: @@ -1,4 +1,10 @@
-process.on('SIGTERM', () => { console.log('__SIGTERM received__'); process.exit(); });
-process.on('SIGINT', () => { console.log('__SIGINT received__'); process.exit(); });
-process.send('script ready');
+process.on('SIGTERM', () => {
+  console.log(`__SIGTERM received__ ${process.pid}`);
+  process.exit();
+});
+process.on('SIGINT', () => {
+  console.log(`__SIGINT received__ ${process.pid}`);
+  process.exit();
+});
+process.send(`script ready ${process.pid}`);
 setTimeout(() => {}, 100_000);

filename: test/parallel/test-watch-mode-kill-signal-default.mjs
patch: @@ -26,20 +26,37 @@ const child = spawn(
 );
 
 let stdout = '';
+let firstGrandchildPid;
 child.stdout.on('data', (data) => {
-  stdout += `${data}`;
-  if (/__(SIGINT|SIGTERM) received__/.test(stdout)) {
+  const dataStr = data.toString();
+  console.log(`[STDOUT] ${dataStr}`);
+  stdout += `${dataStr}`;
+  const match = dataStr.match(/__(SIGINT|SIGTERM) received__ (\d+)/);
+  if (match && match[2] === firstGrandchildPid) {
+    console.log(`[PARENT] Sending kill signal to watcher process: ${child.pid}`);
     child.kill();
   }
 });
 
+// After the write triggers a restart of the grandchild, the newly spawned second
+// grandchild can post another 'script ready' message before the stdout from the first
+// grandchild is relayed by the watcher and processed by this parent process to kill
+// the watcher. If we write again and trigger another restart, we can
+// end up in an infinite loop and never receive the stdout of the grandchildren in time.
+// Only write once to verify the first grandchild process receives the expected signal.
+// We don't care about the subsequent grandchild processes.
 child.on('message', (msg) => {
-  if (msg === 'script ready') {
-    writeFileSync(indexPath, indexContents);
+  console.log(`[MESSAGE]`, msg);
+  if (!firstGrandchildPid && typeof msg === 'string') {
+    const match = msg.match(/script ready (\d+)/);
+    if (match) {
+      firstGrandchildPid = match[1];  // This is the first grandchild
+      writeFileSync(indexPath, indexContents);
+    }
   }
 });
 
 await once(child, 'exit');
 
-assert.match(stdout, /__SIGTERM received__/);
-assert.doesNotMatch(stdout, /__SIGINT received__/);
+assert.match(stdout, new RegExp(`__SIGTERM received__ ${firstGrandchildPid}`));
+assert.doesNotMatch(stdout, new RegExp(`__SIGINT received__ ${firstGrandchildPid}`));

filename: test/parallel/test-watch-mode-kill-signal-override.mjs
patch: @@ -27,20 +27,40 @@ const child = spawn(
 );
 
 let stdout = '';
+let firstGrandchildPid;
 child.stdout.on('data', (data) => {
-  stdout += `${data}`;
-  if (/__(SIGINT|SIGTERM) received__/.test(stdout)) {
+  const dataStr = data.toString();
+  console.log(`[STDOUT] ${dataStr}`);
+  stdout += `${dataStr}`;
+  const match = dataStr.match(/__(SIGINT|SIGTERM) received__ (\d+)/);
+  if (match && match[2] === firstGrandchildPid) {
+    console.log(`[PARENT] Sending kill signal to watcher process: ${child.pid}`);
     child.kill();
   }
 });
 
+// After the write triggers a restart of the grandchild, the newly spawned second
+// grandchild can post another 'script ready' message before the stdout from the first
+// grandchild is relayed by the watcher and processed by this parent process to kill
+// the watcher. If we write again and trigger another restart, we can
+// end up in an infinite loop and never receive the stdout of the grandchildren in time.
+// Only write once to verify the first grandchild process receives the expected signal.
+// We don't care about the subsequent grandchild processes.
 child.on('message', (msg) => {
-  if (msg === 'script ready') {
-    writeFileSync(indexPath, indexContents);
+  console.log(`[MESSAGE]`, msg);
+  if (!firstGrandchildPid && typeof msg === 'string') {
+    const match = msg.match(/script ready (\d+)/);
+    if (match) {
+      firstGrandchildPid = match[1];  // This is the first grandchild
+      writeFileSync(indexPath, indexContents);
+    }
   }
 });
 
 await once(child, 'exit');
 
-assert.match(stdout, /__SIGINT received__/);
-assert.doesNotMatch(stdout, /__SIGTERM received__/);
+// The second grandchild, if there is one, could receive SIGTERM if it's killed as a
+// consequence of the parent being killed in this process instead of being killed by the
+// parent for file changes. Here we only care about the first grandchild.
+assert.match(stdout, new RegExp(`__SIGINT received__ ${firstGrandchildPid}`));
+assert.doesNotMatch(stdout, new RegExp(`__SIGTERM received__ ${firstGrandchildPid}`));