Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import * as NodeURL from "node:url";
6
7import { describe, expect, it } from "@effect/vitest";
8import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
9import * as Clock from "effect/Clock";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Scope from "effect/Scope";
13
14import {
15 capturePosixOwnershipLedger,
16 isSafeCgroupPath,
17 makeLinuxCgroupController,
18 makePosixProcessTreeController,
19 observePosixOwnershipLedger,
20 observePosixOwnershipLedgerContinuously,
21 parseCgroup2Mount,
22 parseCgroup2Mounts,
23 parseUnifiedCgroupPath,
24 posixProcessIsZombie,
25 resolveLinuxCgroupTargetCommand,
26 signalLinuxCgroupRootTerm,
27 sweepStaleLinuxCgroupSiblings,
28 terminateLinuxCgroupLease,
29 terminatePosixOwnedProcessTree,
30 wrapCommandForLinuxCgroup,
31 type AcpOwnedPosixProcess,
32 type AcpLinuxCgroupLease,
33 type AcpPosixOwnershipRoot,
34 type AcpPosixProcessIdentity,
35 type AcpPosixProcessTreeController,
36} from "./AcpSessionRuntime.ts";
37
38const threadSpawnHelperSource = NodeURL.fileURLToPath(
39 new URL("../../../scripts/acp-thread-spawn-helper.c", import.meta.url),
40);
41
42const identity = (
43 pid: number,
44 ppid: number,
45 pgid: number,
46 sid: number,
47 startTime = String(pid),
48 state = "S",
49): AcpPosixProcessIdentity => ({
50 executable: `/proc/${pid}/exe`,
51 pgid,
52 pid,
53 ppid,
54 sid,
55 startTime,
56 state,
57});
58
59function makeController(input: {
60 readonly processes: ReadonlyArray<AcpPosixProcessIdentity>;
61 readonly onProcess?: (
62 processes: Map<number, AcpPosixProcessIdentity>,
63 pid: number,
64 signal: NodeJS.Signals,
65 ) => void;
66}) {
67 const processes = new Map(input.processes.map((process) => [process.pid, process]));
68 const signals: Array<string> = [];
69 const controller: AcpPosixProcessTreeController = {
70 childPidsOf: (pid) =>
71 [...processes.values()]
72 .filter((process) => process.ppid === pid)
73 .map((process) => process.pid),
74 childrenOf: (pid) => [...processes.values()].filter((process) => process.ppid === pid),
75 identity: (pid) => processes.get(pid),
76 snapshot: () => [...processes.values()],
77 signalProcess: (pid, signal) => {
78 signals.push(`process:${pid}:${signal}`);
79 if (input.onProcess) return input.onProcess(processes, pid, signal);
80 processes.delete(pid);
81 },
82 };
83 return { controller, processes, signals };
84}
85
86const server = () => identity(process.pid, 1, process.pid, process.pid, "server");
87
88function processExists(pid: number): boolean {
89 try {
90 process.kill(pid, 0);
91 return true;
92 } catch {
93 return false;
94 }
95}
96
97describe("terminatePosixOwnedProcessTree", () => {
98 it("parses unified cgroup paths and escaped cgroup2 mountinfo", () => {
99 expect(parseUnifiedCgroupPath("0::/user.slice/app.scope\n")).toBe("/user.slice/app.scope");
100 expect(parseUnifiedCgroupPath("0::/one\n0::/two\n")).toBeUndefined();
101 expect(isSafeCgroupPath("/user.slice/app.scope")).toBe(true);
102 expect(isSafeCgroupPath("/user.slice/../escape")).toBe(false);
103 expect(isSafeCgroupPath("/user.slice/app.scope (deleted)")).toBe(false);
104 expect(
105 parseCgroup2Mount(
106 "42 31 0:37 /user.slice /sys/fs/cgroup/user\\040mount rw - cgroup2 cgroup2 rw\n",
107 ),
108 ).toEqual({ mountPoint: "/sys/fs/cgroup/user mount", root: "/user.slice" });
109 expect(parseCgroup2Mount("42 31 0:37 / /sys/fs/cgroup rw - tmpfs tmpfs rw\n")).toBeUndefined();
110 expect(
111 parseCgroup2Mounts(
112 "41 31 0:36 /other /sys/fs/cgroup/other rw - cgroup2 cgroup2 rw\n" +
113 "42 31 0:37 /user.slice /sys/fs/cgroup/user rw - cgroup2 cgroup2 rw\n",
114 ),
115 ).toHaveLength(2);
116 });
117
118 it.live("sweeps empty t3-acp sibling leases owned by dead pids only", () =>
119 Effect.sync(() => {
120 const scratchRoot = NodePath.join(process.cwd(), "tmp");
121 NodeFS.mkdirSync(scratchRoot, { recursive: true });
122 const parent = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-stale-siblings-"));
123 // Temp dirs are not cgroupfs: rmdir fails when control files exist, so the
124 // test injects populated/remove while still exercising the real selection
125 // and path-safety logic against a real parent directory tree.
126 const populatedByPath = new Map<string, "0" | "1">();
127 const writeSibling = (name: string, populated: "0" | "1" | null) => {
128 const path = NodePath.join(parent, name);
129 NodeFS.mkdirSync(path);
130 if (populated !== null) populatedByPath.set(path, populated);
131 return path;
132 };
133 const deadPid = 2_147_483_646;
134 // Synthetic live foreign pid (not this process, still reported alive by the probe).
135 const liveForeignPid = 2_147_483_645;
136 const staleEmpty = writeSibling(`t3-acp-${deadPid}-aaaa`, "0");
137 const currentPidSibling = writeSibling(`t3-acp-${process.pid}-bbbb`, "0");
138 const liveForeignSibling = writeSibling(`t3-acp-${liveForeignPid}-cccc`, "0");
139 const stalePopulated = writeSibling(`t3-acp-${deadPid}-dddd`, "1");
140 const unrelated = writeSibling("other-lease", "0");
141 const isProcessAlive = (pid: number) => pid === process.pid || pid === liveForeignPid;
142 try {
143 sweepStaleLinuxCgroupSiblings(parent, {
144 isProcessAlive,
145 readPopulated: (path) => populatedByPath.get(path),
146 remove: (path) => {
147 populatedByPath.delete(path);
148 NodeFS.rmdirSync(path);
149 },
150 });
151 expect(NodeFS.existsSync(staleEmpty)).toBe(false);
152 expect(NodeFS.existsSync(currentPidSibling)).toBe(true);
153 expect(NodeFS.existsSync(liveForeignSibling)).toBe(true);
154 expect(NodeFS.existsSync(stalePopulated)).toBe(true);
155 expect(NodeFS.existsSync(unrelated)).toBe(true);
156 // Missing populated state must not remove a sibling.
157 writeSibling(`t3-acp-${deadPid}-eeee`, null);
158 sweepStaleLinuxCgroupSiblings(parent, {
159 isProcessAlive,
160 readPopulated: (path) => populatedByPath.get(path),
161 remove: (path) => {
162 populatedByPath.delete(path);
163 NodeFS.rmdirSync(path);
164 },
165 });
166 expect(NodeFS.existsSync(NodePath.join(parent, `t3-acp-${deadPid}-eeee`))).toBe(true);
167 expect(NodeFS.existsSync(currentPidSibling)).toBe(true);
168 } finally {
169 NodeFS.rmSync(parent, { recursive: true, force: true });
170 }
171 }),
172 );
173
174 it.live("preserves exact argv and strips wrapper-only environment before exec", () =>
175 Effect.gen(function* () {
176 if ((yield* HostProcessPlatform) !== "linux") return;
177 const lease = makeLinuxCgroupController().create();
178 if (lease === undefined) return;
179 const scratchRoot = NodePath.join(process.cwd(), "tmp");
180 NodeFS.mkdirSync(scratchRoot, { recursive: true });
181 const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-wrapper-"));
182 const linkedNode = NodePath.join(scratch, "T3 Code AppImage 'quoted'");
183 const bareGrok = NodePath.join(scratch, "grok");
184 const relativeBin = NodePath.join(scratch, "relative-bin");
185 const directoryBin = NodePath.join(scratch, "directory-bin");
186 const validBin = NodePath.join(scratch, "valid-bin");
187 const outputPath = NodePath.join(scratch, "argv.json");
188 NodeFS.mkdirSync(relativeBin);
189 NodeFS.mkdirSync(NodePath.join(directoryBin, "grok"), { recursive: true });
190 NodeFS.mkdirSync(validBin);
191 NodeFS.symlinkSync(process.execPath, linkedNode);
192 NodeFS.symlinkSync(process.execPath, bareGrok);
193 NodeFS.symlinkSync(process.execPath, NodePath.join(relativeBin, "grok"));
194 NodeFS.symlinkSync(process.execPath, NodePath.join(validBin, "grok"));
195 expect(resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: scratch })).toBe(bareGrok);
196 expect(resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: "" })).toBe(bareGrok);
197 // Undefined PATH uses Node's default search path (/usr/bin:/bin), not cwd alone
198 // (bareGrok lives only in cwd / PATH=scratch).
199 expect(resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: undefined })).toBeUndefined();
200 expect(resolveLinuxCgroupTargetCommand("node", scratch, { PATH: undefined })).toBeDefined();
201 expect(resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: "relative-bin" })).toBe(
202 NodePath.join(relativeBin, "grok"),
203 );
204 expect(
205 resolveLinuxCgroupTargetCommand("grok", scratch, {
206 PATH: `directory-bin${NodePath.delimiter}valid-bin`,
207 }),
208 ).toBe(NodePath.join(validBin, "grok"));
209 const target = [
210 'const fs = require("node:fs");',
211 "fs.writeFileSync(process.argv[1], JSON.stringify({",
212 " args: process.argv.slice(2),",
213 " electron: process.env.ELECTRON_RUN_AS_NODE,",
214 " wrapper: process.env.T3_ACP_CGROUP_WRAPPER,",
215 "}));",
216 ].join("\n");
217 const wrapped = wrapCommandForLinuxCgroup(lease, linkedNode, [
218 "-e",
219 target,
220 outputPath,
221 "space value",
222 "single'quote",
223 'double"quote',
224 ]);
225 try {
226 const result = NodeChildProcess.spawnSync(wrapped.command, wrapped.args, {
227 encoding: "utf8",
228 env: {
229 ...process.env,
230 ELECTRON_RUN_AS_NODE: "1",
231 T3_ACP_CGROUP_WRAPPER: "1",
232 },
233 });
234 expect(result.status, result.stderr).toBe(0);
235 expect(NodeFS.readFileSync(outputPath, "utf8")).toBe(
236 '{"args":["space value","single\'quote","double\\"quote"]}',
237 );
238 } finally {
239 yield* terminateLinuxCgroupLease(lease).pipe(Effect.ignore);
240 NodeFS.rmSync(scratch, { recursive: true, force: true });
241 }
242 }),
243 );
244
245 it.live("kills a post-TERM detached double fork without touching an unrelated sentinel", () =>
246 Effect.gen(function* () {
247 if ((yield* HostProcessPlatform) !== "linux") return;
248 const controller = makeLinuxCgroupController();
249 const lease = controller.create();
250 if (lease === undefined) return;
251 expect(parseUnifiedCgroupPath(NodeFS.readFileSync("/proc/self/cgroup", "utf8"))).not.toBe(
252 lease.relativePath,
253 );
254 const scratchRoot = NodePath.join(process.cwd(), "tmp");
255 NodeFS.mkdirSync(scratchRoot, { recursive: true });
256 const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-kill-"));
257 const readyPath = NodePath.join(scratch, "ready");
258 const childPath = NodePath.join(scratch, "child");
259 const childProgram = "setInterval(() => {}, 1000);";
260 const launcherProgram = [
261 'const fs = require("node:fs");',
262 'const cp = require("node:child_process");',
263 "const child = cp.spawn(process.execPath, ['-e', process.argv[2]], { detached: true, stdio: 'ignore' });",
264 "fs.writeFileSync(process.argv[1], String(child.pid));",
265 "child.unref();",
266 ].join("\n");
267 const providerProgram = [
268 'const fs = require("node:fs");',
269 'const cp = require("node:child_process");',
270 "fs.writeFileSync(process.argv[1], String(process.pid));",
271 "process.on('SIGTERM', () => {",
272 " const launcher = cp.spawn(process.execPath, ['-e', process.argv[3], process.argv[2], process.argv[4]], { detached: true, stdio: 'ignore' });",
273 " launcher.unref();",
274 " process.exit(0);",
275 "});",
276 "setInterval(() => {}, 1000);",
277 ].join("\n");
278 const wrapped = wrapCommandForLinuxCgroup(lease, process.execPath, [
279 "-e",
280 providerProgram,
281 readyPath,
282 childPath,
283 launcherProgram,
284 childProgram,
285 ]);
286 const provider = NodeChildProcess.spawn(wrapped.command, wrapped.args, {
287 detached: true,
288 env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", T3_ACP_CGROUP_WRAPPER: "1" },
289 stdio: "ignore",
290 });
291 provider.unref();
292 const sentinel = NodeChildProcess.spawn(process.execPath, ["-e", childProgram], {
293 detached: true,
294 stdio: "ignore",
295 });
296 sentinel.unref();
297 let detachedChildPid: number | undefined;
298 try {
299 yield* Effect.gen(function* () {
300 while (!NodeFS.existsSync(readyPath)) yield* Effect.sleep("10 millis");
301 }).pipe(Effect.timeout("2 seconds"));
302 process.kill(provider.pid!, "SIGTERM");
303 detachedChildPid = yield* Effect.gen(function* () {
304 while (true) {
305 try {
306 const pid = Number(NodeFS.readFileSync(childPath, "utf8"));
307 if (Number.isSafeInteger(pid) && pid > 1) return pid;
308 } catch {
309 // The TERM-time launcher has not published its child yet.
310 }
311 yield* Effect.sleep("10 millis");
312 }
313 }).pipe(Effect.timeout("2 seconds"));
314 expect(processExists(detachedChildPid)).toBe(true);
315 yield* terminateLinuxCgroupLease(lease);
316 expect(processExists(sentinel.pid!)).toBe(true);
317 yield* Effect.gen(function* () {
318 while (processExists(detachedChildPid!)) yield* Effect.sleep("10 millis");
319 }).pipe(Effect.timeout("2 seconds"));
320 expect(NodeFS.existsSync(lease.path)).toBe(false);
321
322 const replacement = controller.create();
323 expect(replacement?.path).not.toBe(lease.path);
324 if (replacement !== undefined) {
325 NodeFS.mkdirSync(NodePath.join(replacement.path, "nested"));
326 yield* terminateLinuxCgroupLease(replacement);
327 expect(NodeFS.existsSync(replacement.path)).toBe(false);
328 }
329 } finally {
330 yield* terminateLinuxCgroupLease(lease).pipe(Effect.ignore);
331 try {
332 process.kill(-provider.pid!, "SIGKILL");
333 } catch {
334 // The contained provider already exited.
335 }
336 try {
337 process.kill(-sentinel.pid!, "SIGKILL");
338 } catch {
339 // The unrelated sentinel already exited.
340 }
341 if (detachedChildPid !== undefined && processExists(detachedChildPid)) {
342 try {
343 process.kill(detachedChildPid, "SIGKILL");
344 } catch {
345 // The detached child already exited.
346 }
347 }
348 NodeFS.rmSync(scratch, { recursive: true, force: true });
349 }
350 }),
351 );
352
353 it.live("re-kills repopulated cgroups and verifies root removal after retryable errors", () =>
354 Effect.gen(function* () {
355 let exists = true;
356 let killCalls = 0;
357 let populated = false;
358 let removeCalls = 0;
359 const lease: AcpLinuxCgroupLease = {
360 contains: () => false,
361 exists: () => exists,
362 path: "/test/t3-acp-repopulation",
363 relativePath: "/test/t3-acp-repopulation",
364 kill: () => {
365 killCalls += 1;
366 populated = false;
367 },
368 populated: () => populated,
369 remove: () => {
370 removeCalls += 1;
371 if (removeCalls === 1) {
372 populated = true;
373 const error = new Error("repopulated") as NodeJS.ErrnoException;
374 error.code = "EBUSY";
375 throw error;
376 }
377 if (removeCalls === 2) {
378 const error = new Error("nested path vanished") as NodeJS.ErrnoException;
379 error.code = "ENOENT";
380 throw error;
381 }
382 exists = false;
383 },
384 };
385
386 yield* terminateLinuxCgroupLease(lease);
387 expect(killCalls).toBeGreaterThanOrEqual(3);
388 expect(removeCalls).toBe(3);
389 expect(exists).toBe(false);
390 yield* terminateLinuxCgroupLease(lease);
391 expect(removeCalls).toBe(3);
392 }),
393 );
394
395 it.live("reports persistent retryable removal failures as removal failures", () =>
396 Effect.gen(function* () {
397 const removeError = Object.assign(new Error("cgroup remains busy"), {
398 code: "EBUSY",
399 });
400 const lease: AcpLinuxCgroupLease = {
401 contains: () => false,
402 exists: () => true,
403 path: "/test/t3-acp-busy",
404 relativePath: "/test/t3-acp-busy",
405 kill: () => undefined,
406 populated: () => false,
407 remove: () => {
408 throw removeError;
409 },
410 };
411
412 const error = yield* Effect.flip(terminateLinuxCgroupLease(lease));
413 expect(error.detail).toBe("Failed to remove ACP cgroup /test/t3-acp-busy");
414 expect(error.cause).toBe(removeError);
415 }),
416 );
417
418 it("sends TERM only to the exact captured root while it remains in the child cgroup", () => {
419 const fixture = makeController({
420 processes: [server(), identity(100, process.pid, 100, 100, "owned")],
421 });
422 const ownedRoot: AcpOwnedPosixProcess = {
423 ...identity(100, process.pid, 100, 100, "owned"),
424 parentExecutable: server().executable,
425 parentStartTime: server().startTime,
426 };
427 const root: AcpPosixOwnershipRoot = { captureAttempted: true, value: ownedRoot };
428 const lease: AcpLinuxCgroupLease = {
429 contains: () => true,
430 exists: () => true,
431 path: "/test/t3-acp-root",
432 relativePath: "/test/t3-acp-root",
433 kill: () => undefined,
434 populated: () => true,
435 remove: () => undefined,
436 };
437 signalLinuxCgroupRootTerm({ controller: fixture.controller, lease, root });
438 expect(fixture.signals).toEqual(["process:100:SIGTERM"]);
439
440 const reused = makeController({
441 processes: [server(), identity(100, process.pid, 100, 100, "reused")],
442 });
443 signalLinuxCgroupRootTerm({ controller: reused.controller, lease, root });
444 expect(reused.signals).toEqual([]);
445
446 const migrated = makeController({
447 processes: [server(), identity(100, process.pid, 100, 100, "owned")],
448 });
449 signalLinuxCgroupRootTerm({
450 controller: migrated.controller,
451 lease: { ...lease, contains: () => false },
452 root,
453 });
454 expect(migrated.signals).toEqual([]);
455 });
456
457 it.live("finds a child forked by a non-leader pthread", () =>
458 Effect.gen(function* () {
459 if ((yield* HostProcessPlatform) !== "linux") return;
460 const scratchRoot = NodePath.join(process.cwd(), "tmp");
461 NodeFS.mkdirSync(scratchRoot, { recursive: true });
462 const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-pthread-spawn-"));
463 const binary = NodePath.join(scratch, "helper");
464 const pidPath = NodePath.join(scratch, "pids");
465 expect(NodeFS.statSync(threadSpawnHelperSource).isFile()).toBe(true);
466 const compile = NodeChildProcess.spawnSync(
467 "cc",
468 ["-pthread", threadSpawnHelperSource, "-o", binary],
469 {
470 encoding: "utf8",
471 },
472 );
473 if ((compile.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") {
474 NodeFS.rmSync(scratch, { recursive: true, force: true });
475 return;
476 }
477 expect(compile.status, compile.stderr).toBe(0);
478 const helper = NodeChildProcess.spawn(binary, [pidPath], { detached: true, stdio: "ignore" });
479 helper.unref();
480 try {
481 const published = yield* Effect.gen(function* () {
482 while (true) {
483 try {
484 const ids = NodeFS.readFileSync(pidPath, "utf8").trim().split(/\s+/).map(Number);
485 if (ids.length === 2 && ids.every(Number.isSafeInteger)) return ids;
486 } catch {
487 // The worker has not published its TID and child yet.
488 }
489 yield* Effect.sleep("10 millis");
490 }
491 }).pipe(Effect.timeout("2 seconds"));
492 const [workerTid, childPid] = published;
493 expect(workerTid).not.toBe(helper.pid);
494 expect(makePosixProcessTreeController("linux").childrenOf(helper.pid!)).toContainEqual(
495 expect.objectContaining({ pid: childPid, ppid: helper.pid }),
496 );
497 } finally {
498 try {
499 process.kill(-helper.pid!, "SIGKILL");
500 } catch {
501 // The isolated fixture already exited.
502 }
503 NodeFS.rmSync(scratch, { recursive: true, force: true });
504 }
505 }),
506 );
507
508 it.live("keeps ownership across a fork-before-exec executable transition", () =>
509 Effect.gen(function* () {
510 const beforeExec = { ...identity(110, 100, 110, 110), executable: "/provider/fork" };
511 const fixture = makeController({
512 processes: [server(), identity(100, process.pid, 100, 100), beforeExec],
513 });
514 const frontier = new Map<number, AcpOwnedPosixProcess>();
515 const childQueues = new Map<number, Array<number>>();
516 const ledger = new Map<string, AcpOwnedPosixProcess>();
517 const root: AcpPosixOwnershipRoot = { value: undefined };
518 observePosixOwnershipLedger({
519 childQueues,
520 controller: fixture.controller,
521 frontier,
522 ledger,
523 root,
524 rootPid: 100,
525 });
526 fixture.processes.set(110, { ...beforeExec, executable: "/usr/bin/bash" });
527 observePosixOwnershipLedger({
528 childQueues,
529 controller: fixture.controller,
530 frontier,
531 ledger,
532 root,
533 rootPid: 100,
534 });
535
536 expect([...ledger.values()].find((process) => process.pid === 110)?.executable).toBe(
537 "/usr/bin/bash",
538 );
539 yield* terminatePosixOwnedProcessTree({
540 controller: fixture.controller,
541 grace: 0,
542 ledger,
543 rootPid: 100,
544 });
545 expect(fixture.signals).toContain("process:110:SIGTERM");
546 expect(fixture.processes.has(110)).toBe(false);
547 }),
548 );
549
550 it("never adopts a replacement PID after initial root capture failed", () => {
551 const fixture = makeController({ processes: [server()] });
552 const frontier = new Map<number, AcpOwnedPosixProcess>();
553 const childQueues = new Map<number, Array<number>>();
554 const ledger = new Map<string, AcpOwnedPosixProcess>();
555 const root: AcpPosixOwnershipRoot = { value: undefined };
556 const capture = () => {
557 try {
558 observePosixOwnershipLedger({
559 childQueues,
560 controller: fixture.controller,
561 frontier,
562 ledger,
563 root,
564 rootPid: 100,
565 });
566 return undefined;
567 } catch (error) {
568 return error;
569 }
570 };
571 expect(capture()).toMatchObject({
572 detail: "ACP process 100 exited before its ownership ledger was captured",
573 });
574 fixture.processes.set(100, identity(100, process.pid, 100, 100, "reused"));
575 expect(capture()).toMatchObject({
576 detail: "ACP process 100 exited before its ownership ledger was captured",
577 });
578 expect(ledger.size).toBe(0);
579 });
580
581 it.live("rotates more than 64 live parents without scanning retained tombstones", () =>
582 Effect.gen(function* () {
583 const parents = Array.from({ length: 130 }, (_, index) =>
584 identity(1_000 + index, 100, 1_000 + index, 1_000 + index),
585 );
586 let childListReads = 0;
587 let identityCalls = 0;
588 let snapshotCalls = 0;
589 const fixture = makeController({
590 processes: [server(), identity(100, process.pid, 100, 100)],
591 });
592 const controller: AcpPosixProcessTreeController = {
593 ...fixture.controller,
594 childPidsOf: (pid) => {
595 childListReads += 1;
596 return fixture.controller.childPidsOf(pid);
597 },
598 identity: (pid) => {
599 identityCalls += 1;
600 return fixture.controller.identity(pid);
601 },
602 snapshot: () => {
603 snapshotCalls += 1;
604 return fixture.controller.snapshot();
605 },
606 };
607 const frontier = new Map<number, AcpOwnedPosixProcess>();
608 const childQueues = new Map<number, Array<number>>();
609 const ledger = new Map<string, AcpOwnedPosixProcess>();
610 const root: AcpPosixOwnershipRoot = { value: undefined };
611 for (let index = 0; index < 5_000; index += 1) {
612 const tombstone = identity(100_000 + index, 1, 100_000 + index, 100_000 + index);
613 ledger.set(`${tombstone.pid}:${tombstone.startTime}`, {
614 ...tombstone,
615 parentExecutable: undefined,
616 parentStartTime: "",
617 });
618 }
619 observePosixOwnershipLedger({
620 childQueues,
621 controller,
622 frontier,
623 ledger,
624 root,
625 rootPid: 100,
626 });
627 for (const parent of parents) {
628 fixture.processes.set(parent.pid, parent);
629 fixture.processes.set(
630 parent.pid + 10_000,
631 identity(parent.pid + 10_000, parent.pid, parent.pgid, parent.sid),
632 );
633 }
634 let passes = 0;
635 while (
636 !parents.every((parent) =>
637 [...ledger.values()].some((owned) => owned.pid === parent.pid + 10_000),
638 ) &&
639 passes < 40
640 ) {
641 childListReads = 0;
642 identityCalls = 0;
643 observePosixOwnershipLedger({
644 childQueues,
645 controller,
646 frontier,
647 ledger,
648 maxProcesses: 64,
649 root,
650 rootPid: 100,
651 });
652 expect(identityCalls + childListReads).toBeLessThanOrEqual(64);
653 passes += 1;
654 }
655
656 const missing = parents.filter(
657 (parent) => ![...ledger.values()].some((owned) => owned.pid === parent.pid + 10_000),
658 );
659 expect(missing, `missing after ${passes} passes`).toEqual([]);
660 expect(passes).toBeGreaterThan(2);
661 yield* terminatePosixOwnedProcessTree({
662 controller,
663 grace: 0,
664 ledger,
665 rootPid: 100,
666 });
667 expect(snapshotCalls).toBe(10);
668 expect(fixture.processes.size).toBe(1);
669 }),
670 );
671
672 it.live("polls only known descendants and stops with its scope", () =>
673 Effect.gen(function* () {
674 let childrenCalls = 0;
675 let identityCalls = 0;
676 let snapshotCalls = 0;
677 const fixture = makeController({
678 processes: [server(), identity(100, process.pid, 100, 100), identity(110, 100, 110, 110)],
679 });
680 const controller: AcpPosixProcessTreeController = {
681 ...fixture.controller,
682 childPidsOf: (pid) => {
683 childrenCalls += 1;
684 return fixture.controller.childPidsOf(pid);
685 },
686 identity: (pid) => {
687 identityCalls += 1;
688 return fixture.controller.identity(pid);
689 },
690 snapshot: () => {
691 snapshotCalls += 1;
692 return fixture.controller.snapshot();
693 },
694 };
695 const scope = yield* Scope.make();
696 const frontier = new Map<number, AcpOwnedPosixProcess>();
697 const childQueues = new Map<number, Array<number>>();
698 let ledgerValuesCalls = 0;
699 const ledger = new (class extends Map<string, AcpOwnedPosixProcess> {
700 override values(): MapIterator<AcpOwnedPosixProcess> {
701 ledgerValuesCalls += 1;
702 return super.values();
703 }
704 })();
705 const root: AcpPosixOwnershipRoot = { value: undefined };
706 for (let index = 0; index < 5_000; index += 1) {
707 const tombstone = identity(10_000 + index, 1, 10_000 + index, 10_000 + index);
708 ledger.set(`${tombstone.pid}:${tombstone.startTime}`, {
709 ...tombstone,
710 parentExecutable: undefined,
711 parentStartTime: "",
712 });
713 }
714 yield* observePosixOwnershipLedgerContinuously({
715 childQueues,
716 controller,
717 frontier,
718 ledger,
719 root,
720 rootPid: 100,
721 }).pipe(Effect.forkIn(scope));
722 const timerStartedAt = yield* Clock.currentTimeMillis;
723 yield* Effect.sleep(0);
724 const timerDelay = (yield* Clock.currentTimeMillis) - timerStartedAt;
725 yield* Effect.sleep("80 millis");
726
727 expect(timerDelay).toBeLessThan(250);
728 expect(ledgerValuesCalls).toBe(0);
729 expect(snapshotCalls).toBe(0);
730 expect(childrenCalls).toBeGreaterThan(0);
731 expect(childrenCalls).toBeLessThanOrEqual(12);
732 const callsAtClose = identityCalls + childrenCalls;
733 yield* Scope.close(scope, Exit.void);
734 yield* Effect.sleep("60 millis");
735 expect(identityCalls + childrenCalls).toBe(callsAtClose);
736 }),
737 );
738
739 it.live("terminates nested owned groups bottom-up and catches a TERM fork race", () =>
740 Effect.gen(function* () {
741 let forked = false;
742 const fixture = makeController({
743 processes: [
744 server(),
745 identity(100, process.pid, 100, 100),
746 identity(110, 100, 110, 110),
747 identity(115, 110, 115, 110),
748 identity(120, 110, 120, 120),
749 identity(121, 120, 120, 120),
750 ],
751 onProcess: (processes, pid, signal) => {
752 if (signal === "SIGTERM" && pid === 121 && !forked) {
753 forked = true;
754 processes.set(122, identity(122, 110, 122, 122));
755 }
756 processes.delete(pid);
757 },
758 });
759
760 yield* terminatePosixOwnedProcessTree({
761 controller: fixture.controller,
762 grace: 0,
763 rootPid: 100,
764 });
765
766 expect(fixture.processes.has(100)).toBe(false);
767 expect(fixture.processes.has(122)).toBe(false);
768 expect(fixture.signals.indexOf("process:121:SIGTERM")).toBeLessThan(
769 fixture.signals.indexOf("process:120:SIGTERM"),
770 );
771 expect(fixture.signals.indexOf("process:115:SIGTERM")).toBeLessThan(
772 fixture.signals.indexOf("process:110:SIGTERM"),
773 );
774 }),
775 );
776
777 it.live("falls back to exact PIDs for unknown group members and a missing leader", () =>
778 Effect.gen(function* () {
779 const unrelated = identity(999, 1, 110, 110, "unrelated");
780 const fixture = makeController({
781 processes: [
782 server(),
783 identity(100, process.pid, 100, 100),
784 identity(110, 100, 110, 110),
785 identity(111, 110, 110, 110),
786 unrelated,
787 ],
788 onProcess: (processes, pid) => {
789 processes.delete(pid);
790 if (pid === 111) processes.delete(110);
791 },
792 });
793
794 yield* terminatePosixOwnedProcessTree({
795 controller: fixture.controller,
796 grace: 0,
797 rootPid: 100,
798 });
799
800 expect(fixture.signals).toContain("process:111:SIGTERM");
801 expect(fixture.processes.get(999)).toEqual(unrelated);
802 }),
803 );
804
805 it.live("re-admits a still-owned child after PID reuse and never signals the T3 session", () =>
806 Effect.gen(function* () {
807 const reused = identity(110, 100, 110, 110, "reused");
808 const fixture = makeController({
809 processes: [
810 server(),
811 identity(100, process.pid, 100, 100),
812 identity(110, 100, 110, 110, "owned"),
813 identity(120, 100, 120, process.pid),
814 ],
815 onProcess: (processes, pid) => {
816 if (pid === 110) processes.set(110, reused);
817 else processes.delete(pid);
818 },
819 });
820
821 const result = yield* Effect.exit(
822 terminatePosixOwnedProcessTree({
823 controller: fixture.controller,
824 grace: 0,
825 rootPid: 100,
826 }),
827 );
828
829 // PID 110 morphs to a new identity under the owned root and never exits, so
830 // teardown fails closed after re-admitting and re-signalling the live child.
831 expect(Exit.isFailure(result)).toBe(true);
832 expect(fixture.processes.get(110)).toEqual(reused);
833 expect(
834 fixture.signals.filter((entry) => entry.startsWith("process:110:")).length,
835 ).toBeGreaterThan(0);
836 expect(fixture.signals.some((entry) => entry.includes(":120:"))).toBe(false);
837 }),
838 );
839
840 it.live("does not treat zombie residual entries as teardown survivors", () =>
841 Effect.gen(function* () {
842 expect(posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "Z" })).toBe(true);
843 expect(posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "S" })).toBe(false);
844 const withoutState: AcpPosixProcessIdentity = {
845 executable: "/proc/1/exe",
846 pgid: 1,
847 pid: 1,
848 ppid: 0,
849 sid: 1,
850 startTime: "1",
851 };
852 expect(posixProcessIsZombie(withoutState)).toBe(false);
853
854 const root = identity(100, process.pid, 100, 100);
855 const zombieChild = identity(110, 100, 110, 110, "110", "Z");
856 const fixture = makeController({
857 processes: [server(), root, zombieChild],
858 onProcess: (processes, pid) => {
859 // Kill leaves a zombie with the same pid/starttime until reaped.
860 const current = processes.get(pid);
861 if (current === undefined) return;
862 processes.set(pid, { ...current, state: "Z" });
863 },
864 });
865 yield* terminatePosixOwnedProcessTree({
866 controller: fixture.controller,
867 grace: 0,
868 rootPid: 100,
869 });
870 // Zombies remain visible but must not fail residual teardown.
871 expect(fixture.processes.get(100)?.state).toBe("Z");
872 expect(fixture.processes.get(110)?.state).toBe("Z");
873 }),
874 );
875
876 it("admits a live child after a free PID was previously reserved by a dead entry", () => {
877 const staleChild: AcpOwnedPosixProcess = {
878 ...identity(200, 100, 200, 200, "stale-child"),
879 parentExecutable: `/proc/100/exe`,
880 parentStartTime: "100",
881 };
882 const liveChild = identity(200, 100, 200, 200, "live-child");
883 const root = identity(100, process.pid, 100, 100);
884 const ownedRoot: AcpOwnedPosixProcess = {
885 ...root,
886 parentExecutable: `/proc/${process.pid}/exe`,
887 parentStartTime: "server",
888 };
889 const ledger = new Map<string, AcpOwnedPosixProcess>([
890 [`100:${root.startTime}`, ownedRoot],
891 [`200:${staleChild.startTime}`, staleChild],
892 ]);
893 const controller = makeController({
894 processes: [server(), root],
895 }).controller;
896
897 // First capture: PID 200 is free, so the dead reservation is dropped.
898 capturePosixOwnershipLedger({
899 controller,
900 ledger,
901 rootPid: 100,
902 table: [root],
903 });
904 expect([...ledger.values()].some((entry) => entry.pid === 200)).toBe(false);
905
906 // Second capture: a new process reuses PID 200 under the owned parent.
907 capturePosixOwnershipLedger({
908 controller: makeController({ processes: [server(), root, liveChild] }).controller,
909 ledger,
910 rootPid: 100,
911 table: [root, liveChild],
912 });
913
914 const admitted = [...ledger.values()].find((entry) => entry.pid === 200);
915 expect(admitted?.startTime).toBe("live-child");
916 });
917
918 it("admits a live child when a stale ledger entry still occupies the reused PID", () => {
919 const staleChild: AcpOwnedPosixProcess = {
920 ...identity(200, 100, 200, 200, "stale-child"),
921 parentExecutable: `/proc/100/exe`,
922 parentStartTime: "100",
923 };
924 const liveChild = identity(200, 100, 200, 200, "live-child");
925 const root = identity(100, process.pid, 100, 100);
926 const ownedRoot: AcpOwnedPosixProcess = {
927 ...root,
928 parentExecutable: `/proc/${process.pid}/exe`,
929 parentStartTime: "server",
930 };
931 const ledger = new Map<string, AcpOwnedPosixProcess>([
932 [`100:${root.startTime}`, ownedRoot],
933 [`200:${staleChild.startTime}`, staleChild],
934 ]);
935
936 capturePosixOwnershipLedger({
937 controller: makeController({ processes: [server(), root, liveChild] }).controller,
938 ledger,
939 rootPid: 100,
940 table: [root, liveChild],
941 });
942
943 expect([...ledger.values()].some((entry) => entry.startTime === "stale-child")).toBe(false);
944 const admitted = [...ledger.values()].find((entry) => entry.pid === 200);
945 expect(admitted?.startTime).toBe("live-child");
946 });
947
948 it.live("signals children forked under a still-live parent during the same pass", () =>
949 Effect.gen(function* () {
950 let forked = false;
951 const fixture = makeController({
952 processes: [
953 server(),
954 identity(100, process.pid, 100, 100),
955 identity(110, 100, 110, 110),
956 identity(111, 110, 111, 111),
957 ],
958 onProcess: (processes, pid) => {
959 // Bottom-up: signal 111 first while 110 is still live, then fork 112
960 // under 110 so the same pass must enqueue and signal 112.
961 if (pid === 111 && !forked) {
962 forked = true;
963 processes.set(112, identity(112, 110, 112, 112));
964 }
965 processes.delete(pid);
966 },
967 });
968
969 yield* terminatePosixOwnedProcessTree({
970 controller: fixture.controller,
971 grace: 0,
972 rootPid: 100,
973 });
974
975 expect(forked).toBe(true);
976 expect(fixture.processes.has(112)).toBe(false);
977 expect(fixture.signals.some((entry) => entry.startsWith("process:112:"))).toBe(true);
978 }),
979 );
980
981 it.live("detects an owned child first observed in the final survivor snapshot", () =>
982 Effect.gen(function* () {
983 const lateChild = identity(111, 110, 111, 111);
984 const fixture = makeController({
985 processes: [server(), identity(100, process.pid, 100, 100), identity(110, 100, 110, 110)],
986 onProcess: (processes, pid) => {
987 // Leave the descendant parent alive through teardown so it can fork
988 // immediately after the last signal pass.
989 if (pid !== 110) processes.delete(pid);
990 },
991 });
992 let snapshotCalls = 0;
993 const controller: AcpPosixProcessTreeController = {
994 ...fixture.controller,
995 snapshot: () => {
996 snapshotCalls += 1;
997 // Two TERM discovery passes, the root TERM pass, and two KILL passes
998 // precede the final survivor snapshot.
999 if (snapshotCalls === 6) fixture.processes.set(lateChild.pid, lateChild);
1000 return fixture.controller.snapshot();
1001 },
1002 };
1003
1004 const error = yield* Effect.flip(
1005 terminatePosixOwnedProcessTree({
1006 controller,
1007 discoveryPasses: 2,
1008 grace: 0,
1009 rootPid: 100,
1010 }),
1011 );
1012
1013 expect(snapshotCalls).toBe(6);
1014 expect(error.detail).toContain("110, 111");
1015 }),
1016 );
1017
1018 it.live("retains the ledger across root exit and an explicit failure for finalizer retry", () =>
1019 Effect.gen(function* () {
1020 let ignoreSignals = true;
1021 const ledger = new Map<string, AcpOwnedPosixProcess>();
1022 const frontier = new Map<number, AcpOwnedPosixProcess>();
1023 const childQueues = new Map<number, Array<number>>();
1024 const root: AcpPosixOwnershipRoot = { value: undefined };
1025 const fixture = makeController({
1026 processes: [
1027 server(),
1028 identity(100, process.pid, 100, 100),
1029 identity(110, 100, 110, 110),
1030 identity(111, 110, 110, 110),
1031 ],
1032 onProcess: (processes, pid) => {
1033 if (ignoreSignals && pid === 100) processes.delete(100);
1034 if (!ignoreSignals) processes.delete(pid);
1035 },
1036 });
1037 observePosixOwnershipLedger({
1038 childQueues,
1039 controller: fixture.controller,
1040 frontier,
1041 ledger,
1042 root,
1043 rootPid: 100,
1044 });
1045
1046 const explicit = yield* Effect.exit(
1047 terminatePosixOwnedProcessTree({
1048 controller: fixture.controller,
1049 grace: 0,
1050 ledger,
1051 rootPid: 100,
1052 }),
1053 );
1054 expect(Exit.isFailure(explicit)).toBe(true);
1055 expect(fixture.processes.has(100)).toBe(false);
1056 expect(fixture.processes.has(111)).toBe(true);
1057
1058 fixture.processes.set(112, identity(112, 110, 112, 112));
1059 observePosixOwnershipLedger({
1060 childQueues,
1061 controller: fixture.controller,
1062 frontier,
1063 ledger,
1064 root,
1065 rootPid: 100,
1066 });
1067 ignoreSignals = false;
1068 yield* terminatePosixOwnedProcessTree({
1069 controller: fixture.controller,
1070 grace: 0,
1071 ledger,
1072 rootPid: 100,
1073 });
1074 expect(fixture.processes.has(110)).toBe(false);
1075 expect(fixture.processes.has(111)).toBe(false);
1076 expect(fixture.processes.has(112)).toBe(false);
1077 }),
1078 );
1079
1080 it("fails closed where a stable POSIX identity provider is unavailable", () => {
1081 try {
1082 makePosixProcessTreeController("darwin");
1083 throw new Error("Expected Darwin process ownership to fail closed");
1084 } catch (error) {
1085 expect(error).toMatchObject({
1086 detail: "Detached ACP descendant ownership is unsupported on darwin",
1087 });
1088 }
1089 });
1090});