File size: 10,379 Bytes
3144483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import { spawn } from "node:child_process";
import { once } from "node:events";
import { constants as osConstants } from "node:os";
import process from "node:process";
import { setImmediate as nextTurn } from "node:timers/promises";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createDeferredCore } from "../shared/deferred.js";
import * as processIdentity from "../shared/pid-alive.js";
import { killPidIfAlive, waitForPidToExit } from "../test-utils/process-tree.js";
import { COMMAND_PROCESS_TREE_KILL_GRACE_MS } from "./exec-spawn.js";
import { createCommandTerminationController } from "./exec-termination.js";

afterEach(() => vi.restoreAllMocks());

async function withOwnedTree(
  run: (tree: { parent: ReturnType<typeof spawn>; descendantPid: number }) => Promise<void>,
) {
  const descendant = `process.on('SIGTERM',()=>{});setInterval(()=>{},1000);process.send('ready');`;
  const parent = spawn(
    process.execPath,
    [
      "-e",
      `const {spawn}=require('node:child_process');
      process.on('SIGTERM',()=>{});
      const child=spawn(process.execPath,['-e',${JSON.stringify(descendant)}],{stdio:['ignore','ignore','ignore','ipc']});
      child.once('message',()=>process.send(child.pid));setInterval(()=>{},1000);`,
    ],
    { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] },
  );
  const closed = once(parent, "close");
  let descendantPid: number | undefined;
  try {
    const [message] = await once(parent, "message", { signal: AbortSignal.timeout(2_000) });
    descendantPid = Number(message);
    expect(Number.isSafeInteger(descendantPid)).toBe(true);
    await run({ parent, descendantPid });
  } finally {
    killPidIfAlive(parent.pid);
    killPidIfAlive(descendantPid);
    await closed;
    if (descendantPid) {
      expect(await waitForPidToExit(descendantPid)).toBe(true);
    }
  }
}

describe.skipIf(process.platform === "win32")("command process-group settlement", () => {
  it.each([
    { name: "an absent group", probeError: "ESRCH", needsGrace: false },
    { name: "surviving descendants", probeError: undefined, needsGrace: true },
    { name: "a permission-denied group", probeError: "EPERM", needsGrace: true },
  ])(
    "settles $name after a failed root without losing cleanup ownership",
    async ({ probeError, needsGrace }) => {
      vi.useFakeTimers();
      vi.spyOn(processIdentity, "getFileLockProcessStartTime").mockReturnValue(123);
      const kill = vi.spyOn(process, "kill").mockImplementation(() => {
        if (probeError) {
          throw Object.assign(new Error(probeError), { code: probeError });
        }
        return true;
      });
      const child = { pid: 4242, exitCode: 7, signalCode: null, kill: vi.fn(() => true) };
      const cancelController = new AbortController();
      const controller = createCommandTerminationController({
        child,
        cancelController,
        processTree: { mode: "graceful" },
        killGraceMs: 300,
        isChildExited: () => true,
        isCommandSettled: () => true,
      });
      try {
        expect(controller.terminate()).toBe(needsGrace);
        let settled = false;
        const completion = controller.settle().then((cleanup) => {
          settled = true;
          return cleanup;
        });
        await vi.advanceTimersByTimeAsync(0);
        expect(settled).toBe(!needsGrace);
        expect(controller.terminate()).toBe(needsGrace);
        if (needsGrace) {
          expect(kill).toHaveBeenCalledWith(-4242, "SIGTERM");
        } else {
          expect(kill).not.toHaveBeenCalledWith(-4242, "SIGTERM");
        }
        expect(kill).not.toHaveBeenCalledWith(-4242, "SIGKILL");
        await vi.advanceTimersByTimeAsync(299);
        expect(settled).toBe(!needsGrace);
        expect(kill).not.toHaveBeenCalledWith(-4242, "SIGKILL");
        await vi.advanceTimersByTimeAsync(1);
        expect(settled).toBe(!needsGrace);
        if (needsGrace) {
          expect(kill).toHaveBeenCalledWith(-4242, "SIGKILL");
        } else {
          expect(kill).not.toHaveBeenCalledWith(-4242, "SIGKILL");
        }
        // Neither live nor EPERM probes prove extinction after the force-send receipt.
        await vi.advanceTimersByTimeAsync(COMMAND_PROCESS_TREE_KILL_GRACE_MS - 1);
        expect(settled).toBe(!needsGrace);
        await vi.advanceTimersByTimeAsync(1);
        await expect(completion).resolves.toBe(needsGrace ? "uncertain" : "normal");
        expect(kill.mock.calls.every(([pid]) => pid === -4242)).toBe(true);
        expect(child.kill).not.toHaveBeenCalled();
        expect(cancelController.signal.aborted).toBe(false);
      } finally {
        vi.clearAllTimers();
        vi.useRealTimers();
      }
    },
  );

  it.each(["graceful", "force"] as const)(
    "joins observed group exit after a %s force-send receipt",
    async (mode) => {
      await withOwnedTree(async ({ parent, descendantPid }) => {
        const kill = process.kill.bind(process);
        const forced = createDeferredCore();
        let observedAbsence = false;
        const signals = vi.spyOn(process, "kill").mockImplementation((pid, signal) => {
          if (
            pid === -parent.pid! &&
            (signal === "SIGKILL" || signal === osConstants.signals.SIGKILL)
          ) {
            // A successful send is not an exit receipt. Keep this real group alive until released below.
            forced.resolve();
            return true;
          }
          try {
            return kill(pid, signal);
          } catch (error) {
            if (
              pid === -parent.pid! &&
              signal === 0 &&
              error instanceof Error &&
              "code" in error &&
              error.code === "ESRCH"
            ) {
              observedAbsence = true;
            }
            throw error;
          }
        });
        const owner = createCommandTerminationController({
          child: parent,
          cancelController: new AbortController(),
          processTree: { mode },
          killGraceMs: 0,
          isChildExited: () => parent.exitCode !== null || parent.signalCode !== null,
          isCommandSettled: () => false,
        });
        owner.terminate();
        await forced.promise;
        let settled = false;
        const completion = owner.settle().then((result) => {
          settled = true;
          return { result, observedAbsence };
        });
        await nextTurn();
        expect(processIdentity.isPidAlive(descendantPid)).toBe(true);
        expect.soft(settled).toBe(false);
        kill(-parent.pid!, "SIGKILL");
        const outcome = await completion;
        expect(outcome.result).toBe(outcome.observedAbsence ? "forced" : "uncertain");
        if (outcome.result === "forced") {
          expect(processIdentity.isPidAlive(descendantPid)).toBe(false);
        }
        expect(
          signals.mock.calls.filter(
            ([, signal]) => signal === "SIGKILL" || signal === osConstants.signals.SIGKILL,
          ),
        ).toHaveLength(1);
      });
    },
  );

  it("reports forced cleanup when the original group is confirmed absent", async () => {
    const parent = spawn(
      process.execPath,
      ["-e", "process.on('message',()=>process.exit(0));process.send('ready');"],
      {
        detached: true,
        stdio: ["ignore", "ignore", "ignore", "ipc"],
      },
    );
    const closed = once(parent, "close");
    try {
      await once(parent, "message", { signal: AbortSignal.timeout(2_000) });
      const owner = createCommandTerminationController({
        child: parent,
        cancelController: new AbortController(),
        processTree: { mode: "force" },
        killGraceMs: 0,
        isChildExited: () => parent.exitCode !== null || parent.signalCode !== null,
        isCommandSettled: () => false,
      });
      parent.send("finish");
      await closed;
      owner.terminate();
      expect(await owner.settle()).toBe("forced");
    } finally {
      killPidIfAlive(parent.pid);
      await closed;
    }
  });

  it.each([
    { observation: "live", killSignal: undefined },
    { observation: "unknown", killSignal: undefined },
    { observation: "reused", killSignal: undefined },
    { observation: "live", killSignal: "SIGKILL" },
    { observation: "live", killSignal: osConstants.signals.SIGKILL },
  ] as const)(
    "reports uncertain when the original group remains $observation after force (initial signal=$killSignal)",
    async ({ observation, killSignal }) => {
      await withOwnedTree(async ({ parent, descendantPid }) => {
        const kill = process.kill.bind(process);
        const readStart = processIdentity.getFileLockProcessStartTime;
        const originalStart = readStart(parent.pid!);
        expect(originalStart).not.toBeNull();
        let forced = false;
        const signals = vi.spyOn(process, "kill").mockImplementation((pid, signal) => {
          if (
            pid === -parent.pid! &&
            (signal === "SIGKILL" || signal === osConstants.signals.SIGKILL)
          ) {
            forced = true;
            return true;
          }
          if (forced && pid === -parent.pid! && signal === 0 && observation === "unknown") {
            throw Object.assign(new Error("fixture observation unavailable"), { code: "EPERM" });
          }
          return kill(pid, signal);
        });
        vi.spyOn(processIdentity, "getFileLockProcessStartTime").mockImplementation(
          (pid, ...args) =>
            forced && observation === "reused" && pid === parent.pid
              ? originalStart! + 1
              : readStart(pid, ...args),
        );
        const owner = createCommandTerminationController({
          child: parent,
          cancelController: new AbortController(),
          processTree: { mode: "graceful" },
          killSignal,
          killGraceMs: 0,
          isChildExited: () => parent.exitCode !== null || parent.signalCode !== null,
          isCommandSettled: () => false,
        });
        owner.terminate();
        expect(await owner.settle()).toBe("uncertain");
        expect(processIdentity.isPidAlive(descendantPid)).toBe(true);
        expect(
          signals.mock.calls.filter(
            ([, signal]) => signal === "SIGKILL" || signal === osConstants.signals.SIGKILL,
          ),
        ).toHaveLength(1);
      });
    },
  );
});