processTreeTerminator.windows.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. import type { ChildProcess } from "node:child_process";
  2. import { EventEmitter } from "node:events";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. const { execFileMock } = vi.hoisted(() => ({
  5. execFileMock: vi.fn(),
  6. }));
  7. vi.mock("node:child_process", async (importOriginal) => ({
  8. ...(await importOriginal<typeof import("node:child_process")>()),
  9. execFile: execFileMock,
  10. }));
  11. import {
  12. captureProcessTreeSnapshotAsync,
  13. filterCurrentProcessIdentitiesAsync,
  14. terminateProcessTree,
  15. terminateProcessTreeAndWait,
  16. } from "@zcode/services/process/processTreeTerminator";
  17. const DOTNET_UNIX_EPOCH_TICKS = 621_355_968_000_000_000n;
  18. let targetedPowerShellResult: string | undefined;
  19. let targetedPowerShellResultsByPid: Map<number, string>;
  20. let powershellResult: string;
  21. let powershellError: Error | null;
  22. let powershellDelayMs: number;
  23. let targetedPowerShellUsesConfiguredTimeout: boolean;
  24. let onPowerShellQuery: (() => void) | undefined;
  25. let alivePids: Set<number>;
  26. let taskkillRemovesOnGraceful: boolean;
  27. function powershellIdentity(pid: number, parentPid: number): string {
  28. return powershellIdentityAt(pid, parentPid, Date.UTC(2026, 6, 24, 11, 0, 0));
  29. }
  30. function powershellIdentityAt(pid: number, parentPid: number, utcMilliseconds: number): string {
  31. const ticks = DOTNET_UNIX_EPOCH_TICKS + BigInt(utcMilliseconds) * 10_000n;
  32. return `${pid} ${parentPid} ${ticks}\n`;
  33. }
  34. describe("terminateProcessTree Windows", () => {
  35. beforeEach(() => {
  36. vi.useFakeTimers();
  37. vi.setSystemTime(new Date(Date.UTC(2026, 6, 24, 12, 0, 0)));
  38. vi.spyOn(process, "platform", "get").mockReturnValue("win32");
  39. alivePids = new Set([4242]);
  40. vi.spyOn(process, "kill").mockImplementation((pid) => {
  41. if (alivePids.has(Number(pid))) return true;
  42. throw Object.assign(new Error("process not found"), { code: "ESRCH" });
  43. });
  44. targetedPowerShellResult = undefined;
  45. targetedPowerShellResultsByPid = new Map();
  46. powershellResult = powershellIdentity(4242, 1);
  47. powershellError = null;
  48. powershellDelayMs = 0;
  49. targetedPowerShellUsesConfiguredTimeout = false;
  50. onPowerShellQuery = undefined;
  51. taskkillRemovesOnGraceful = false;
  52. execFileMock
  53. .mockReset()
  54. .mockImplementation(
  55. (
  56. command: string,
  57. args: string[],
  58. options: { timeout?: number },
  59. callback: (error: Error | null, stdout: string, stderr: string) => void,
  60. ) => {
  61. if (command === "powershell.exe") {
  62. onPowerShellQuery?.();
  63. const targeted = args.some((arg) => arg.includes("ProcessId ="));
  64. const targetedPid = Number(
  65. /ProcessId = (\d+)/u.exec(args.find((arg) => arg.includes("ProcessId =")) ?? "")?.[1],
  66. );
  67. const resultAtInvocation = targeted
  68. ? (targetedPowerShellResultsByPid.get(targetedPid) ??
  69. targetedPowerShellResult ??
  70. powershellIdentity(targetedPid, targetedPid === 5000 ? 4242 : 1))
  71. : powershellResult;
  72. const reply = () => callback(powershellError, resultAtInvocation, "");
  73. const delayMs =
  74. targeted && targetedPowerShellUsesConfiguredTimeout
  75. ? (options.timeout ?? 0)
  76. : powershellDelayMs;
  77. if (delayMs > 0) setTimeout(reply, delayMs);
  78. else reply();
  79. } else {
  80. const pid = Number(args[1]);
  81. if (taskkillRemovesOnGraceful || args.includes("/F")) {
  82. alivePids.delete(pid);
  83. }
  84. callback(null, "", "");
  85. }
  86. return {};
  87. },
  88. );
  89. });
  90. afterEach(() => {
  91. vi.useRealTimers();
  92. vi.restoreAllMocks();
  93. });
  94. it("Windows 进程快照直接使用 PowerShell/CIM", async () => {
  95. const child = {
  96. exitCode: null,
  97. pid: 4242,
  98. signalCode: null,
  99. } as ChildProcess;
  100. powershellResult = powershellIdentity(4242, 1);
  101. const snapshot = await captureProcessTreeSnapshotAsync(child);
  102. expect(snapshot?.rootPid).toBe(4242);
  103. expect(execFileMock.mock.calls.filter(([command]) => command === "wmic.exe")).toHaveLength(0);
  104. expect(
  105. execFileMock.mock.calls.filter(([command]) => command === "powershell.exe"),
  106. ).toHaveLength(1);
  107. });
  108. it("非等待式回收到 force deadline 后不使用旧快照强杀 root", async () => {
  109. const child = {
  110. exitCode: null,
  111. pid: 4242,
  112. signalCode: null,
  113. } as ChildProcess;
  114. // 修复原因:Node exit 回调可能晚于 OS 退出及 PID 复用;deadline 时没有新的
  115. // CreationDate 复核,就不能根据旧快照向裸 root PID 发送 /F。
  116. terminateProcessTree(child, { forceAfterMs: 20 });
  117. await vi.advanceTimersByTimeAsync(20);
  118. expect(execFileMock).not.toHaveBeenCalledWith(
  119. "taskkill",
  120. ["/PID", "4242", "/T", "/F"],
  121. expect.objectContaining({ windowsHide: true }),
  122. expect.any(Function),
  123. );
  124. });
  125. it("force 前定向复核 CreationDate 匹配才强杀 root", async () => {
  126. const child = {
  127. exitCode: null,
  128. pid: 4242,
  129. signalCode: null,
  130. } as ChildProcess;
  131. terminateProcessTree(child, { forceAfterMs: 1_000 });
  132. await vi.advanceTimersByTimeAsync(250);
  133. expect(execFileMock).toHaveBeenCalledWith(
  134. "taskkill",
  135. ["/PID", "4242", "/T", "/F"],
  136. expect.objectContaining({ windowsHide: true }),
  137. expect.any(Function),
  138. );
  139. });
  140. it("force 前直接使用 PowerShell 定向复核 root", async () => {
  141. const child = {
  142. exitCode: null,
  143. pid: 4242,
  144. signalCode: null,
  145. } as ChildProcess;
  146. powershellResult = powershellIdentity(4242, 1);
  147. terminateProcessTree(child, { forceAfterMs: 1_000 });
  148. await vi.advanceTimersByTimeAsync(250);
  149. expect(execFileMock).toHaveBeenCalledWith(
  150. "powershell.exe",
  151. expect.arrayContaining(["-Command", expect.stringContaining("ProcessId = 4242")]),
  152. expect.objectContaining({ windowsHide: true }),
  153. expect.any(Function),
  154. );
  155. expect(execFileMock).toHaveBeenCalledWith(
  156. "taskkill",
  157. ["/PID", "4242", "/T", "/F"],
  158. expect.objectContaining({ windowsHide: true }),
  159. expect.any(Function),
  160. );
  161. });
  162. it("force 定向复核为 PowerShell 保留完整预算", async () => {
  163. const child = {
  164. exitCode: null,
  165. pid: 4242,
  166. signalCode: null,
  167. } as ChildProcess;
  168. targetedPowerShellUsesConfiguredTimeout = true;
  169. powershellResult = powershellIdentity(4242, 1);
  170. terminateProcessTree(child, { forceAfterMs: 2_000 });
  171. await vi.advanceTimersByTimeAsync(2_000);
  172. expect(execFileMock).toHaveBeenCalledWith(
  173. "powershell.exe",
  174. expect.arrayContaining(["-Command", expect.stringContaining("ProcessId = 4242")]),
  175. expect.objectContaining({ timeout: 750, windowsHide: true }),
  176. expect.any(Function),
  177. );
  178. expect(execFileMock).toHaveBeenCalledWith(
  179. "taskkill",
  180. ["/PID", "4242", "/T", "/F"],
  181. expect.objectContaining({ windowsHide: true }),
  182. expect.any(Function),
  183. );
  184. });
  185. it("force 定向复核失败时仅对受管 live root 使用句柄兜底", async () => {
  186. const child = Object.assign(new EventEmitter(), {
  187. exitCode: null as number | null,
  188. pid: 4242,
  189. signalCode: null as NodeJS.Signals | null,
  190. kill: vi.fn(),
  191. }) as unknown as ChildProcess;
  192. alivePids = new Set([4242, 5000]);
  193. powershellError = Object.assign(new Error("simulated targeted CIM timeout"), {
  194. code: "ETIMEDOUT",
  195. });
  196. const windowsTaskkillRunner = vi.fn(({ force, pid }: { force: boolean; pid: number }) => {
  197. if (force && pid === 4242) {
  198. alivePids.delete(pid);
  199. child.exitCode = 1;
  200. child.emit("exit", 1, null);
  201. }
  202. return Promise.resolve({});
  203. });
  204. const resultPromise = terminateProcessTreeAndWait(child, {
  205. forceAfterMs: 1_000,
  206. snapshot: {
  207. rootPid: 4242,
  208. descendantPids: [5000],
  209. identities: [
  210. { parentPid: 1, pid: 4242, startTime: "windows-utc-us:1784890800000000" },
  211. { parentPid: 4242, pid: 5000, startTime: "windows-utc-us:1784890800000000" },
  212. ],
  213. },
  214. waitAfterForceMs: 30,
  215. windowsTaskkillRunner,
  216. windowsTaskkillTimeoutMs: 100,
  217. });
  218. await vi.advanceTimersByTimeAsync(250);
  219. // 安全契约:受管 ChildProcess 的 live root 句柄是 root-only 所有权证据;CIM
  220. // 定向复核失败时仍可收口 root,但不得把未复核后代加入显式 /F 目标。
  221. expect(windowsTaskkillRunner).toHaveBeenCalledWith({
  222. force: true,
  223. pid: 4242,
  224. timeoutMs: 100,
  225. });
  226. expect(windowsTaskkillRunner).not.toHaveBeenCalledWith({
  227. force: true,
  228. pid: 5000,
  229. timeoutMs: 100,
  230. });
  231. await vi.advanceTimersByTimeAsync(880);
  232. await expect(resultPromise).resolves.toEqual({ remainingPids: [5000] });
  233. });
  234. it("graceful 挂起时 force 会强杀本次仍匹配的 root 与已验证后代", async () => {
  235. const child = Object.assign(new EventEmitter(), {
  236. exitCode: null as number | null,
  237. pid: 4242,
  238. signalCode: null as NodeJS.Signals | null,
  239. }) as unknown as ChildProcess;
  240. alivePids = new Set([4242, 5000]);
  241. powershellResult = `${powershellIdentity(4242, 1)}${powershellIdentity(5000, 4242)}`;
  242. const windowsTaskkillRunner = vi.fn(({ force, pid }: { force: boolean; pid: number }) =>
  243. force
  244. ? Promise.resolve().then(() => {
  245. alivePids.delete(pid);
  246. if (pid === 4242) {
  247. child.exitCode = 1;
  248. child.emit("exit", 1, null);
  249. }
  250. return {};
  251. })
  252. : new Promise<Record<string, never>>(() => {}),
  253. );
  254. const resultPromise = terminateProcessTreeAndWait(child, {
  255. forceAfterMs: 1_000,
  256. snapshot: await captureProcessTreeSnapshotAsync(child),
  257. waitAfterForceMs: 30,
  258. windowsTaskkillRunner,
  259. windowsTaskkillTimeoutMs: 100,
  260. });
  261. await vi.advanceTimersByTimeAsync(250);
  262. // Bug 回归:旧 deadlineSnapshotOnly 分支只保留 root,导致已验证后代永远没有 /F flight。
  263. expect(windowsTaskkillRunner).toHaveBeenCalledWith({
  264. force: true,
  265. pid: 4242,
  266. timeoutMs: 100,
  267. });
  268. expect(windowsTaskkillRunner).toHaveBeenCalledWith({
  269. force: true,
  270. pid: 5000,
  271. timeoutMs: 100,
  272. });
  273. await expect(resultPromise).resolves.toEqual({ remainingPids: [] });
  274. });
  275. it("force 前后代 PID 已复用时跳过该 PID 但继续收口匹配的 root", async () => {
  276. const child = Object.assign(new EventEmitter(), {
  277. exitCode: null as number | null,
  278. pid: 4242,
  279. signalCode: null as NodeJS.Signals | null,
  280. }) as unknown as ChildProcess;
  281. alivePids = new Set([4242, 5000]);
  282. powershellResult = `${powershellIdentity(4242, 1)}${powershellIdentity(5000, 4242)}`;
  283. targetedPowerShellResultsByPid.set(5000, powershellIdentity(6000, 1));
  284. const windowsTaskkillRunner = vi.fn(({ force, pid }: { force: boolean; pid: number }) =>
  285. force
  286. ? Promise.resolve().then(() => {
  287. alivePids.delete(pid);
  288. if (pid === 4242) {
  289. child.exitCode = 1;
  290. child.emit("exit", 1, null);
  291. }
  292. return {};
  293. })
  294. : new Promise<Record<string, never>>(() => {}),
  295. );
  296. const resultPromise = terminateProcessTreeAndWait(child, {
  297. forceAfterMs: 1_000,
  298. snapshot: await captureProcessTreeSnapshotAsync(child),
  299. waitAfterForceMs: 30,
  300. windowsTaskkillRunner,
  301. windowsTaskkillTimeoutMs: 100,
  302. });
  303. await vi.advanceTimersByTimeAsync(250);
  304. expect(windowsTaskkillRunner).toHaveBeenCalledWith({
  305. force: true,
  306. pid: 4242,
  307. timeoutMs: 100,
  308. });
  309. expect(windowsTaskkillRunner).not.toHaveBeenCalledWith({
  310. force: true,
  311. pid: 5000,
  312. timeoutMs: 100,
  313. });
  314. expect(execFileMock).toHaveBeenCalledWith(
  315. "powershell.exe",
  316. expect.arrayContaining(["-Command", expect.stringContaining("ProcessId = 5000")]),
  317. expect.objectContaining({ windowsHide: true }),
  318. expect.any(Function),
  319. );
  320. // 不匹配可能是 PID 复用,也可能是查询降级。安全边界是不强杀,并继续把旧身份
  321. // 作为未确认残留报告,禁止把复核失败误判成清理成功。
  322. await vi.advanceTimersByTimeAsync(880);
  323. await expect(resultPromise).resolves.toEqual({ remainingPids: [5000] });
  324. });
  325. it("force timer 先于 exit 回调且 PID 已复用时不强杀新 root", async () => {
  326. const child = {
  327. exitCode: null,
  328. pid: 4242,
  329. signalCode: null,
  330. } as ChildProcess;
  331. targetedPowerShellResult = powershellIdentity(6000, 1);
  332. terminateProcessTree(child, { forceAfterMs: 1_000 });
  333. await vi.advanceTimersByTimeAsync(250);
  334. expect(execFileMock).not.toHaveBeenCalledWith(
  335. "taskkill",
  336. ["/PID", "4242", "/T", "/F"],
  337. expect.objectContaining({ windowsHide: true }),
  338. expect.any(Function),
  339. );
  340. });
  341. it("PowerShell 全量快照与身份过滤保持同一进程创建身份", async () => {
  342. const child = {
  343. exitCode: null,
  344. pid: 4242,
  345. signalCode: null,
  346. } as ChildProcess;
  347. const snapshot = await captureProcessTreeSnapshotAsync(child);
  348. expect(await filterCurrentProcessIdentitiesAsync(snapshot!.identities, {})).toEqual(
  349. snapshot!.identities,
  350. );
  351. const secondSnapshot = await captureProcessTreeSnapshotAsync(child);
  352. expect(await filterCurrentProcessIdentitiesAsync(secondSnapshot!.identities, {})).toEqual(
  353. secondSnapshot!.identities,
  354. );
  355. });
  356. it("PowerShell 查询耗尽预算后 force 复用快照且不重复查询", async () => {
  357. const child = Object.assign(new EventEmitter(), {
  358. exitCode: null as number | null,
  359. pid: 4242,
  360. signalCode: null as NodeJS.Signals | null,
  361. }) as unknown as ChildProcess;
  362. powershellResult = powershellIdentity(4242, 1);
  363. const snapshot = await captureProcessTreeSnapshotAsync(child);
  364. const fullQueryCount = execFileMock.mock.calls.filter(
  365. ([command, args]) =>
  366. command === "powershell.exe" &&
  367. !(args as string[]).some((arg) => arg.includes("ProcessId =")),
  368. ).length;
  369. const resultPromise = terminateProcessTreeAndWait(child, {
  370. forceAfterMs: 0,
  371. snapshot,
  372. waitAfterForceMs: 30,
  373. windowsTaskkillTimeoutMs: 1,
  374. });
  375. await vi.advanceTimersByTimeAsync(0);
  376. expect(execFileMock).not.toHaveBeenCalledWith(
  377. "taskkill",
  378. ["/PID", "4242", "/T", "/F"],
  379. expect.objectContaining({ windowsHide: true }),
  380. expect.any(Function),
  381. );
  382. expect(
  383. execFileMock.mock.calls.filter(
  384. ([command, args]) =>
  385. command === "powershell.exe" &&
  386. !(args as string[]).some((arg) => arg.includes("ProcessId =")),
  387. ),
  388. ).toHaveLength(fullQueryCount);
  389. await vi.advanceTimersByTimeAsync(31);
  390. await expect(resultPromise).resolves.toEqual({ remainingPids: [4242] });
  391. });
  392. it("进程表快照查询本身也受 transport 全链路绝对 deadline 约束", async () => {
  393. const child = {
  394. exitCode: null,
  395. pid: 4242,
  396. signalCode: null,
  397. } as ChildProcess;
  398. powershellDelayMs = 50;
  399. let settled = false;
  400. const snapshotPromise = captureProcessTreeSnapshotAsync(child, {
  401. windowsCleanupDeadlineAtMs: Date.now() + 40,
  402. });
  403. void snapshotPromise.then(() => {
  404. settled = true;
  405. });
  406. await vi.advanceTimersByTimeAsync(39);
  407. expect(settled).toBe(false);
  408. await vi.advanceTimersByTimeAsync(1);
  409. // 旧实现会继续等待 PowerShell 到 60ms;绝对 deadline 到达后必须立即退化为
  410. // unavailable,让 transport 继续进入有界的 fail-closed 收口。
  411. expect(settled).toBe(true);
  412. await expect(snapshotPromise).resolves.toBeUndefined();
  413. // 让被 absolute-deadline race 截断的底层 mock 查询完成,避免模块级共享 flight 污染后续用例。
  414. await vi.advanceTimersByTimeAsync(20);
  415. });
  416. it("不为晚于共享查询启动的新 root 复用过期进程表", async () => {
  417. const firstChild = {
  418. exitCode: null,
  419. pid: 4242,
  420. signalCode: null,
  421. } as ChildProcess;
  422. const secondChild = {
  423. exitCode: null,
  424. pid: 6000,
  425. signalCode: null,
  426. } as ChildProcess;
  427. powershellDelayMs = 20;
  428. const firstSnapshotPromise = captureProcessTreeSnapshotAsync(firstChild, {
  429. ownedProcessStartedAtMs: Date.now(),
  430. });
  431. await vi.advanceTimersByTimeAsync(1);
  432. powershellResult = powershellIdentity(6000, 1);
  433. const secondSnapshotPromise = captureProcessTreeSnapshotAsync(secondChild, {
  434. ownedProcessStartedAtMs: Date.now(),
  435. });
  436. await vi.advanceTimersByTimeAsync(20);
  437. await expect(firstSnapshotPromise).resolves.toMatchObject({ rootPid: 4242 });
  438. await expect(secondSnapshotPromise).resolves.toMatchObject({ rootPid: 6000 });
  439. });
  440. it("等待 graceful taskkill flight 与稍后投递的 exit 后再判定完成", async () => {
  441. const child = Object.assign(new EventEmitter(), {
  442. exitCode: null as number | null,
  443. pid: 4242,
  444. signalCode: null as NodeJS.Signals | null,
  445. }) as unknown as ChildProcess;
  446. let completeTaskkill: (() => void) | undefined;
  447. const windowsTaskkillRunner = vi.fn(
  448. () =>
  449. new Promise<Record<string, never>>((resolve) => {
  450. completeTaskkill = () => {
  451. alivePids.delete(4242);
  452. resolve({});
  453. };
  454. }),
  455. );
  456. let result: Awaited<ReturnType<typeof terminateProcessTreeAndWait>> | undefined;
  457. const resultPromise = terminateProcessTreeAndWait(child, {
  458. forceAfterMs: 0,
  459. snapshot: await captureProcessTreeSnapshotAsync(child),
  460. waitAfterForceMs: 30,
  461. windowsTaskkillRunner,
  462. windowsTaskkillTimeoutMs: 100,
  463. });
  464. void resultPromise.then((value) => {
  465. result = value;
  466. });
  467. // Bug 回归:旧 waiter 在 graceful taskkill 尚未 settle 时按固定 force-wait 窗口
  468. // 报 remaining PID;真实进程可能只晚几个毫秒投递 ChildProcess exit。
  469. await vi.advanceTimersByTimeAsync(31);
  470. expect(result).toBeUndefined();
  471. completeTaskkill?.();
  472. await vi.advanceTimersByTimeAsync(0);
  473. expect(result).toBeUndefined();
  474. setTimeout(() => {
  475. child.exitCode = 1;
  476. child.emit("exit", 1, null);
  477. }, 5);
  478. await vi.advanceTimersByTimeAsync(5);
  479. await expect(resultPromise).resolves.toEqual({ remainingPids: [] });
  480. expect(windowsTaskkillRunner).toHaveBeenCalledWith({
  481. force: false,
  482. pid: 4242,
  483. timeoutMs: 100,
  484. });
  485. });
  486. it("root 查询期间退出并复用 PID 时不认领新进程后代", async () => {
  487. const child = Object.assign(new EventEmitter(), {
  488. exitCode: null as number | null,
  489. pid: 4242,
  490. signalCode: null as NodeJS.Signals | null,
  491. }) as unknown as ChildProcess;
  492. alivePids = new Set([4242, 5000]);
  493. powershellResult =
  494. powershellIdentityAt(4242, 1, Date.UTC(2026, 6, 24, 11, 30, 0)) +
  495. powershellIdentityAt(5000, 4242, Date.UTC(2026, 6, 24, 11, 30, 0, 100));
  496. onPowerShellQuery = () => {
  497. child.exitCode = 0;
  498. };
  499. const snapshot = await captureProcessTreeSnapshotAsync(child, {
  500. ownedProcessStartedAtMs: Date.UTC(2026, 6, 24, 10, 0, 0),
  501. });
  502. expect(snapshot).toBeUndefined();
  503. expect(execFileMock).not.toHaveBeenCalledWith(
  504. "taskkill",
  505. expect.anything(),
  506. expect.anything(),
  507. expect.anything(),
  508. );
  509. });
  510. it("root 查询期间退出且有可信 exit 时间时恢复并回收旧后代", async () => {
  511. const child = Object.assign(new EventEmitter(), {
  512. exitCode: null as number | null,
  513. pid: 4242,
  514. signalCode: null as NodeJS.Signals | null,
  515. }) as unknown as ChildProcess;
  516. alivePids = new Set([5000]);
  517. taskkillRemovesOnGraceful = true;
  518. powershellResult = powershellIdentity(5000, 4242);
  519. const exitedAtMs = Date.UTC(2026, 6, 24, 11, 30, 0);
  520. onPowerShellQuery = () => {
  521. child.exitCode = 0;
  522. };
  523. const snapshot = await captureProcessTreeSnapshotAsync(child, {
  524. ownedProcessStartedAtMs: Date.UTC(2026, 6, 24, 10, 0, 0),
  525. resolveOwnedProcessExitedAtMs: () => exitedAtMs,
  526. });
  527. expect(snapshot?.identities.map((identity) => identity.pid)).toEqual([5000]);
  528. const resultPromise = terminateProcessTreeAndWait(child, {
  529. forceAfterMs: 0,
  530. snapshot,
  531. waitAfterForceMs: 0,
  532. });
  533. await vi.advanceTimersByTimeAsync(0);
  534. await expect(resultPromise).resolves.toEqual({ remainingPids: [] });
  535. expect(execFileMock).toHaveBeenCalledWith(
  536. "taskkill",
  537. ["/PID", "5000", "/T"],
  538. expect.objectContaining({ windowsHide: true }),
  539. expect.any(Function),
  540. );
  541. });
  542. it("双后端查询失败时等待未验证 root 并明确报告残留", async () => {
  543. const child = Object.assign(new EventEmitter(), {
  544. exitCode: null as number | null,
  545. pid: 4242,
  546. signalCode: null as NodeJS.Signals | null,
  547. }) as unknown as ChildProcess;
  548. powershellResult = "";
  549. await expect(captureProcessTreeSnapshotAsync(child)).resolves.toBeUndefined();
  550. const resultPromise = terminateProcessTreeAndWait(child, {
  551. forceAfterMs: 20,
  552. snapshot: {
  553. rootPid: 4242,
  554. descendantPids: [],
  555. identities: [],
  556. identityVerification: "unavailable",
  557. },
  558. waitAfterForceMs: 30,
  559. windowsTaskkillTimeoutMs: 20,
  560. });
  561. let result: Awaited<typeof resultPromise> | undefined;
  562. void resultPromise.then((value) => {
  563. result = value;
  564. });
  565. // 查询失败且没有任何已验证 identity 时,graceful/force targets 都为空;没有实际
  566. // taskkill 可以等待,因此 deadline 不应无条件预留 taskkill timeout。
  567. await vi.advanceTimersByTimeAsync(49);
  568. expect(result).toBeUndefined();
  569. await vi.advanceTimersByTimeAsync(1);
  570. expect(result).toEqual({ remainingPids: [4242] });
  571. expect(execFileMock).not.toHaveBeenCalledWith(
  572. "taskkill",
  573. expect.anything(),
  574. expect.anything(),
  575. expect.anything(),
  576. );
  577. });
  578. it("没有 taskkill 目标时使用 transport 剩余预算观察延迟正常退出", async () => {
  579. const child = Object.assign(new EventEmitter(), {
  580. exitCode: null as number | null,
  581. pid: 4242,
  582. signalCode: null as NodeJS.Signals | null,
  583. kill: vi.fn(),
  584. }) as unknown as ChildProcess;
  585. let result: Awaited<ReturnType<typeof terminateProcessTreeAndWait>> | undefined;
  586. const resultPromise = terminateProcessTreeAndWait(child, {
  587. forceAfterMs: 0,
  588. snapshot: {
  589. rootPid: 4242,
  590. descendantPids: [],
  591. identities: [],
  592. identityVerification: "unavailable",
  593. },
  594. waitAfterForceMs: 30,
  595. windowsCleanupDeadlineAtMs: Date.now() + 1_000,
  596. windowsTaskkillTimeoutMs: 100,
  597. });
  598. void resultPromise.then((value) => {
  599. result = value;
  600. });
  601. setTimeout(() => {
  602. alivePids.delete(4242);
  603. child.exitCode = 0;
  604. child.emit("exit", 0, null);
  605. }, 600);
  606. // Bug 回归:没有可安全发送 taskkill 的身份时,旧 waiter 会把 1s 绝对预算
  607. // 压缩为 waitAfterForceMs=30ms,把随后正常 code=0 的 exit 误报为残留。
  608. await vi.advanceTimersByTimeAsync(30);
  609. expect(result).toBeUndefined();
  610. await vi.advanceTimersByTimeAsync(570);
  611. await expect(resultPromise).resolves.toEqual({ remainingPids: [] });
  612. expect(execFileMock).not.toHaveBeenCalledWith(
  613. "taskkill",
  614. expect.anything(),
  615. expect.anything(),
  616. expect.anything(),
  617. );
  618. });
  619. it("纯观察窗口不突破 Local Host 四秒总上界", async () => {
  620. const child = Object.assign(new EventEmitter(), {
  621. exitCode: null as number | null,
  622. pid: 4242,
  623. signalCode: null as NodeJS.Signals | null,
  624. }) as unknown as ChildProcess;
  625. let result: Awaited<ReturnType<typeof terminateProcessTreeAndWait>> | undefined;
  626. const resultPromise = terminateProcessTreeAndWait(child, {
  627. forceAfterMs: 0,
  628. snapshot: {
  629. rootPid: 4242,
  630. descendantPids: [],
  631. identities: [],
  632. identityVerification: "unavailable",
  633. },
  634. waitAfterForceMs: 30,
  635. windowsCleanupDeadlineAtMs: Date.now() + 1_000,
  636. windowsTaskkillTimeoutMs: 100,
  637. });
  638. void resultPromise.then((value) => {
  639. result = value;
  640. });
  641. // 首次 cleanup 最坏 3.25s;最终重试只能再观察 750ms,必须在 Local Host
  642. // 的 4s 强制退出点前明确返回真实残留,不能把完整 1.25s retry 预算串行叠加。
  643. await vi.advanceTimersByTimeAsync(749);
  644. expect(result).toBeUndefined();
  645. await vi.advanceTimersByTimeAsync(1);
  646. await expect(resultPromise).resolves.toEqual({ remainingPids: [4242] });
  647. });
  648. it("未验证 root 仍有已验证目标时保留 taskkill deadline", async () => {
  649. const child = Object.assign(new EventEmitter(), {
  650. exitCode: null as number | null,
  651. pid: 4242,
  652. signalCode: null as NodeJS.Signals | null,
  653. }) as unknown as ChildProcess;
  654. alivePids = new Set([4242, 5000]);
  655. const windowsTaskkillRunner = vi.fn(() => new Promise<Record<string, never>>(() => {}));
  656. let result: Awaited<ReturnType<typeof terminateProcessTreeAndWait>> | undefined;
  657. const resultPromise = terminateProcessTreeAndWait(child, {
  658. forceAfterMs: 20,
  659. snapshot: {
  660. rootPid: 4242,
  661. descendantPids: [5000],
  662. identities: [
  663. {
  664. parentPid: 4242,
  665. pid: 5000,
  666. startTime: "20260724190000.000000+480",
  667. },
  668. ],
  669. identityVerification: "unavailable",
  670. },
  671. waitAfterForceMs: 30,
  672. windowsTaskkillRunner,
  673. windowsTaskkillTimeoutMs: 20,
  674. });
  675. void resultPromise.then((value) => {
  676. result = value;
  677. });
  678. // 即使 root 不可验证,只要存在已验证后代,graceful taskkill 就是真实 flight;
  679. // 继续保留完整预算,不能在 force + grace 的 50ms 边界提前报告。
  680. await vi.advanceTimersByTimeAsync(50);
  681. expect(result).toBeUndefined();
  682. await vi.advanceTimersByTimeAsync(20);
  683. await expect(resultPromise).resolves.toEqual({ remainingPids: [5000, 4242] });
  684. expect(windowsTaskkillRunner).toHaveBeenCalledWith({
  685. force: false,
  686. pid: 5000,
  687. timeoutMs: 20,
  688. });
  689. });
  690. it("全链路绝对 deadline 会扣除进入 waiter 前已消耗的快照与 EOF 时间", async () => {
  691. const child = Object.assign(new EventEmitter(), {
  692. exitCode: null as number | null,
  693. pid: 4242,
  694. signalCode: null as NodeJS.Signals | null,
  695. }) as unknown as ChildProcess;
  696. const windowsTaskkillRunner = vi.fn(() => new Promise<Record<string, never>>(() => {}));
  697. let result: Awaited<ReturnType<typeof terminateProcessTreeAndWait>> | undefined;
  698. const resultPromise = terminateProcessTreeAndWait(child, {
  699. forceAfterMs: 0,
  700. snapshot: {
  701. rootPid: 4242,
  702. descendantPids: [],
  703. identities: [
  704. {
  705. parentPid: 1,
  706. pid: 4242,
  707. startTime: "20260724190000.000000+480",
  708. },
  709. ],
  710. },
  711. waitAfterForceMs: 30,
  712. // 模拟 snapshot + EOF 已经消耗 3,210ms:transport 的 3,250ms 全链路预算只剩 40ms。
  713. windowsCleanupDeadlineAtMs: Date.now() + 40,
  714. windowsTaskkillRunner,
  715. windowsTaskkillTimeoutMs: 100,
  716. });
  717. void resultPromise.then((value) => {
  718. result = value;
  719. });
  720. await vi.advanceTimersByTimeAsync(39);
  721. expect(result).toBeUndefined();
  722. await vi.advanceTimersByTimeAsync(1);
  723. // 旧实现会在这里仍为 undefined,并把窗口错误延长到 130ms;断言必须快速失败,
  724. // 不能等待旧 deadline 导致 fake-timer 用例自身超时。
  725. expect(result).toEqual({ remainingPids: [4242] });
  726. await expect(resultPromise).resolves.toEqual(result);
  727. expect(windowsTaskkillRunner).toHaveBeenCalledWith({
  728. force: false,
  729. pid: 4242,
  730. timeoutMs: 100,
  731. });
  732. });
  733. it("CIM 硬不可用时缓存 capability 并跳过后续身份查询", async () => {
  734. const child = {
  735. exitCode: null,
  736. pid: 4242,
  737. signalCode: null,
  738. } as ChildProcess;
  739. powershellError = Object.assign(new Error("powershell unavailable"), { code: "ENOENT" });
  740. await expect(captureProcessTreeSnapshotAsync(child)).resolves.toBeUndefined();
  741. const queryCount = execFileMock.mock.calls.filter(
  742. ([command]) => command === "powershell.exe",
  743. ).length;
  744. await expect(
  745. filterCurrentProcessIdentitiesAsync(
  746. [{ parentPid: 1, pid: 4242, startTime: "windows-utc-us:1784890800000000" }],
  747. {},
  748. ),
  749. ).resolves.toEqual([]);
  750. expect(
  751. execFileMock.mock.calls.filter(([command]) => command === "powershell.exe"),
  752. ).toHaveLength(queryCount);
  753. });
  754. });