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

AcpSessionRuntime.processTree.test.ts

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