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