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

AcpSessionRuntime.processTree.test.ts

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