processTreeTerminator.windows.test.ts 28 KB

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