Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpSessionRuntime.processTree.test.ts

1,164 lines42.0 KB

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, vi } 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 };
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 }
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("contains a packaged-runtime command without requiring cgroup delegation", () => {
246 if (HostProcessPlatform.defaultValue() !== "linux") return;
247 const scratchRoot = NodePath.join(process.cwd(), "tmp");
248 NodeFS.mkdirSync(scratchRoot, { recursive: true });
249 const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-wrapper-fake-"));
250 const leasePath = NodePath.join(scratch, "lease with spaces");
251 const outputPath = NodePath.join(scratch, "argv output");
252 NodeFS.mkdirSync(leasePath);
253 NodeFS.writeFileSync(NodePath.join(leasePath, "cgroup.procs"), "");
254 const relativePath = parseUnifiedCgroupPath(NodeFS.readFileSync("/proc/self/cgroup", "utf8"));
255 expect(relativePath).toBeDefined();
256 const lease: AcpLinuxCgroupLease = {
257 contains: () => false,
258 exists: () => true,
259 path: leasePath,
260 relativePath: relativePath!,
261 kill: () => undefined,
262 populated: () => false,
263 remove: () => undefined,
264 };
265 const packagedExecPath = vi.spyOn(process, "execPath", "get").mockReturnValue("/bin/sh");
266 try {
267 const wrapped = wrapCommandForLinuxCgroup(lease, "/bin/sh", [
268 "-c",
269 'printf "%s\\n" "$0" "$1" "$2" "$3" "${ELECTRON_RUN_AS_NODE-}" "${T3_ACP_CGROUP_WRAPPER-}" > "$4"',
270 "packaged-target",
271 "space value",
272 "single'quote",
273 'double"quote',
274 outputPath,
275 ]);
276 const result = NodeChildProcess.spawnSync(wrapped.command, wrapped.args, {
277 encoding: "utf8",
278 env: {
279 ...process.env,
280 ELECTRON_RUN_AS_NODE: "1",
281 T3_ACP_CGROUP_WRAPPER: "1",
282 },
283 });
284 expect(result.status, result.stderr).toBe(0);
285 expect(NodeFS.readFileSync(outputPath, "utf8")).toBe(
286 "packaged-target\nspace value\nsingle'quote\ndouble\"quote\n\n\n",
287 );
288 expect(NodeFS.readFileSync(NodePath.join(leasePath, "cgroup.procs"), "utf8")).toMatch(
289 /^\d+\n$/,
290 );
291​
292 const mismatch = wrapCommandForLinuxCgroup(
293 { ...lease, relativePath: "/not-the-current-cgroup" },
294 "/bin/sh",
295 ["-c", 'printf executed > "$0"', outputPath],
296 );
297 NodeFS.rmSync(outputPath);
298 const mismatchResult = NodeChildProcess.spawnSync(mismatch.command, mismatch.args, {
299 encoding: "utf8",
300 });
301 expect(mismatchResult.status, mismatchResult.stderr).toBe(126);
302 expect(NodeFS.existsSync(outputPath)).toBe(false);
303​
304 const missingTarget = wrapCommandForLinuxCgroup(lease, "/nonexistent-t3-probe", []);
305 const missingTargetResult = NodeChildProcess.spawnSync(
306 missingTarget.command,
307 missingTarget.args,
308 {
309 encoding: "utf8",
310 },
311 );
312 expect(missingTargetResult.status, missingTargetResult.stderr).toBe(125);
313 } finally {
314 packagedExecPath.mockRestore();
315 NodeFS.rmSync(scratch, { recursive: true, force: true });
316 }
317 });
318​
319 it.live("kills a post-TERM detached double fork without touching an unrelated sentinel", () =>
320 Effect.gen(function* () {
321 if ((yield* HostProcessPlatform) !== "linux") return;
322 const controller = makeLinuxCgroupController();
323 const lease = controller.create();
324 if (lease === undefined) return;
325 expect(parseUnifiedCgroupPath(NodeFS.readFileSync("/proc/self/cgroup", "utf8"))).not.toBe(
326 lease.relativePath,
327 );
328 const scratchRoot = NodePath.join(process.cwd(), "tmp");
329 NodeFS.mkdirSync(scratchRoot, { recursive: true });
330 const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-kill-"));
331 const readyPath = NodePath.join(scratch, "ready");
332 const childPath = NodePath.join(scratch, "child");
333 const childProgram = "setInterval(() => {}, 1000);";
334 const launcherProgram = [
335 'const fs = require("node:fs");',
336 'const cp = require("node:child_process");',
337 "const child = cp.spawn(process.execPath, ['-e', process.argv[2]], { detached: true, stdio: 'ignore' });",
338 "fs.writeFileSync(process.argv[1], String(child.pid));",
339 "child.unref();",
340 ].join("\n");
341 const providerProgram = [
342 'const fs = require("node:fs");',
343 'const cp = require("node:child_process");',
344 "fs.writeFileSync(process.argv[1], String(process.pid));",
345 "process.on('SIGTERM', () => {",
346 " const launcher = cp.spawn(process.execPath, ['-e', process.argv[3], process.argv[2], process.argv[4]], { detached: true, stdio: 'ignore' });",
347 " launcher.unref();",
348 " process.exit(0);",
349 "});",
350 "setInterval(() => {}, 1000);",
351 ].join("\n");
352 const wrapped = wrapCommandForLinuxCgroup(lease, process.execPath, [
353 "-e",
354 providerProgram,
355 readyPath,
356 childPath,
357 launcherProgram,
358 childProgram,
359 ]);
360 const provider = NodeChildProcess.spawn(wrapped.command, wrapped.args, {
361 detached: true,
362 env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", T3_ACP_CGROUP_WRAPPER: "1" },
363 stdio: "ignore",
364 });
365 provider.unref();
366 const sentinel = NodeChildProcess.spawn(process.execPath, ["-e", childProgram], {
367 detached: true,
368 stdio: "ignore",
369 });
370 sentinel.unref();
371 let detachedChildPid: number | undefined;
372 try {
373 yield* Effect.gen(function* () {
374 while (!NodeFS.existsSync(readyPath)) yield* Effect.sleep("10 millis");
375 }).pipe(Effect.timeout("2 seconds"));
376 process.kill(provider.pid!, "SIGTERM");
377 detachedChildPid = yield* Effect.gen(function* () {
378 while (true) {
379 try {
380 const pid = Number(NodeFS.readFileSync(childPath, "utf8"));
381 if (Number.isSafeInteger(pid) && pid > 1) return pid;
382 } catch {
383 // The TERM-time launcher has not published its child yet.
384 }
385 yield* Effect.sleep("10 millis");
386 }
387 }).pipe(Effect.timeout("2 seconds"));
388 expect(processExists(detachedChildPid)).toBe(true);
389 yield* terminateLinuxCgroupLease(lease);
390 expect(processExists(sentinel.pid!)).toBe(true);
391 yield* Effect.gen(function* () {
392 while (processExists(detachedChildPid!)) yield* Effect.sleep("10 millis");
393 }).pipe(Effect.timeout("2 seconds"));
394 expect(NodeFS.existsSync(lease.path)).toBe(false);
395​
396 const replacement = controller.create();
397 expect(replacement?.path).not.toBe(lease.path);
398 if (replacement !== undefined) {
399 NodeFS.mkdirSync(NodePath.join(replacement.path, "nested"));
400 yield* terminateLinuxCgroupLease(replacement);
401 expect(NodeFS.existsSync(replacement.path)).toBe(false);
402 }
403 } finally {
404 yield* terminateLinuxCgroupLease(lease).pipe(Effect.ignore);
405 try {
406 process.kill(-provider.pid!, "SIGKILL");
407 } catch {
408 // The contained provider already exited.
409 }
410 try {
411 process.kill(-sentinel.pid!, "SIGKILL");
412 } catch {
413 // The unrelated sentinel already exited.
414 }
415 if (detachedChildPid !== undefined && processExists(detachedChildPid)) {
416 try {
417 process.kill(detachedChildPid, "SIGKILL");
418 } catch {
419 // The detached child already exited.
420 }
421 }
422 NodeFS.rmSync(scratch, { recursive: true, force: true });
423 }
424 }),
425 );
426​
427 it.live("re-kills repopulated cgroups and verifies root removal after retryable errors", () =>
428 Effect.gen(function* () {
429 let exists = true;
430 let killCalls = 0;
431 let populated = false;
432 let removeCalls = 0;
433 const lease: AcpLinuxCgroupLease = {
434 contains: () => false,
435 exists: () => exists,
436 path: "/test/t3-acp-repopulation",
437 relativePath: "/test/t3-acp-repopulation",
438 kill: () => {
439 killCalls += 1;
440 populated = false;
441 },
442 populated: () => populated,
443 remove: () => {
444 removeCalls += 1;
445 if (removeCalls === 1) {
446 populated = true;
447 const error = new Error("repopulated") as NodeJS.ErrnoException;
448 error.code = "EBUSY";
449 throw error;
450 }
451 if (removeCalls === 2) {
452 const error = new Error("nested path vanished") as NodeJS.ErrnoException;
453 error.code = "ENOENT";
454 throw error;
455 }
456 exists = false;
457 },
458 };
459​
460 yield* terminateLinuxCgroupLease(lease);
461 expect(killCalls).toBeGreaterThanOrEqual(3);
462 expect(removeCalls).toBe(3);
463 expect(exists).toBe(false);
464 yield* terminateLinuxCgroupLease(lease);
465 expect(removeCalls).toBe(3);
466 }),
467 );
468​
469 it.live("reports persistent retryable removal failures as removal failures", () =>
470 Effect.gen(function* () {
471 const removeError = Object.assign(new Error("cgroup remains busy"), {
472 code: "EBUSY",
473 });
474 const lease: AcpLinuxCgroupLease = {
475 contains: () => false,
476 exists: () => true,
477 path: "/test/t3-acp-busy",
478 relativePath: "/test/t3-acp-busy",
479 kill: () => undefined,
480 populated: () => false,
481 remove: () => {
482 throw removeError;
483 },
484 };
485​
486 const error = yield* Effect.flip(terminateLinuxCgroupLease(lease));
487 expect(error.detail).toBe("Failed to remove ACP cgroup /test/t3-acp-busy");
488 expect(error.cause).toBe(removeError);
489 }),
490 );
491​
492 it("sends TERM only to the exact captured root while it remains in the child cgroup", () => {
493 const fixture = makeController({
494 processes: [server(), identity(100, process.pid, 100, 100, "owned")],
495 });
496 const ownedRoot: AcpOwnedPosixProcess = {
497 ...identity(100, process.pid, 100, 100, "owned"),
498 parentExecutable: server().executable,
499 parentStartTime: server().startTime,
500 };
501 const root: AcpPosixOwnershipRoot = { captureAttempted: true, value: ownedRoot };
502 const lease: AcpLinuxCgroupLease = {
503 contains: () => true,
504 exists: () => true,
505 path: "/test/t3-acp-root",
506 relativePath: "/test/t3-acp-root",
507 kill: () => undefined,
508 populated: () => true,
509 remove: () => undefined,
510 };
511 signalLinuxCgroupRootTerm({ controller: fixture.controller, lease, root });
512 expect(fixture.signals).toEqual(["process:100:SIGTERM"]);
513​
514 const reused = makeController({
515 processes: [server(), identity(100, process.pid, 100, 100, "reused")],
516 });
517 signalLinuxCgroupRootTerm({ controller: reused.controller, lease, root });
518 expect(reused.signals).toEqual([]);
519​
520 const migrated = makeController({
521 processes: [server(), identity(100, process.pid, 100, 100, "owned")],
522 });
523 signalLinuxCgroupRootTerm({
524 controller: migrated.controller,
525 lease: { ...lease, contains: () => false },
526 root,
527 });
528 expect(migrated.signals).toEqual([]);
529 });
530​
531 it.live("finds a child forked by a non-leader pthread", () =>
532 Effect.gen(function* () {
533 if ((yield* HostProcessPlatform) !== "linux") return;
534 const scratchRoot = NodePath.join(process.cwd(), "tmp");
535 NodeFS.mkdirSync(scratchRoot, { recursive: true });
536 const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-pthread-spawn-"));
537 const binary = NodePath.join(scratch, "helper");
538 const pidPath = NodePath.join(scratch, "pids");
539 expect(NodeFS.statSync(threadSpawnHelperSource).isFile()).toBe(true);
540 const compile = NodeChildProcess.spawnSync(
541 "cc",
542 ["-pthread", threadSpawnHelperSource, "-o", binary],
543 {
544 encoding: "utf8",
545 },
546 );
547 if ((compile.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") {
548 NodeFS.rmSync(scratch, { recursive: true, force: true });
549 return;
550 }
551 expect(compile.status, compile.stderr).toBe(0);
552 const helper = NodeChildProcess.spawn(binary, [pidPath], { detached: true, stdio: "ignore" });
553 helper.unref();
554 try {
555 const published = yield* Effect.gen(function* () {
556 while (true) {
557 try {
558 const ids = NodeFS.readFileSync(pidPath, "utf8").trim().split(/\s+/).map(Number);
559 if (ids.length === 2 && ids.every(Number.isSafeInteger)) return ids;
560 } catch {
561 // The worker has not published its TID and child yet.
562 }
563 yield* Effect.sleep("10 millis");
564 }
565 }).pipe(Effect.timeout("2 seconds"));
566 const [workerTid, childPid] = published;
567 expect(workerTid).not.toBe(helper.pid);
568 expect(makePosixProcessTreeController("linux").childrenOf(helper.pid!)).toContainEqual(
569 expect.objectContaining({ pid: childPid, ppid: helper.pid }),
570 );
571 } finally {
572 try {
573 process.kill(-helper.pid!, "SIGKILL");
574 } catch {
575 // The isolated fixture already exited.
576 }
577 NodeFS.rmSync(scratch, { recursive: true, force: true });
578 }
579 }),
580 );
581​
582 it.live("keeps ownership across a fork-before-exec executable transition", () =>
583 Effect.gen(function* () {
584 const beforeExec = { ...identity(110, 100, 110, 110), executable: "/provider/fork" };
585 const fixture = makeController({
586 processes: [server(), identity(100, process.pid, 100, 100), beforeExec],
587 });
588 const frontier = new Map<number, AcpOwnedPosixProcess>();
589 const childQueues = new Map<number, Array<number>>();
590 const ledger = new Map<string, AcpOwnedPosixProcess>();
591 const root: AcpPosixOwnershipRoot = { value: undefined };
592 observePosixOwnershipLedger({
593 childQueues,
594 controller: fixture.controller,
595 frontier,
596 ledger,
597 root,
598 rootPid: 100,
599 });
600 fixture.processes.set(110, { ...beforeExec, executable: "/usr/bin/bash" });
601 observePosixOwnershipLedger({
602 childQueues,
603 controller: fixture.controller,
604 frontier,
605 ledger,
606 root,
607 rootPid: 100,
608 });
609​
610 expect([...ledger.values()].find((process) => process.pid === 110)?.executable).toBe(
611 "/usr/bin/bash",
612 );
613 yield* terminatePosixOwnedProcessTree({
614 controller: fixture.controller,
615 grace: 0,
616 ledger,
617 rootPid: 100,
618 });
619 expect(fixture.signals).toContain("process:110:SIGTERM");
620 expect(fixture.processes.has(110)).toBe(false);
621 }),
622 );
623​
624 it("never adopts a replacement PID after initial root capture failed", () => {
625 const fixture = makeController({ processes: [server()] });
626 const frontier = new Map<number, AcpOwnedPosixProcess>();
627 const childQueues = new Map<number, Array<number>>();
628 const ledger = new Map<string, AcpOwnedPosixProcess>();
629 const root: AcpPosixOwnershipRoot = { value: undefined };
630 const capture = () => {
631 try {
632 observePosixOwnershipLedger({
633 childQueues,
634 controller: fixture.controller,
635 frontier,
636 ledger,
637 root,
638 rootPid: 100,
639 });
640 return undefined;
641 } catch (error) {
642 return error;
643 }
644 };
645 expect(capture()).toMatchObject({
646 detail: "ACP process 100 exited before its ownership ledger was captured",
647 });
648 fixture.processes.set(100, identity(100, process.pid, 100, 100, "reused"));
649 expect(capture()).toMatchObject({
650 detail: "ACP process 100 exited before its ownership ledger was captured",
651 });
652 expect(ledger.size).toBe(0);
653 });
654​
655 it.live("rotates more than 64 live parents without scanning retained tombstones", () =>
656 Effect.gen(function* () {
657 const parents = Array.from({ length: 130 }, (_, index) =>
658 identity(1_000 + index, 100, 1_000 + index, 1_000 + index),
659 );
660 let childListReads = 0;
661 let identityCalls = 0;
662 let snapshotCalls = 0;
663 const fixture = makeController({
664 processes: [server(), identity(100, process.pid, 100, 100)],
665 });
666 const controller: AcpPosixProcessTreeController = {
667 ...fixture.controller,
668 childPidsOf: (pid) => {
669 childListReads += 1;
670 return fixture.controller.childPidsOf(pid);
671 },
672 identity: (pid) => {
673 identityCalls += 1;
674 return fixture.controller.identity(pid);
675 },
676 snapshot: () => {
677 snapshotCalls += 1;
678 return fixture.controller.snapshot();
679 },
680 };
681 const frontier = new Map<number, AcpOwnedPosixProcess>();
682 const childQueues = new Map<number, Array<number>>();
683 const ledger = new Map<string, AcpOwnedPosixProcess>();
684 const root: AcpPosixOwnershipRoot = { value: undefined };
685 for (let index = 0; index < 5_000; index += 1) {
686 const tombstone = identity(100_000 + index, 1, 100_000 + index, 100_000 + index);
687 ledger.set(`${tombstone.pid}:${tombstone.startTime}`, {
688 ...tombstone,
689 parentExecutable: undefined,
690 parentStartTime: "",
691 });
692 }
693 observePosixOwnershipLedger({
694 childQueues,
695 controller,
696 frontier,
697 ledger,
698 root,
699 rootPid: 100,
700 });
701 for (const parent of parents) {
702 fixture.processes.set(parent.pid, parent);
703 fixture.processes.set(
704 parent.pid + 10_000,
705 identity(parent.pid + 10_000, parent.pid, parent.pgid, parent.sid),
706 );
707 }
708 let passes = 0;
709 while (
710 !parents.every((parent) =>
711 [...ledger.values()].some((owned) => owned.pid === parent.pid + 10_000),
712 ) &&
713 passes < 40
714 ) {
715 childListReads = 0;
716 identityCalls = 0;
717 observePosixOwnershipLedger({
718 childQueues,
719 controller,
720 frontier,
721 ledger,
722 maxProcesses: 64,
723 root,
724 rootPid: 100,
725 });
726 expect(identityCalls + childListReads).toBeLessThanOrEqual(64);
727 passes += 1;
728 }
729​
730 const missing = parents.filter(
731 (parent) => ![...ledger.values()].some((owned) => owned.pid === parent.pid + 10_000),
732 );
733 expect(missing, `missing after ${passes} passes`).toEqual([]);
734 expect(passes).toBeGreaterThan(2);
735 yield* terminatePosixOwnedProcessTree({
736 controller,
737 grace: 0,
738 ledger,
739 rootPid: 100,
740 });
741 expect(snapshotCalls).toBe(10);
742 expect(fixture.processes.size).toBe(1);
743 }),
744 );
745​
746 it.live("polls only known descendants and stops with its scope", () =>
747 Effect.gen(function* () {
748 let childrenCalls = 0;
749 let identityCalls = 0;
750 let snapshotCalls = 0;
751 const fixture = makeController({
752 processes: [server(), identity(100, process.pid, 100, 100), identity(110, 100, 110, 110)],
753 });
754 const controller: AcpPosixProcessTreeController = {
755 ...fixture.controller,
756 childPidsOf: (pid) => {
757 childrenCalls += 1;
758 return fixture.controller.childPidsOf(pid);
759 },
760 identity: (pid) => {
761 identityCalls += 1;
762 return fixture.controller.identity(pid);
763 },
764 snapshot: () => {
765 snapshotCalls += 1;
766 return fixture.controller.snapshot();
767 },
768 };
769 const scope = yield* Scope.make();
770 const frontier = new Map<number, AcpOwnedPosixProcess>();
771 const childQueues = new Map<number, Array<number>>();
772 let ledgerValuesCalls = 0;
773 const ledger = new (class extends Map<string, AcpOwnedPosixProcess> {
774 override values(): MapIterator<AcpOwnedPosixProcess> {
775 ledgerValuesCalls += 1;
776 return super.values();
777 }
778 })();
779 const root: AcpPosixOwnershipRoot = { value: undefined };
780 for (let index = 0; index < 5_000; index += 1) {
781 const tombstone = identity(10_000 + index, 1, 10_000 + index, 10_000 + index);
782 ledger.set(`${tombstone.pid}:${tombstone.startTime}`, {
783 ...tombstone,
784 parentExecutable: undefined,
785 parentStartTime: "",
786 });
787 }
788 yield* observePosixOwnershipLedgerContinuously({
789 childQueues,
790 controller,
791 frontier,
792 ledger,
793 root,
794 rootPid: 100,
795 }).pipe(Effect.forkIn(scope));
796 const timerStartedAt = yield* Clock.currentTimeMillis;
797 yield* Effect.sleep(0);
798 const timerDelay = (yield* Clock.currentTimeMillis) - timerStartedAt;
799 yield* Effect.sleep("80 millis");
800​
801 expect(timerDelay).toBeLessThan(250);
802 expect(ledgerValuesCalls).toBe(0);
803 expect(snapshotCalls).toBe(0);
804 expect(childrenCalls).toBeGreaterThan(0);
805 expect(childrenCalls).toBeLessThanOrEqual(12);
806 const callsAtClose = identityCalls + childrenCalls;
807 yield* Scope.close(scope, Exit.void);
808 yield* Effect.sleep("60 millis");
809 expect(identityCalls + childrenCalls).toBe(callsAtClose);
810 }),
811 );
812​
813 it.live("terminates nested owned groups bottom-up and catches a TERM fork race", () =>
814 Effect.gen(function* () {
815 let forked = false;
816 const fixture = makeController({
817 processes: [
818 server(),
819 identity(100, process.pid, 100, 100),
820 identity(110, 100, 110, 110),
821 identity(115, 110, 115, 110),
822 identity(120, 110, 120, 120),
823 identity(121, 120, 120, 120),
824 ],
825 onProcess: (processes, pid, signal) => {
826 if (signal === "SIGTERM" && pid === 121 && !forked) {
827 forked = true;
828 processes.set(122, identity(122, 110, 122, 122));
829 }
830 processes.delete(pid);
831 },
832 });
833​
834 yield* terminatePosixOwnedProcessTree({
835 controller: fixture.controller,
836 grace: 0,
837 rootPid: 100,
838 });
839​
840 expect(fixture.processes.has(100)).toBe(false);
841 expect(fixture.processes.has(122)).toBe(false);
842 expect(fixture.signals.indexOf("process:121:SIGTERM")).toBeLessThan(
843 fixture.signals.indexOf("process:120:SIGTERM"),
844 );
845 expect(fixture.signals.indexOf("process:115:SIGTERM")).toBeLessThan(
846 fixture.signals.indexOf("process:110:SIGTERM"),
847 );
848 }),
849 );
850​
851 it.live("falls back to exact PIDs for unknown group members and a missing leader", () =>
852 Effect.gen(function* () {
853 const unrelated = identity(999, 1, 110, 110, "unrelated");
854 const fixture = makeController({
855 processes: [
856 server(),
857 identity(100, process.pid, 100, 100),
858 identity(110, 100, 110, 110),
859 identity(111, 110, 110, 110),
860 unrelated,
861 ],
862 onProcess: (processes, pid) => {
863 processes.delete(pid);
864 if (pid === 111) processes.delete(110);
865 },
866 });
867​
868 yield* terminatePosixOwnedProcessTree({
869 controller: fixture.controller,
870 grace: 0,
871 rootPid: 100,
872 });
873​
874 expect(fixture.signals).toContain("process:111:SIGTERM");
875 expect(fixture.processes.get(999)).toEqual(unrelated);
876 }),
877 );
878​
879 it.live("re-admits a still-owned child after PID reuse and never signals the T3 session", () =>
880 Effect.gen(function* () {
881 const reused = identity(110, 100, 110, 110, "reused");
882 const fixture = makeController({
883 processes: [
884 server(),
885 identity(100, process.pid, 100, 100),
886 identity(110, 100, 110, 110, "owned"),
887 identity(120, 100, 120, process.pid),
888 ],
889 onProcess: (processes, pid) => {
890 if (pid === 110) processes.set(110, reused);
891 else processes.delete(pid);
892 },
893 });
894​
895 const result = yield* Effect.exit(
896 terminatePosixOwnedProcessTree({
897 controller: fixture.controller,
898 grace: 0,
899 rootPid: 100,
900 }),
901 );
902​
903 // PID 110 morphs to a new identity under the owned root and never exits, so
904 // teardown fails closed after re-admitting and re-signalling the live child.
905 expect(Exit.isFailure(result)).toBe(true);
906 expect(fixture.processes.get(110)).toEqual(reused);
907 expect(
908 fixture.signals.filter((entry) => entry.startsWith("process:110:")).length,
909 ).toBeGreaterThan(0);
910 expect(fixture.signals.some((entry) => entry.includes(":120:"))).toBe(false);
911 }),
912 );
913​
914 it.live("does not treat zombie residual entries as teardown survivors", () =>
915 Effect.gen(function* () {
916 expect(posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "Z" })).toBe(true);
917 expect(posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "S" })).toBe(false);
918 const withoutState: AcpPosixProcessIdentity = {
919 executable: "/proc/1/exe",
920 pgid: 1,
921 pid: 1,
922 ppid: 0,
923 sid: 1,
924 startTime: "1",
925 };
926 expect(posixProcessIsZombie(withoutState)).toBe(false);
927​
928 const root = identity(100, process.pid, 100, 100);
929 const zombieChild = identity(110, 100, 110, 110, "110", "Z");
930 const fixture = makeController({
931 processes: [server(), root, zombieChild],
932 onProcess: (processes, pid) => {
933 // Kill leaves a zombie with the same pid/starttime until reaped.
934 const current = processes.get(pid);
935 if (current === undefined) return;
936 processes.set(pid, { ...current, state: "Z" });
937 },
938 });
939 yield* terminatePosixOwnedProcessTree({
940 controller: fixture.controller,
941 grace: 0,
942 rootPid: 100,
943 });
944 // Zombies remain visible but must not fail residual teardown.
945 expect(fixture.processes.get(100)?.state).toBe("Z");
946 expect(fixture.processes.get(110)?.state).toBe("Z");
947 }),
948 );
949​
950 it("admits a live child after a free PID was previously reserved by a dead entry", () => {
951 const staleChild: AcpOwnedPosixProcess = {
952 ...identity(200, 100, 200, 200, "stale-child"),
953 parentExecutable: `/proc/100/exe`,
954 parentStartTime: "100",
955 };
956 const liveChild = identity(200, 100, 200, 200, "live-child");
957 const root = identity(100, process.pid, 100, 100);
958 const ownedRoot: AcpOwnedPosixProcess = {
959 ...root,
960 parentExecutable: `/proc/${process.pid}/exe`,
961 parentStartTime: "server",
962 };
963 const ledger = new Map<string, AcpOwnedPosixProcess>([
964 [`100:${root.startTime}`, ownedRoot],
965 [`200:${staleChild.startTime}`, staleChild],
966 ]);
967 const controller = makeController({
968 processes: [server(), root],
969 }).controller;
970​
971 // First capture: PID 200 is free, so the dead reservation is dropped.
972 capturePosixOwnershipLedger({
973 controller,
974 ledger,
975 rootPid: 100,
976 table: [root],
977 });
978 expect([...ledger.values()].some((entry) => entry.pid === 200)).toBe(false);
979​
980 // Second capture: a new process reuses PID 200 under the owned parent.
981 capturePosixOwnershipLedger({
982 controller: makeController({ processes: [server(), root, liveChild] }).controller,
983 ledger,
984 rootPid: 100,
985 table: [root, liveChild],
986 });
987​
988 const admitted = [...ledger.values()].find((entry) => entry.pid === 200);
989 expect(admitted?.startTime).toBe("live-child");
990 });
991​
992 it("admits a live child when a stale ledger entry still occupies the reused PID", () => {
993 const staleChild: AcpOwnedPosixProcess = {
994 ...identity(200, 100, 200, 200, "stale-child"),
995 parentExecutable: `/proc/100/exe`,
996 parentStartTime: "100",
997 };
998 const liveChild = identity(200, 100, 200, 200, "live-child");
999 const root = identity(100, process.pid, 100, 100);
1000 const ownedRoot: AcpOwnedPosixProcess = {
1001 ...root,
1002 parentExecutable: `/proc/${process.pid}/exe`,
1003 parentStartTime: "server",
1004 };
1005 const ledger = new Map<string, AcpOwnedPosixProcess>([
1006 [`100:${root.startTime}`, ownedRoot],
1007 [`200:${staleChild.startTime}`, staleChild],
1008 ]);
1009​
1010 capturePosixOwnershipLedger({
1011 controller: makeController({ processes: [server(), root, liveChild] }).controller,
1012 ledger,
1013 rootPid: 100,
1014 table: [root, liveChild],
1015 });
1016​
1017 expect([...ledger.values()].some((entry) => entry.startTime === "stale-child")).toBe(false);
1018 const admitted = [...ledger.values()].find((entry) => entry.pid === 200);
1019 expect(admitted?.startTime).toBe("live-child");
1020 });
1021​
1022 it.live("signals children forked under a still-live parent during the same pass", () =>
1023 Effect.gen(function* () {
1024 let forked = false;
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, 111, 111),
1031 ],
1032 onProcess: (processes, pid) => {
1033 // Bottom-up: signal 111 first while 110 is still live, then fork 112
1034 // under 110 so the same pass must enqueue and signal 112.
1035 if (pid === 111 && !forked) {
1036 forked = true;
1037 processes.set(112, identity(112, 110, 112, 112));
1039 processes.delete(pid);
1040 },
1041 });
1042​
1043 yield* terminatePosixOwnedProcessTree({
1044 controller: fixture.controller,
1045 grace: 0,
1046 rootPid: 100,
1047 });
1048​
1049 expect(forked).toBe(true);
1050 expect(fixture.processes.has(112)).toBe(false);
1051 expect(fixture.signals.some((entry) => entry.startsWith("process:112:"))).toBe(true);
1052 }),
1053 );
1054​
1055 it.live("detects an owned child first observed in the final survivor snapshot", () =>
1056 Effect.gen(function* () {
1057 const lateChild = identity(111, 110, 111, 111);
1058 const fixture = makeController({
1059 processes: [server(), identity(100, process.pid, 100, 100), identity(110, 100, 110, 110)],
1060 onProcess: (processes, pid) => {
1061 // Leave the descendant parent alive through teardown so it can fork
1062 // immediately after the last signal pass.
1063 if (pid !== 110) processes.delete(pid);
1064 },
1065 });
1066 let snapshotCalls = 0;
1067 const controller: AcpPosixProcessTreeController = {
1068 ...fixture.controller,
1069 snapshot: () => {
1070 snapshotCalls += 1;
1071 // Two TERM discovery passes, the root TERM pass, and two KILL passes
1072 // precede the final survivor snapshot.
1073 if (snapshotCalls === 6) fixture.processes.set(lateChild.pid, lateChild);
1074 return fixture.controller.snapshot();
1075 },
1076 };
1077​
1078 const error = yield* Effect.flip(
1079 terminatePosixOwnedProcessTree({
1080 controller,
1081 discoveryPasses: 2,
1082 grace: 0,
1083 rootPid: 100,
1084 }),
1085 );
1086​
1087 expect(snapshotCalls).toBe(6);
1088 expect(error.detail).toContain("110, 111");
1089 }),
1090 );
1091​
1092 it.live("retains the ledger across root exit and an explicit failure for finalizer retry", () =>
1093 Effect.gen(function* () {
1094 let ignoreSignals = true;
1095 const ledger = new Map<string, AcpOwnedPosixProcess>();
1096 const frontier = new Map<number, AcpOwnedPosixProcess>();
1097 const childQueues = new Map<number, Array<number>>();
1098 const root: AcpPosixOwnershipRoot = { value: undefined };
1099 const fixture = makeController({
1100 processes: [
1101 server(),
1102 identity(100, process.pid, 100, 100),
1103 identity(110, 100, 110, 110),
1104 identity(111, 110, 110, 110),
1105 ],
1106 onProcess: (processes, pid) => {
1107 if (ignoreSignals && pid === 100) processes.delete(100);
1108 if (!ignoreSignals) processes.delete(pid);
1109 },
1110 });
1111 observePosixOwnershipLedger({
1112 childQueues,
1113 controller: fixture.controller,
1114 frontier,
1115 ledger,
1116 root,
1117 rootPid: 100,
1118 });
1119​
1120 const explicit = yield* Effect.exit(
1121 terminatePosixOwnedProcessTree({
1122 controller: fixture.controller,
1123 grace: 0,
1124 ledger,
1125 rootPid: 100,
1126 }),
1127 );
1128 expect(Exit.isFailure(explicit)).toBe(true);
1129 expect(fixture.processes.has(100)).toBe(false);
1130 expect(fixture.processes.has(111)).toBe(true);
1131​
1132 fixture.processes.set(112, identity(112, 110, 112, 112));
1133 observePosixOwnershipLedger({
1134 childQueues,
1135 controller: fixture.controller,
1136 frontier,
1137 ledger,
1138 root,
1139 rootPid: 100,
1140 });
1141 ignoreSignals = false;
1142 yield* terminatePosixOwnedProcessTree({
1143 controller: fixture.controller,
1144 grace: 0,
1145 ledger,
1146 rootPid: 100,
1147 });
1148 expect(fixture.processes.has(110)).toBe(false);
1149 expect(fixture.processes.has(111)).toBe(false);
1150 expect(fixture.processes.has(112)).toBe(false);
1151 }),
1152 );
1153​
1154 it("fails closed where a stable POSIX identity provider is unavailable", () => {
1155 try {
1156 makePosixProcessTreeController("darwin");
1157 throw new Error("Expected Darwin process ownership to fail closed");
1158 } catch (error) {
1159 expect(error).toMatchObject({
1160 detail: "Detached ACP descendant ownership is unsupported on darwin",
1161 });
1163 });
1164});