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

AcpSessionRuntime.processTree.test.ts

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