The best way to control Claude Code, Codex and more from any computer or phone

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