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";
5
6import { describe, expect, it, vi } from "@effect/vitest";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10
11import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
12
13const identity = (
14 pid: number,
15 ppid: number,
16 pgid: number,
17 sid: number,
18 startTime = String(pid),
19 state = "S",
20): AcpSessionRuntime.AcpPosixProcessIdentity => ({
21 executable: `/proc/${pid}/exe`,
22 pgid,
23 pid,
24 ppid,
25 sid,
26 startTime,
27 state,
28});
29
30function makeController(input: {
31 readonly processes: ReadonlyArray<AcpSessionRuntime.AcpPosixProcessIdentity>;
32 readonly onProcess?: (
33 processes: Map<number, AcpSessionRuntime.AcpPosixProcessIdentity>,
34 pid: number,
35 signal: NodeJS.Signals,
36 ) => void;
37}) {
38 const processes = new Map(input.processes.map((process) => [process.pid, process]));
39 const signals: Array<string> = [];
40 const controller: AcpSessionRuntime.AcpPosixProcessTreeController = {
41 childPidsOf: (pid) =>
42 [...processes.values()]
43 .filter((process) => process.ppid === pid)
44 .map((process) => process.pid),
45 childrenOf: (pid) => [...processes.values()].filter((process) => process.ppid === pid),
46 identity: (pid) => processes.get(pid),
47 snapshot: () => [...processes.values()],
48 signalProcess: (pid, signal) => {
49 signals.push(`process:${pid}:${signal}`);
50 if (input.onProcess) return input.onProcess(processes, pid, signal);
51 processes.delete(pid);
52 },
53 };
54 return { controller, processes, signals };
55}
56
57const server = () => identity(process.pid, 1, process.pid, process.pid, "server");
58
59describe("terminatePosixOwnedProcessTree", () => {
60 it("parses unified cgroup paths and escaped cgroup2 mountinfo", () => {
61 expect(AcpSessionRuntime.parseUnifiedCgroupPath("0::/user.slice/app.scope\n")).toBe(
62 "/user.slice/app.scope",
63 );
64 expect(AcpSessionRuntime.parseUnifiedCgroupPath("0::/one\n0::/two\n")).toBeUndefined();
65 expect(AcpSessionRuntime.isSafeCgroupPath("/user.slice/app.scope")).toBe(true);
66 expect(AcpSessionRuntime.isSafeCgroupPath("/user.slice/../escape")).toBe(false);
67 expect(AcpSessionRuntime.isSafeCgroupPath("/user.slice/app.scope (deleted)")).toBe(false);
68 expect(
69 AcpSessionRuntime.parseCgroup2Mount(
70 "42 31 0:37 /user.slice /sys/fs/cgroup/user\\040mount rw - cgroup2 cgroup2 rw\n",
71 ),
72 ).toEqual({ mountPoint: "/sys/fs/cgroup/user mount", root: "/user.slice" });
73 expect(
74 AcpSessionRuntime.parseCgroup2Mount("42 31 0:37 / /sys/fs/cgroup rw - tmpfs tmpfs rw\n"),
75 ).toBeUndefined();
76 expect(
77 AcpSessionRuntime.parseCgroup2Mounts(
78 "41 31 0:36 /other /sys/fs/cgroup/other rw - cgroup2 cgroup2 rw\n" +
79 "42 31 0:37 /user.slice /sys/fs/cgroup/user rw - cgroup2 cgroup2 rw\n",
80 ),
81 ).toHaveLength(2);
82 });
83
84 it.live("sweeps empty t3-acp sibling leases owned by dead pids only", () =>
85 Effect.sync(() => {
86 const scratchRoot = NodePath.join(process.cwd(), "tmp");
87 NodeFS.mkdirSync(scratchRoot, { recursive: true });
88 const parent = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-stale-siblings-"));
89 // Temp dirs are not cgroupfs: rmdir fails when control files exist, so the
90 // test injects populated/remove while still exercising the real selection
91 // and path-safety logic against a real parent directory tree.
92 const populatedByPath = new Map<string, "0" | "1">();
93 const writeSibling = (name: string, populated: "0" | "1" | null) => {
94 const path = NodePath.join(parent, name);
95 NodeFS.mkdirSync(path);
96 if (populated !== null) populatedByPath.set(path, populated);
97 return path;
98 };
99 const deadPid = 2_147_483_646;
100 const liveForeignPid = 2_147_483_645;
101 const staleEmpty = writeSibling(`t3-acp-${deadPid}-aaaa`, "0");
102 const currentPidSibling = writeSibling(`t3-acp-${process.pid}-bbbb`, "0");
103 const liveForeignSibling = writeSibling(`t3-acp-${liveForeignPid}-cccc`, "0");
104 const stalePopulated = writeSibling(`t3-acp-${deadPid}-dddd`, "1");
105 const unrelated = writeSibling("other-lease", "0");
106 const isProcessAlive = (pid: number) => pid === process.pid || pid === liveForeignPid;
107 try {
108 AcpSessionRuntime.sweepStaleLinuxCgroupSiblings(parent, {
109 isProcessAlive,
110 readPopulated: (path) => populatedByPath.get(path),
111 remove: (path) => {
112 populatedByPath.delete(path);
113 NodeFS.rmdirSync(path);
114 },
115 });
116 expect(NodeFS.existsSync(staleEmpty)).toBe(false);
117 expect(NodeFS.existsSync(currentPidSibling)).toBe(true);
118 expect(NodeFS.existsSync(liveForeignSibling)).toBe(true);
119 expect(NodeFS.existsSync(stalePopulated)).toBe(true);
120 expect(NodeFS.existsSync(unrelated)).toBe(true);
121 writeSibling(`t3-acp-${deadPid}-eeee`, null);
122 AcpSessionRuntime.sweepStaleLinuxCgroupSiblings(parent, {
123 isProcessAlive,
124 readPopulated: (path) => populatedByPath.get(path),
125 remove: (path) => {
126 populatedByPath.delete(path);
127 NodeFS.rmdirSync(path);
128 },
129 });
130 expect(NodeFS.existsSync(NodePath.join(parent, `t3-acp-${deadPid}-eeee`))).toBe(true);
131 expect(NodeFS.existsSync(currentPidSibling)).toBe(true);
132 } finally {
133 NodeFS.rmSync(parent, { recursive: true, force: true });
134 }
135 }),
136 );
137
138 it.live("preserves exact argv and strips wrapper-only environment before exec", () =>
139 Effect.gen(function* () {
140 if ((yield* HostProcess.Platform) !== "linux") return;
141 const lease = AcpSessionRuntime.makeLinuxCgroupController().create();
142 if (lease === undefined) return;
143 const scratchRoot = NodePath.join(process.cwd(), "tmp");
144 NodeFS.mkdirSync(scratchRoot, { recursive: true });
145 const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-wrapper-"));
146 const linkedNode = NodePath.join(scratch, "T3 Code AppImage 'quoted'");
147 const bareGrok = NodePath.join(scratch, "grok");
148 const relativeBin = NodePath.join(scratch, "relative-bin");
149 const directoryBin = NodePath.join(scratch, "directory-bin");
150 const validBin = NodePath.join(scratch, "valid-bin");
151 const outputPath = NodePath.join(scratch, "argv.json");
152 NodeFS.mkdirSync(relativeBin);
153 NodeFS.mkdirSync(NodePath.join(directoryBin, "grok"), { recursive: true });
154 NodeFS.mkdirSync(validBin);
155 NodeFS.symlinkSync(process.execPath, linkedNode);
156 NodeFS.symlinkSync(process.execPath, bareGrok);
157 NodeFS.symlinkSync(process.execPath, NodePath.join(relativeBin, "grok"));
158 NodeFS.symlinkSync(process.execPath, NodePath.join(validBin, "grok"));
159 expect(
160 AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: scratch }),
161 ).toBe(bareGrok);
162 expect(AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: "" })).toBe(
163 bareGrok,
164 );
165 // Undefined PATH uses Node's default search path (/usr/bin:/bin), not cwd alone
166 // (bareGrok lives only in cwd / PATH=scratch).
167 expect(
168 AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: undefined }),
169 ).toBeUndefined();
170 expect(
171 AcpSessionRuntime.resolveLinuxCgroupTargetCommand("node", scratch, { PATH: undefined }),
172 ).toBeDefined();
173 expect(
174 AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, {
175 PATH: "relative-bin",
176 }),
177 ).toBe(NodePath.join(relativeBin, "grok"));
178 expect(
179 AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, {
180 PATH: `directory-bin${NodePath.delimiter}valid-bin`,
181 }),
182 ).toBe(NodePath.join(validBin, "grok"));
183 const target = [
184 'const fs = require("node:fs");',
185 "fs.writeFileSync(process.argv[1], JSON.stringify({",
186 " args: process.argv.slice(2),",
187 " electron: process.env.ELECTRON_RUN_AS_NODE,",
188 " wrapper: process.env.T3_ACP_CGROUP_WRAPPER,",
189 "}));",
190 ].join("\n");
191 const wrapped = AcpSessionRuntime.wrapCommandForLinuxCgroup(lease, linkedNode, [
192 "-e",
193 target,
194 outputPath,
195 "space value",
196 "single'quote",
197 'double"quote',
198 ]);
199 try {
200 const result = NodeChildProcess.spawnSync(wrapped.command, wrapped.args, {
201 encoding: "utf8",
202 env: {
203 ...process.env,
204 ELECTRON_RUN_AS_NODE: "1",
205 T3_ACP_CGROUP_WRAPPER: "1",
206 },
207 });
208 expect(result.status, result.stderr).toBe(0);
209 expect(NodeFS.readFileSync(outputPath, "utf8")).toBe(
210 '{"args":["space value","single\'quote","double\\"quote"]}',
211 );
212 } finally {
213 yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease).pipe(Effect.ignore);
214 NodeFS.rmSync(scratch, { recursive: true, force: true });
215 }
216 }),
217 );
218
219 it("contains a packaged-runtime command without requiring cgroup delegation", () => {
220 if (HostProcess.Platform.defaultValue() !== "linux") return;
221 const scratchRoot = NodePath.join(process.cwd(), "tmp");
222 NodeFS.mkdirSync(scratchRoot, { recursive: true });
223 const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-wrapper-fake-"));
224 const leasePath = NodePath.join(scratch, "lease with spaces");
225 const outputPath = NodePath.join(scratch, "argv output");
226 NodeFS.mkdirSync(leasePath);
227 NodeFS.writeFileSync(NodePath.join(leasePath, "cgroup.procs"), "");
228 const relativePath = AcpSessionRuntime.parseUnifiedCgroupPath(
229 NodeFS.readFileSync("/proc/self/cgroup", "utf8"),
230 );
231 expect(relativePath).toBeDefined();
232 const lease: AcpSessionRuntime.AcpLinuxCgroupLease = {
233 contains: () => false,
234 exists: () => true,
235 path: leasePath,
236 relativePath: relativePath!,
237 kill: () => undefined,
238 populated: () => false,
239 remove: () => undefined,
240 };
241 const packagedExecPath = vi.spyOn(process, "execPath", "get").mockReturnValue("/bin/sh");
242 try {
243 const wrapped = AcpSessionRuntime.wrapCommandForLinuxCgroup(lease, "/bin/sh", [
244 "-c",
245 'printf "%s\\n" "$0" "$1" "$2" "$3" "${ELECTRON_RUN_AS_NODE-}" "${T3_ACP_CGROUP_WRAPPER-}" > "$4"',
246 "packaged-target",
247 "space value",
248 "single'quote",
249 'double"quote',
250 outputPath,
251 ]);
252 const result = NodeChildProcess.spawnSync(wrapped.command, wrapped.args, {
253 encoding: "utf8",
254 env: {
255 ...process.env,
256 ELECTRON_RUN_AS_NODE: "1",
257 T3_ACP_CGROUP_WRAPPER: "1",
258 },
259 });
260 expect(result.status, result.stderr).toBe(0);
261 expect(NodeFS.readFileSync(outputPath, "utf8")).toBe(
262 "packaged-target\nspace value\nsingle'quote\ndouble\"quote\n\n\n",
263 );
264 expect(NodeFS.readFileSync(NodePath.join(leasePath, "cgroup.procs"), "utf8")).toMatch(
265 /^\d+\n$/,
266 );
267
268 const mismatch = AcpSessionRuntime.wrapCommandForLinuxCgroup(
269 { ...lease, relativePath: "/not-the-current-cgroup" },
270 "/bin/sh",
271 ["-c", 'printf executed > "$0"', outputPath],
272 );
273 NodeFS.rmSync(outputPath);
274 const mismatchResult = NodeChildProcess.spawnSync(mismatch.command, mismatch.args, {
275 encoding: "utf8",
276 });
277 expect(mismatchResult.status, mismatchResult.stderr).toBe(126);
278 expect(NodeFS.existsSync(outputPath)).toBe(false);
279
280 const missingTarget = AcpSessionRuntime.wrapCommandForLinuxCgroup(
281 lease,
282 "/nonexistent-t3-probe",
283 [],
284 );
285 const missingTargetResult = NodeChildProcess.spawnSync(
286 missingTarget.command,
287 missingTarget.args,
288 {
289 encoding: "utf8",
290 },
291 );
292 expect(missingTargetResult.status, missingTargetResult.stderr).toBe(125);
293 // CI's /bin/sh is dash, which runs the EXIT trap after a failed exec. Bash does not,
294 // so run the same wrapper under bash too.
295 const missingTargetBash = NodeChildProcess.spawnSync("bash", missingTarget.args, {
296 encoding: "utf8",
297 });
298 if ((missingTargetBash.error as NodeJS.ErrnoException | undefined)?.code !== "ENOENT") {
299 expect(missingTargetBash.status, missingTargetBash.stderr).toBe(125);
300 expect(missingTargetBash.stderr).toContain("/nonexistent-t3-probe");
301 }
302 } finally {
303 packagedExecPath.mockRestore();
304 NodeFS.rmSync(scratch, { recursive: true, force: true });
305 }
306 });
307
308 it("sends TERM only to the exact captured root while it remains in the child cgroup", () => {
309 const fixture = makeController({
310 processes: [server(), identity(100, process.pid, 100, 100, "owned")],
311 });
312 const ownedRoot: AcpSessionRuntime.AcpOwnedPosixProcess = {
313 ...identity(100, process.pid, 100, 100, "owned"),
314 parentExecutable: server().executable,
315 parentStartTime: server().startTime,
316 };
317 const root: AcpSessionRuntime.AcpPosixOwnershipRoot = {
318 captureAttempted: true,
319 value: ownedRoot,
320 };
321 const lease: AcpSessionRuntime.AcpLinuxCgroupLease = {
322 contains: () => true,
323 exists: () => true,
324 path: "/test/t3-acp-root",
325 relativePath: "/test/t3-acp-root",
326 kill: () => undefined,
327 populated: () => true,
328 remove: () => undefined,
329 };
330 AcpSessionRuntime.signalLinuxCgroupRootTerm({ controller: fixture.controller, lease, root });
331 expect(fixture.signals).toEqual(["process:100:SIGTERM"]);
332
333 const reused = makeController({
334 processes: [server(), identity(100, process.pid, 100, 100, "reused")],
335 });
336 AcpSessionRuntime.signalLinuxCgroupRootTerm({ controller: reused.controller, lease, root });
337 expect(reused.signals).toEqual([]);
338
339 const migrated = makeController({
340 processes: [server(), identity(100, process.pid, 100, 100, "owned")],
341 });
342 AcpSessionRuntime.signalLinuxCgroupRootTerm({
343 controller: migrated.controller,
344 lease: { ...lease, contains: () => false },
345 root,
346 });
347 expect(migrated.signals).toEqual([]);
348 });
349
350 it.live("keeps ownership across a fork-before-exec executable transition", () =>
351 Effect.gen(function* () {
352 const beforeExec = { ...identity(110, 100, 110, 110), executable: "/provider/fork" };
353 const fixture = makeController({
354 processes: [server(), identity(100, process.pid, 100, 100), beforeExec],
355 });
356 const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
357 const childQueues = new Map<number, Array<number>>();
358 const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>();
359 const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
360 AcpSessionRuntime.observePosixOwnershipLedger({
361 childQueues,
362 controller: fixture.controller,
363 frontier,
364 ledger,
365 root,
366 rootPid: 100,
367 });
368 fixture.processes.set(110, { ...beforeExec, executable: "/usr/bin/bash" });
369 AcpSessionRuntime.observePosixOwnershipLedger({
370 childQueues,
371 controller: fixture.controller,
372 frontier,
373 ledger,
374 root,
375 rootPid: 100,
376 });
377
378 expect([...ledger.values()].find((process) => process.pid === 110)?.executable).toBe(
379 "/usr/bin/bash",
380 );
381 yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
382 controller: fixture.controller,
383 grace: 0,
384 ledger,
385 rootPid: 100,
386 });
387 expect(fixture.signals).toContain("process:110:SIGTERM");
388 expect(fixture.processes.has(110)).toBe(false);
389 }),
390 );
391
392 it("never adopts a replacement PID after initial root capture failed", () => {
393 const fixture = makeController({ processes: [server()] });
394 const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
395 const childQueues = new Map<number, Array<number>>();
396 const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>();
397 const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
398 const capture = () => {
399 try {
400 AcpSessionRuntime.observePosixOwnershipLedger({
401 childQueues,
402 controller: fixture.controller,
403 frontier,
404 ledger,
405 root,
406 rootPid: 100,
407 });
408 return undefined;
409 } catch (error) {
410 return error;
411 }
412 };
413 expect(capture()).toMatchObject({
414 detail: "ACP process 100 exited before its ownership ledger was captured",
415 });
416 fixture.processes.set(100, identity(100, process.pid, 100, 100, "reused"));
417 expect(capture()).toMatchObject({
418 detail: "ACP process 100 exited before its ownership ledger was captured",
419 });
420 expect(ledger.size).toBe(0);
421 });
422
423 it.live("rotates more than 64 live parents without scanning retained tombstones", () =>
424 Effect.gen(function* () {
425 // The server fixture's process group is the runner's real pid, so a synthetic
426 // parent sharing it would be skipped as the server's own group.
427 const parentPidBase = process.pid < 500_000 ? 500_000 : 1_000;
428 const parents = Array.from({ length: 130 }, (_, index) =>
429 identity(parentPidBase + index, 100, parentPidBase + index, parentPidBase + index),
430 );
431 let childListReads = 0;
432 let identityCalls = 0;
433 let snapshotCalls = 0;
434 const fixture = makeController({
435 processes: [server(), identity(100, process.pid, 100, 100)],
436 });
437 const controller: AcpSessionRuntime.AcpPosixProcessTreeController = {
438 ...fixture.controller,
439 childPidsOf: (pid) => {
440 childListReads += 1;
441 return fixture.controller.childPidsOf(pid);
442 },
443 identity: (pid) => {
444 identityCalls += 1;
445 return fixture.controller.identity(pid);
446 },
447 snapshot: () => {
448 snapshotCalls += 1;
449 return fixture.controller.snapshot();
450 },
451 };
452 const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
453 const childQueues = new Map<number, Array<number>>();
454 const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>();
455 const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
456 for (let index = 0; index < 5_000; index += 1) {
457 const tombstone = identity(100_000 + index, 1, 100_000 + index, 100_000 + index);
458 ledger.set(`${tombstone.pid}:${tombstone.startTime}`, {
459 ...tombstone,
460 parentExecutable: undefined,
461 parentStartTime: "",
462 });
463 }
464 AcpSessionRuntime.observePosixOwnershipLedger({
465 childQueues,
466 controller,
467 frontier,
468 ledger,
469 root,
470 rootPid: 100,
471 });
472 for (const parent of parents) {
473 fixture.processes.set(parent.pid, parent);
474 fixture.processes.set(
475 parent.pid + 10_000,
476 identity(parent.pid + 10_000, parent.pid, parent.pgid, parent.sid),
477 );
478 }
479 let passes = 0;
480 while (
481 !parents.every((parent) =>
482 [...ledger.values()].some((owned) => owned.pid === parent.pid + 10_000),
483 ) &&
484 passes < 40
485 ) {
486 childListReads = 0;
487 identityCalls = 0;
488 AcpSessionRuntime.observePosixOwnershipLedger({
489 childQueues,
490 controller,
491 frontier,
492 ledger,
493 maxProcesses: 64,
494 root,
495 rootPid: 100,
496 });
497 expect(identityCalls + childListReads).toBeLessThanOrEqual(64);
498 passes += 1;
499 }
500
501 const missing = parents.filter(
502 (parent) => ![...ledger.values()].some((owned) => owned.pid === parent.pid + 10_000),
503 );
504 expect(missing, `missing after ${passes} passes`).toEqual([]);
505 expect(passes).toBeGreaterThan(2);
506 yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
507 controller,
508 grace: 0,
509 ledger,
510 rootPid: 100,
511 });
512 expect(snapshotCalls).toBe(10);
513 expect(fixture.processes.size).toBe(1);
514 }),
515 );
516
517 it.live("terminates nested owned groups bottom-up and catches a TERM fork race", () =>
518 Effect.gen(function* () {
519 let forked = false;
520 const fixture = makeController({
521 processes: [
522 server(),
523 identity(100, process.pid, 100, 100),
524 identity(110, 100, 110, 110),
525 identity(115, 110, 115, 110),
526 identity(120, 110, 120, 120),
527 identity(121, 120, 120, 120),
528 ],
529 onProcess: (processes, pid, signal) => {
530 if (signal === "SIGTERM" && pid === 121 && !forked) {
531 forked = true;
532 processes.set(122, identity(122, 110, 122, 122));
533 }
534 processes.delete(pid);
535 },
536 });
537
538 yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
539 controller: fixture.controller,
540 grace: 0,
541 rootPid: 100,
542 });
543
544 expect(fixture.processes.has(100)).toBe(false);
545 expect(fixture.processes.has(122)).toBe(false);
546 expect(fixture.signals.indexOf("process:121:SIGTERM")).toBeLessThan(
547 fixture.signals.indexOf("process:120:SIGTERM"),
548 );
549 expect(fixture.signals.indexOf("process:115:SIGTERM")).toBeLessThan(
550 fixture.signals.indexOf("process:110:SIGTERM"),
551 );
552 }),
553 );
554
555 it.live("falls back to exact PIDs for unknown group members and a missing leader", () =>
556 Effect.gen(function* () {
557 const unrelated = identity(999, 1, 110, 110, "unrelated");
558 const fixture = makeController({
559 processes: [
560 server(),
561 identity(100, process.pid, 100, 100),
562 identity(110, 100, 110, 110),
563 identity(111, 110, 110, 110),
564 unrelated,
565 ],
566 onProcess: (processes, pid) => {
567 processes.delete(pid);
568 if (pid === 111) processes.delete(110);
569 },
570 });
571
572 yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
573 controller: fixture.controller,
574 grace: 0,
575 rootPid: 100,
576 });
577
578 expect(fixture.signals).toContain("process:111:SIGTERM");
579 expect(fixture.processes.get(999)).toEqual(unrelated);
580 }),
581 );
582
583 it.live("re-admits a still-owned child after PID reuse and never signals the T3 session", () =>
584 Effect.gen(function* () {
585 const reused = identity(110, 100, 110, 110, "reused");
586 const fixture = makeController({
587 processes: [
588 server(),
589 identity(100, process.pid, 100, 100),
590 identity(110, 100, 110, 110, "owned"),
591 identity(120, 100, 120, process.pid),
592 ],
593 onProcess: (processes, pid) => {
594 if (pid === 110) processes.set(110, reused);
595 else processes.delete(pid);
596 },
597 });
598
599 const result = yield* Effect.exit(
600 AcpSessionRuntime.terminatePosixOwnedProcessTree({
601 controller: fixture.controller,
602 grace: 0,
603 rootPid: 100,
604 }),
605 );
606
607 expect(Exit.isFailure(result)).toBe(true);
608 expect(fixture.processes.get(110)).toEqual(reused);
609 expect(
610 fixture.signals.filter((entry) => entry.startsWith("process:110:")).length,
611 ).toBeGreaterThan(0);
612 expect(fixture.signals.some((entry) => entry.includes(":120:"))).toBe(false);
613 }),
614 );
615
616 it.live("does not treat zombie residual entries as teardown survivors", () =>
617 Effect.gen(function* () {
618 expect(AcpSessionRuntime.posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "Z" })).toBe(
619 true,
620 );
621 expect(AcpSessionRuntime.posixProcessIsZombie({ ...identity(1, 0, 1, 1), state: "S" })).toBe(
622 false,
623 );
624 const withoutState: AcpSessionRuntime.AcpPosixProcessIdentity = {
625 executable: "/proc/1/exe",
626 pgid: 1,
627 pid: 1,
628 ppid: 0,
629 sid: 1,
630 startTime: "1",
631 };
632 expect(AcpSessionRuntime.posixProcessIsZombie(withoutState)).toBe(false);
633
634 const root = identity(100, process.pid, 100, 100);
635 const zombieChild = identity(110, 100, 110, 110, "110", "Z");
636 const fixture = makeController({
637 processes: [server(), root, zombieChild],
638 onProcess: (processes, pid) => {
639 // Kill leaves a zombie with the same pid/starttime until reaped.
640 const current = processes.get(pid);
641 if (current === undefined) return;
642 processes.set(pid, { ...current, state: "Z" });
643 },
644 });
645 yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
646 controller: fixture.controller,
647 grace: 0,
648 rootPid: 100,
649 });
650 // Zombies remain visible but must not fail residual teardown.
651 expect(fixture.processes.get(100)?.state).toBe("Z");
652 expect(fixture.processes.get(110)?.state).toBe("Z");
653 }),
654 );
655
656 it("admits a live child after a free PID was previously reserved by a dead entry", () => {
657 const staleChild: AcpSessionRuntime.AcpOwnedPosixProcess = {
658 ...identity(200, 100, 200, 200, "stale-child"),
659 parentExecutable: `/proc/100/exe`,
660 parentStartTime: "100",
661 };
662 const liveChild = identity(200, 100, 200, 200, "live-child");
663 const root = identity(100, process.pid, 100, 100);
664 const ownedRoot: AcpSessionRuntime.AcpOwnedPosixProcess = {
665 ...root,
666 parentExecutable: `/proc/${process.pid}/exe`,
667 parentStartTime: "server",
668 };
669 const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>([
670 [`100:${root.startTime}`, ownedRoot],
671 [`200:${staleChild.startTime}`, staleChild],
672 ]);
673 const controller = makeController({
674 processes: [server(), root],
675 }).controller;
676
677 AcpSessionRuntime.capturePosixOwnershipLedger({
678 controller,
679 ledger,
680 rootPid: 100,
681 table: [root],
682 });
683 expect([...ledger.values()].some((entry) => entry.pid === 200)).toBe(false);
684
685 AcpSessionRuntime.capturePosixOwnershipLedger({
686 controller: makeController({ processes: [server(), root, liveChild] }).controller,
687 ledger,
688 rootPid: 100,
689 table: [root, liveChild],
690 });
691
692 const admitted = [...ledger.values()].find((entry) => entry.pid === 200);
693 expect(admitted?.startTime).toBe("live-child");
694 });
695
696 it.live("signals children forked under a still-live parent during the same pass", () =>
697 Effect.gen(function* () {
698 let forked = false;
699 const fixture = makeController({
700 processes: [
701 server(),
702 identity(100, process.pid, 100, 100),
703 identity(110, 100, 110, 110),
704 identity(111, 110, 111, 111),
705 ],
706 onProcess: (processes, pid) => {
707 if (pid === 111 && !forked) {
708 forked = true;
709 processes.set(112, identity(112, 110, 112, 112));
710 }
711 processes.delete(pid);
712 },
713 });
714
715 yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
716 controller: fixture.controller,
717 grace: 0,
718 rootPid: 100,
719 });
720
721 expect(forked).toBe(true);
722 expect(fixture.processes.has(112)).toBe(false);
723 expect(fixture.signals.some((entry) => entry.startsWith("process:112:"))).toBe(true);
724 }),
725 );
726
727 it.live("detects an owned child first observed in the final survivor snapshot", () =>
728 Effect.gen(function* () {
729 const lateChild = identity(111, 110, 111, 111);
730 const fixture = makeController({
731 processes: [server(), identity(100, process.pid, 100, 100), identity(110, 100, 110, 110)],
732 onProcess: (processes, pid) => {
733 if (pid !== 110) processes.delete(pid);
734 },
735 });
736 let snapshotCalls = 0;
737 const controller: AcpSessionRuntime.AcpPosixProcessTreeController = {
738 ...fixture.controller,
739 snapshot: () => {
740 snapshotCalls += 1;
741 if (snapshotCalls === 6) fixture.processes.set(lateChild.pid, lateChild);
742 return fixture.controller.snapshot();
743 },
744 };
745
746 const error = yield* Effect.flip(
747 AcpSessionRuntime.terminatePosixOwnedProcessTree({
748 controller,
749 discoveryPasses: 2,
750 grace: 0,
751 rootPid: 100,
752 }),
753 );
754
755 expect(snapshotCalls).toBe(6);
756 expect(error.detail).toContain("110, 111");
757 }),
758 );
759
760 it.live("retains the ledger across root exit and an explicit failure for finalizer retry", () =>
761 Effect.gen(function* () {
762 let ignoreSignals = true;
763 const ledger = new Map<string, AcpSessionRuntime.AcpOwnedPosixProcess>();
764 const frontier = new Map<number, AcpSessionRuntime.AcpOwnedPosixProcess>();
765 const childQueues = new Map<number, Array<number>>();
766 const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined };
767 const fixture = makeController({
768 processes: [
769 server(),
770 identity(100, process.pid, 100, 100),
771 identity(110, 100, 110, 110),
772 identity(111, 110, 110, 110),
773 ],
774 onProcess: (processes, pid) => {
775 if (ignoreSignals && pid === 100) processes.delete(100);
776 if (!ignoreSignals) processes.delete(pid);
777 },
778 });
779 AcpSessionRuntime.observePosixOwnershipLedger({
780 childQueues,
781 controller: fixture.controller,
782 frontier,
783 ledger,
784 root,
785 rootPid: 100,
786 });
787
788 const explicit = yield* Effect.exit(
789 AcpSessionRuntime.terminatePosixOwnedProcessTree({
790 controller: fixture.controller,
791 grace: 0,
792 ledger,
793 rootPid: 100,
794 }),
795 );
796 expect(Exit.isFailure(explicit)).toBe(true);
797 expect(fixture.processes.has(100)).toBe(false);
798 expect(fixture.processes.has(111)).toBe(true);
799
800 fixture.processes.set(112, identity(112, 110, 112, 112));
801 AcpSessionRuntime.observePosixOwnershipLedger({
802 childQueues,
803 controller: fixture.controller,
804 frontier,
805 ledger,
806 root,
807 rootPid: 100,
808 });
809 ignoreSignals = false;
810 yield* AcpSessionRuntime.terminatePosixOwnedProcessTree({
811 controller: fixture.controller,
812 grace: 0,
813 ledger,
814 rootPid: 100,
815 });
816 expect(fixture.processes.has(110)).toBe(false);
817 expect(fixture.processes.has(111)).toBe(false);
818 expect(fixture.processes.has(112)).toBe(false);
819 }),
820 );
821
822 it("fails closed where a stable POSIX identity provider is unavailable", () => {
823 try {
824 AcpSessionRuntime.makePosixProcessTreeController("darwin");
825 throw new Error("Expected Darwin process ownership to fail closed");
826 } catch (error) {
827 expect(error).toMatchObject({
828 detail: "Detached ACP descendant ownership is unsupported on darwin",
829 });
830 }
831 });
832});