Skip to content

Commit e2a7e65

Browse files
committed
test(process): synchronize descendant termination proof
1 parent b05213c commit e2a7e65

1 file changed

Lines changed: 86 additions & 40 deletions

File tree

‎src/process/exec.test.ts‎

Lines changed: 86 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
// Exec tests cover command execution, output capture, and cancellation behavior.
22
import type { ChildProcess } from "node:child_process";
3-
import { EventEmitter } from "node:events";
3+
import { EventEmitter, once } from "node:events";
4+
import { existsSync } from "node:fs";
45
import fs from "node:fs/promises";
6+
import path from "node:path";
57
import process from "node:process";
68
import { fileURLToPath } from "node:url";
79
import { describe, expect, it, vi } from "vitest";
810
import { setVerbose } from "../global-state.js";
11+
import { isPidAlive } from "../shared/pid-alive.js";
12+
import { readPidFile, waitForPidToExit } from "../test-utils/process-tree.js";
13+
import { withTempDir } from "../test-utils/temp-dir.js";
914
import { attachChildProcessBridge } from "./child-process-bridge.js";
15+
import * as execSpawn from "./exec-spawn.js";
1016
import {
1117
resolveCommandEnv,
1218
resolveProcessExitCode,
@@ -532,48 +538,88 @@ describe("runCommandBuffered", () => {
532538
it.runIf(process.platform !== "win32")(
533539
"force-kills inherited-pipe descendants after the direct child exits",
534540
{ timeout: 5_000 },
535-
async () => {
536-
const descendantSource =
537-
"process.on('SIGTERM', () => {}); setInterval(() => process.stdout.write('.'), 20)";
538-
const parentSource = [
539-
"const { spawn } = require('node:child_process')",
540-
`const child = spawn(${JSON.stringify(process.execPath)}, ['-e', ${JSON.stringify(descendantSource)}], { stdio: ['ignore', 'inherit', 'inherit'] })`,
541-
"child.unref()",
542-
"process.stdout.write(`PID:${child.pid}\\n`)",
543-
].join(";");
544-
const result = await runCommandBuffered([process.execPath, "-e", parentSource], {
545-
// The timeout starts before Node initializes; loaded CI still needs time to spawn and report the descendant.
546-
timeoutMs: 500,
547-
});
548-
const pidMatch = result.stdout.toString().match(/PID:(\d+)/u);
549-
if (!pidMatch) {
550-
throw new Error(`missing descendant pid in ${result.stdout.toString()}`);
551-
}
552-
const descendantPid = Number(pidMatch[1]);
553-
554-
try {
555-
expect(result).toMatchObject({ code: null, termination: "timeout" });
556-
let descendantExited = false;
557-
for (let attempt = 0; attempt < 40; attempt += 1) {
541+
async () =>
542+
withTempDir("openclaw-exec-descendant-", async (dir) => {
543+
const pidPath = path.join(dir, "descendant.pid");
544+
const termPath = path.join(dir, "sigterm");
545+
// Acknowledge only after the handler and keepalive exist. Stay quiet so
546+
// inherited-pipe release cannot kill the descendant through EPIPE.
547+
const descendantSource = [
548+
"const { writeFileSync } = require('node:fs')",
549+
`process.on('SIGTERM', () => writeFileSync(${JSON.stringify(termPath)}, 'handled'))`,
550+
"setInterval(() => {}, 1_000)",
551+
"process.send('ready')",
552+
].join(";");
553+
const parentSource = [
554+
"const { spawn } = require('node:child_process')",
555+
"const { writeFileSync } = require('node:fs')",
556+
`const child = spawn(process.execPath, ['-e', ${JSON.stringify(descendantSource)}], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'] })`,
557+
`child.once('message', () => { writeFileSync(${JSON.stringify(pidPath)}, String(child.pid)); process.exit(0) })`,
558+
].join(";");
559+
const realSetTimeout = setTimeout;
560+
const spawnSpy = vi.spyOn(execSpawn, "spawnCommandWithInvocation");
561+
let parent: ChildProcess | undefined;
562+
let command: ReturnType<typeof runCommandBuffered> | undefined;
563+
// Freeze deadlines, not subprocess I/O: Node startup must not consume the
564+
// timeout or the 100ms inherited-pipe idle grace. Polling must stay real.
565+
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
566+
try {
567+
let settled = false;
568+
command = runCommandBuffered([process.execPath, "-e", parentSource], {
569+
timeoutMs: 50,
570+
}).then((result) => {
571+
settled = true;
572+
return result;
573+
});
574+
const spawnResult = spawnSpy.mock.results[0];
575+
if (spawnResult?.type !== "return") {
576+
throw new Error("command did not spawn");
577+
}
578+
parent = spawnResult.value.child.nodeChildProcess;
579+
if (!parent) {
580+
throw new Error("command did not expose a child process");
581+
}
582+
expect(await once(parent, "exit", { signal: AbortSignal.timeout(2_000) })).toEqual([
583+
0,
584+
null,
585+
]);
586+
const descendantPid = await readPidFile(pidPath);
587+
expect(isPidAlive(descendantPid)).toBe(true);
588+
expect(settled).toBe(false);
589+
590+
await vi.advanceTimersByTimeAsync(50);
591+
for (let attempt = 0; attempt < 40 && !existsSync(termPath); attempt += 1) {
592+
await new Promise<void>((resolve) => {
593+
realSetTimeout(resolve, 25);
594+
});
595+
}
596+
expect(existsSync(termPath)).toBe(true);
597+
expect(isPidAlive(descendantPid)).toBe(true);
598+
expect(settled).toBe(false);
599+
600+
await vi.advanceTimersByTimeAsync(execSpawn.COMMAND_PROCESS_TREE_KILL_GRACE_MS);
601+
expect(await command).toMatchObject({ code: null, termination: "timeout" });
602+
vi.useRealTimers();
603+
expect(await waitForPidToExit(descendantPid)).toBe(true);
604+
} finally {
558605
try {
559-
process.kill(descendantPid, 0);
560-
} catch {
561-
descendantExited = true;
562-
break;
606+
if (parent?.pid) {
607+
try {
608+
process.kill(-parent.pid, "SIGKILL");
609+
} catch {
610+
// Already gone.
611+
}
612+
}
613+
if (vi.isFakeTimers()) {
614+
await vi.runAllTimersAsync();
615+
}
616+
} finally {
617+
vi.useRealTimers();
618+
spawnSpy.mockRestore();
563619
}
564-
await new Promise<void>((resolve) => {
565-
setTimeout(resolve, 25);
566-
});
567-
}
568-
expect(descendantExited).toBe(true);
569-
} finally {
570-
try {
571-
process.kill(descendantPid, "SIGKILL");
572-
} catch {
573-
// Already gone.
620+
await command;
574621
}
575-
}
576-
},
622+
}),
577623
);
578624

579625
it.runIf(process.platform !== "win32")(

0 commit comments

Comments
 (0)