processTreeTerminator.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. import {
  2. spawn,
  3. spawnSync,
  4. type ChildProcessWithoutNullStreams,
  5. } from "node:child_process";
  6. import { mkdtemp, readFile, rm } from "node:fs/promises";
  7. import { tmpdir } from "node:os";
  8. import { join } from "node:path";
  9. import { setTimeout as delay } from "node:timers/promises";
  10. import { afterEach, describe, expect, it } from "vitest";
  11. import {
  12. captureProcessTreeSnapshot,
  13. shouldSpawnInDetachedProcessGroup,
  14. terminateProcessTree,
  15. terminateProcessTreeAndWait,
  16. type ProcessIdentity,
  17. type ProcessTreeSnapshot,
  18. } from "@zcode/services/process/processTreeTerminator";
  19. const activeChildren = new Set<ChildProcessWithoutNullStreams>();
  20. const tempDirs = new Set<string>();
  21. function isPidAlive(pid: number): boolean {
  22. try {
  23. process.kill(pid, 0);
  24. return true;
  25. } catch {
  26. return false;
  27. }
  28. }
  29. function isPidRunning(pid: number): boolean {
  30. if (!isPidAlive(pid)) {
  31. return false;
  32. }
  33. if (process.platform === "win32") {
  34. return true;
  35. }
  36. const result = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], {
  37. encoding: "utf8",
  38. });
  39. const status = result.stdout.trim();
  40. return status.length > 0 && !status.startsWith("Z");
  41. }
  42. async function waitForPidExit(
  43. pid: number,
  44. timeoutMs = 4_000,
  45. ): Promise<boolean> {
  46. const deadline = Date.now() + timeoutMs;
  47. while (Date.now() < deadline) {
  48. if (!isPidAlive(pid)) {
  49. return true;
  50. }
  51. await delay(50);
  52. }
  53. return !isPidAlive(pid);
  54. }
  55. async function waitForProcessTreeSnapshotIdentity(
  56. child: ChildProcessWithoutNullStreams,
  57. pid: number,
  58. timeoutMs = 4_000,
  59. ): Promise<
  60. | {
  61. snapshot: ProcessTreeSnapshot;
  62. identity: ProcessIdentity;
  63. }
  64. | undefined
  65. > {
  66. const deadline = Date.now() + timeoutMs;
  67. while (Date.now() < deadline) {
  68. const snapshot = captureProcessTreeSnapshot(child);
  69. const identity = snapshot?.identities.find((item) => item.pid === pid);
  70. if (snapshot && identity) {
  71. return { snapshot, identity };
  72. }
  73. await delay(50);
  74. }
  75. const snapshot = captureProcessTreeSnapshot(child);
  76. const identity = snapshot?.identities.find((item) => item.pid === pid);
  77. return snapshot && identity ? { snapshot, identity } : undefined;
  78. }
  79. function readFirstStdoutLine(
  80. child: ChildProcessWithoutNullStreams,
  81. ): Promise<string> {
  82. return new Promise((resolve, reject) => {
  83. let buffer = "";
  84. let stderrBuffer = "";
  85. const timer = setTimeout(() => {
  86. reject(
  87. new Error(
  88. `child did not report grandchild pid stdout=${JSON.stringify(buffer)} stderr=${JSON.stringify(stderrBuffer)}`,
  89. ),
  90. );
  91. }, 2_000);
  92. child.stdout.on("data", (chunk: Buffer) => {
  93. buffer += chunk.toString("utf8");
  94. const newlineIndex = buffer.indexOf("\n");
  95. if (newlineIndex < 0) {
  96. return;
  97. }
  98. clearTimeout(timer);
  99. resolve(buffer.slice(0, newlineIndex).trim());
  100. });
  101. child.stderr.on("data", (chunk: Buffer) => {
  102. stderrBuffer += chunk.toString("utf8");
  103. });
  104. child.once("error", (error) => {
  105. clearTimeout(timer);
  106. reject(error);
  107. });
  108. child.once("exit", (code, signal) => {
  109. if (!buffer.trim()) {
  110. clearTimeout(timer);
  111. reject(
  112. new Error(
  113. `child exited before reporting pid code=${code} signal=${signal} stderr=${JSON.stringify(stderrBuffer)}`,
  114. ),
  115. );
  116. }
  117. });
  118. });
  119. }
  120. async function readReportedPid(
  121. child: ChildProcessWithoutNullStreams,
  122. pidFilePath?: string,
  123. ): Promise<number> {
  124. let stdoutLine = "";
  125. try {
  126. stdoutLine = await readFirstStdoutLine(child);
  127. const stdoutPid = Number(stdoutLine);
  128. if (Number.isInteger(stdoutPid)) {
  129. return stdoutPid;
  130. }
  131. } catch (error) {
  132. if (!pidFilePath) {
  133. throw error;
  134. }
  135. }
  136. if (pidFilePath) {
  137. const filePid = Number((await readFile(pidFilePath, "utf8")).trim());
  138. if (Number.isInteger(filePid)) {
  139. return filePid;
  140. }
  141. }
  142. throw new Error(`child reported invalid pid: ${JSON.stringify(stdoutLine)}`);
  143. }
  144. afterEach(async () => {
  145. for (const child of activeChildren) {
  146. if (child.pid && process.platform !== "win32") {
  147. try {
  148. process.kill(-child.pid, "SIGKILL");
  149. } catch {
  150. /* 测试兜底清理,进程已退出时忽略。 */
  151. }
  152. }
  153. terminateProcessTree(child);
  154. }
  155. activeChildren.clear();
  156. for (const dir of tempDirs) {
  157. await rm(dir, { recursive: true, force: true });
  158. }
  159. tempDirs.clear();
  160. });
  161. describe("terminateProcessTree", () => {
  162. it("回收 runtime wrapper 时会一并结束其派生子进程", async () => {
  163. const dir = await mkdtemp(join(tmpdir(), "zcode-runtime-terminator-"));
  164. tempDirs.add(dir);
  165. const grandchildPidPath = join(dir, "grandchild.pid");
  166. const child = spawn(
  167. process.execPath,
  168. [
  169. "-e",
  170. `
  171. const { writeFileSync } = require("node:fs");
  172. const { spawn } = require("node:child_process");
  173. const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
  174. stdio: "ignore",
  175. });
  176. writeFileSync(${JSON.stringify(grandchildPidPath)}, String(child.pid));
  177. process.stdout.write(String(child.pid) + "\\n");
  178. setInterval(() => {}, 1000);
  179. `,
  180. ],
  181. {
  182. detached: shouldSpawnInDetachedProcessGroup(),
  183. stdio: ["ignore", "pipe", "pipe"],
  184. windowsHide: true,
  185. },
  186. );
  187. activeChildren.add(child);
  188. const grandchildPid = await readReportedPid(child, grandchildPidPath);
  189. expect(isPidAlive(grandchildPid)).toBe(true);
  190. // Bugfix: 用户反馈退出 ZCode 后仍残留 bun 版本的 Agent 子进程。
  191. // 这里用 wrapper -> grandchild 的结构复现,要求关闭 wrapper 时整棵进程树都被回收。
  192. terminateProcessTree(child);
  193. expect(await waitForPidExit(child.pid!)).toBe(true);
  194. expect(await waitForPidExit(grandchildPid)).toBe(true);
  195. activeChildren.delete(child);
  196. });
  197. // Bugfix: Windows 的 taskkill 进程树回收不会向 Node 子进程交付 POSIX SIGTERM。
  198. // 该用例只验证 POSIX graceful shutdown 窗口,Windows 另由进程树清理用例覆盖。
  199. it.runIf(process.platform !== "win32")(
  200. "关闭 runtime wrapper 时先给进程处理 SIGTERM 的窗口",
  201. async () => {
  202. const dir = await mkdtemp(join(tmpdir(), "zcode-runtime-terminator-"));
  203. tempDirs.add(dir);
  204. const markerPath = join(dir, "graceful-exit.txt");
  205. const child = spawn(
  206. process.execPath,
  207. [
  208. "-e",
  209. `
  210. const { writeFileSync } = require("node:fs");
  211. process.on("SIGTERM", () => {
  212. writeFileSync(${JSON.stringify(markerPath)}, "sigterm");
  213. setTimeout(() => process.exit(0), 150);
  214. });
  215. console.log("ready");
  216. setInterval(() => {}, 1000);
  217. `,
  218. ],
  219. {
  220. detached: shouldSpawnInDetachedProcessGroup(),
  221. stdio: ["ignore", "pipe", "pipe"],
  222. windowsHide: true,
  223. },
  224. );
  225. activeChildren.add(child);
  226. await readFirstStdoutLine(child);
  227. // Bugfix: 回收残留进程不能把正常关闭路径变成立即 SIGKILL;
  228. // runtime 仍需要一点时间 flush 会话状态、关闭 MCP 连接和清理临时资源。
  229. terminateProcessTree(child);
  230. await delay(50);
  231. expect(isPidAlive(child.pid!)).toBe(true);
  232. expect(await readFile(markerPath, "utf8")).toBe("sigterm");
  233. expect(await waitForPidExit(child.pid!)).toBe(true);
  234. activeChildren.delete(child);
  235. },
  236. );
  237. it.runIf(process.platform !== "win32")(
  238. "POSIX 下会兜底清理脱离原进程组的后代进程",
  239. async () => {
  240. const dir = await mkdtemp(join(tmpdir(), "zcode-runtime-terminator-"));
  241. tempDirs.add(dir);
  242. const grandchildPidPath = join(dir, "detached-grandchild.pid");
  243. const child = spawn(
  244. process.execPath,
  245. [
  246. "-e",
  247. `
  248. const { writeFileSync } = require("node:fs");
  249. const { spawn } = require("node:child_process");
  250. const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
  251. detached: true,
  252. stdio: "ignore",
  253. });
  254. child.unref();
  255. writeFileSync(${JSON.stringify(grandchildPidPath)}, String(child.pid));
  256. process.stdout.write(String(child.pid) + "\\n");
  257. setInterval(() => {}, 1000);
  258. `,
  259. ],
  260. {
  261. detached: shouldSpawnInDetachedProcessGroup(),
  262. stdio: ["ignore", "pipe", "pipe"],
  263. windowsHide: true,
  264. },
  265. );
  266. activeChildren.add(child);
  267. const grandchildPid = await readReportedPid(child, grandchildPidPath);
  268. expect(isPidAlive(grandchildPid)).toBe(true);
  269. // Bugfix: 有些 runtime 或插件会把后代进程 detached 到自己的进程组;
  270. // 只 kill runtime wrapper 的进程组会留下这类后代进程,必须按已发现的进程树兜底清理。
  271. terminateProcessTree(child);
  272. expect(await waitForPidExit(child.pid!)).toBe(true);
  273. expect(await waitForPidExit(grandchildPid)).toBe(true);
  274. activeChildren.delete(child);
  275. },
  276. );
  277. it.runIf(process.platform !== "win32")(
  278. "非等待式回收会强制结束忽略 SIGTERM 的 runtime 进程树",
  279. async () => {
  280. const child = spawn(
  281. process.execPath,
  282. [
  283. "-e",
  284. `
  285. const { spawn } = require("node:child_process");
  286. const descendant = spawn(
  287. process.execPath,
  288. ["-e", 'process.on("SIGTERM", () => {}); process.send?.("ready"); setInterval(() => {}, 1000);'],
  289. { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] },
  290. );
  291. process.on("SIGTERM", () => {});
  292. descendant.once("message", () => process.stdout.write(String(descendant.pid) + "\\n"));
  293. setInterval(() => {}, 1000);
  294. `,
  295. ],
  296. {
  297. detached: shouldSpawnInDetachedProcessGroup(),
  298. stdio: ["ignore", "pipe", "pipe"],
  299. windowsHide: true,
  300. },
  301. );
  302. activeChildren.add(child);
  303. const descendantPid = await readReportedPid(child);
  304. try {
  305. // 修复原因:公开的非等待式关闭不会注入 force 观察回调;强杀副作用不能
  306. // 依赖该可选回调,否则忽略 SIGTERM 的 runtime 与 detached MCP 会永久残留。
  307. terminateProcessTree(child, { forceAfterMs: 20 });
  308. expect(await waitForPidExit(child.pid!)).toBe(true);
  309. expect(await waitForPidExit(descendantPid)).toBe(true);
  310. } finally {
  311. for (const pid of [child.pid, descendantPid]) {
  312. if (pid && isPidRunning(pid)) {
  313. try {
  314. process.kill(-pid, "SIGKILL");
  315. } catch {
  316. /* 测试兜底清理,进程已退出时忽略。 */
  317. }
  318. }
  319. }
  320. }
  321. activeChildren.delete(child);
  322. },
  323. );
  324. it.runIf(process.platform !== "win32")(
  325. "查询 root 身份失败时记录 warn 且延迟 force 不沿裸 PID 重新发现",
  326. async () => {
  327. const child = spawn(
  328. process.execPath,
  329. ["-e", "setInterval(() => {}, 1000)"],
  330. {
  331. detached: shouldSpawnInDetachedProcessGroup(),
  332. stdio: ["ignore", "pipe", "pipe"],
  333. windowsHide: true,
  334. },
  335. );
  336. activeChildren.add(child);
  337. await delay(50);
  338. const warnMessages: string[] = [];
  339. const originalPath = process.env.PATH;
  340. process.env.PATH = "";
  341. try {
  342. terminateProcessTree(child, {
  343. forceAfterMs: 20,
  344. log: {
  345. warn: (_traceId, ...args) => {
  346. warnMessages.push(args.map(String).join(" "));
  347. },
  348. },
  349. });
  350. } finally {
  351. if (originalPath === undefined) {
  352. delete process.env.PATH;
  353. } else {
  354. process.env.PATH = originalPath;
  355. }
  356. }
  357. expect(
  358. warnMessages.some((message) =>
  359. message.includes("查询 runtime 后代进程失败"),
  360. ),
  361. ).toBe(true);
  362. // 修复原因:首次查询失败后即使 PATH 已恢复,force timer 也不能沿裸 PID
  363. // 重新认领进程树;ChildProcess.kill 同样只是 PID 信号,不是稳定 OS 句柄。
  364. await delay(100);
  365. expect(isPidAlive(child.pid!)).toBe(true);
  366. },
  367. );
  368. it.runIf(process.platform !== "win32")(
  369. "等待式回收会撑到 SIGKILL 兜底完成",
  370. async () => {
  371. const child = spawn(
  372. process.execPath,
  373. [
  374. "-e",
  375. `
  376. process.on("SIGTERM", () => {});
  377. console.log("ready");
  378. setInterval(() => {}, 1000);
  379. `,
  380. ],
  381. {
  382. detached: shouldSpawnInDetachedProcessGroup(),
  383. stdio: ["ignore", "pipe", "pipe"],
  384. windowsHide: true,
  385. },
  386. );
  387. activeChildren.add(child);
  388. await readFirstStdoutLine(child);
  389. // Bugfix: app 关闭时 host 不能只安排一个 unref 的 SIGKILL 兜底就退出;
  390. // 遇到忽略 SIGTERM 的 zcode-cli/app-server 时,必须等兜底执行完再让 host 结束。
  391. const result = await terminateProcessTreeAndWait(child, {
  392. forceAfterMs: 20,
  393. waitAfterForceMs: 20,
  394. });
  395. expect(result).toEqual({ remainingPids: [] });
  396. expect(await waitForPidExit(child.pid!, 1_000)).toBe(true);
  397. activeChildren.delete(child);
  398. },
  399. );
  400. it.runIf(process.platform !== "win32")(
  401. "根进程先退出时仍等待 detached 后代完成强制回收",
  402. async () => {
  403. const child = spawn(
  404. process.execPath,
  405. [
  406. "-e",
  407. `
  408. const { spawn } = require("node:child_process");
  409. const descendant = spawn(
  410. process.execPath,
  411. ["-e", 'process.on("SIGTERM", () => {}); process.send?.("ready"); setInterval(() => {}, 1000);'],
  412. { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] },
  413. );
  414. descendant.once("message", () => process.stdout.write(String(descendant.pid) + "\\n"));
  415. setInterval(() => {}, 1000);
  416. `,
  417. ],
  418. {
  419. detached: shouldSpawnInDetachedProcessGroup(),
  420. stdio: ["ignore", "pipe", "pipe"],
  421. windowsHide: true,
  422. },
  423. );
  424. activeChildren.add(child);
  425. const descendantPid = await readReportedPid(child);
  426. expect(isPidAlive(descendantPid)).toBe(true);
  427. try {
  428. // 修复原因:runtime 根进程收到 SIGTERM 后可能先于 detached MCP
  429. // 退出。等待边界必须是整棵已发现进程树,不能只观察根 child。
  430. await terminateProcessTreeAndWait(child, {
  431. forceAfterMs: 30,
  432. waitAfterForceMs: 30,
  433. });
  434. expect(isPidRunning(descendantPid)).toBe(false);
  435. } finally {
  436. if (isPidAlive(descendantPid)) {
  437. try {
  438. process.kill(-descendantPid, "SIGKILL");
  439. } catch {
  440. /* 测试兜底清理,进程已退出时忽略。 */
  441. }
  442. }
  443. }
  444. activeChildren.delete(child);
  445. },
  446. );
  447. it.runIf(process.platform !== "win32")(
  448. "延迟回收不会终止 PID 相同但创建标识已变化的进程",
  449. async () => {
  450. const child = spawn(
  451. process.execPath,
  452. [
  453. "-e",
  454. `
  455. const { spawn } = require("node:child_process");
  456. const descendant = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
  457. detached: true,
  458. stdio: "ignore",
  459. });
  460. descendant.unref();
  461. process.on("message", (message) => {
  462. if (message === "exit") process.exit(0);
  463. });
  464. process.stdout.write(String(descendant.pid) + "\\n");
  465. `,
  466. ],
  467. {
  468. detached: shouldSpawnInDetachedProcessGroup(),
  469. stdio: ["ignore", "pipe", "pipe", "ipc"],
  470. windowsHide: true,
  471. },
  472. );
  473. activeChildren.add(child);
  474. const descendantPid = await readReportedPid(child);
  475. // 修复原因:stdout 已写出 PID 不代表 ps 的父子/进程组视图已经稳定;
  476. // 由父测试控制 wrapper 退出,并等待包含创建标识的快照,避免固定等待竞态。
  477. const captured = await waitForProcessTreeSnapshotIdentity(child, descendantPid);
  478. expect(captured).toBeDefined();
  479. const { snapshot, identity: descendantIdentity } = captured!;
  480. child.send("exit");
  481. expect(await waitForPidExit(child.pid!)).toBe(true);
  482. try {
  483. // 修复原因:延迟强杀时裸 PID 可能已被系统复用。用错误创建标识模拟
  484. // 同 PID 的新进程,回收器必须把原成员视为已退出,不能向当前进程发信号。
  485. await terminateProcessTreeAndWait(child, {
  486. forceAfterMs: 20,
  487. waitAfterForceMs: 20,
  488. snapshot: {
  489. ...snapshot,
  490. identities: snapshot.identities.map((identity) =>
  491. identity.pid === descendantIdentity.pid
  492. ? { ...identity, startTime: `${descendantIdentity.startTime}-reused` }
  493. : identity,
  494. ),
  495. },
  496. });
  497. expect(isPidRunning(descendantPid)).toBe(true);
  498. } finally {
  499. if (isPidRunning(descendantPid)) {
  500. process.kill(-descendantPid, "SIGKILL");
  501. }
  502. }
  503. activeChildren.delete(child);
  504. },
  505. );
  506. it.runIf(process.platform !== "win32")(
  507. "根进程已退出时仍按原进程组回收同组后代",
  508. async () => {
  509. const child = spawn(
  510. process.execPath,
  511. [
  512. "-e",
  513. `
  514. const { spawn } = require("node:child_process");
  515. const descendant = spawn(
  516. process.execPath,
  517. ["-e", 'process.on("SIGTERM", () => {}); process.send?.("ready"); setInterval(() => {}, 1000);'],
  518. { stdio: ["ignore", "ignore", "ignore", "ipc"] },
  519. );
  520. descendant.once("message", () => {
  521. process.stdout.write(String(descendant.pid) + "\\n", () => setTimeout(() => process.exit(0), 100));
  522. });
  523. `,
  524. ],
  525. {
  526. detached: shouldSpawnInDetachedProcessGroup(),
  527. stdio: ["ignore", "pipe", "pipe"],
  528. windowsHide: true,
  529. },
  530. );
  531. activeChildren.add(child);
  532. const descendantPid = await readReportedPid(child);
  533. const snapshot = captureProcessTreeSnapshot(child);
  534. expect(
  535. snapshot?.identities.some((identity) => identity.pid === descendantPid),
  536. ).toBe(true);
  537. expect(await waitForPidExit(child.pid!)).toBe(true);
  538. expect(isPidRunning(descendantPid)).toBe(true);
  539. try {
  540. // 修复原因:CLI 根进程异常退出后,同组 MCP 仍可能存活;必须用根进程
  541. // 生前快照证明该 PGID 内仍有原成员,不能只凭已退出的裸 root PID 发信号。
  542. await terminateProcessTreeAndWait(child, {
  543. forceAfterMs: 30,
  544. waitAfterForceMs: 30,
  545. snapshot,
  546. });
  547. expect(isPidRunning(descendantPid)).toBe(false);
  548. } finally {
  549. if (isPidRunning(descendantPid)) {
  550. process.kill(-child.pid!, "SIGKILL");
  551. }
  552. }
  553. activeChildren.delete(child);
  554. },
  555. );
  556. it.runIf(process.platform !== "win32")(
  557. "健康 runtime 提前退出时不会固定等待兜底窗口",
  558. async () => {
  559. const child = spawn(
  560. process.execPath,
  561. ["-e", "setInterval(() => {}, 1000)"],
  562. {
  563. detached: shouldSpawnInDetachedProcessGroup(),
  564. stdio: ["ignore", "pipe", "pipe"],
  565. windowsHide: true,
  566. },
  567. );
  568. activeChildren.add(child);
  569. await delay(50);
  570. const startedAt = Date.now();
  571. const waitPromise = terminateProcessTreeAndWait(child, {
  572. forceAfterMs: 1_500,
  573. waitAfterForceMs: 100,
  574. });
  575. setTimeout(() => {
  576. child.kill();
  577. }, 100).unref?.();
  578. // Bugfix: 旧等待式回收固定 sleep graceful + force 窗口;
  579. // 健康 runtime 在 SIGTERM 后提前退出时,不应继续卡满 2.25 秒。
  580. await waitPromise;
  581. const durationMs = Date.now() - startedAt;
  582. expect(await waitForPidExit(child.pid!, 1_000)).toBe(true);
  583. expect(durationMs).toBeLessThan(1_200);
  584. activeChildren.delete(child);
  585. },
  586. );
  587. });