Skip to content

Commit 3678353

Browse files
fix(host-kit): one group-signal seam, and no deadline an app-log tail will not honour
`killProcessTree` probed a group with `process.kill(-pid, 0)` and then wrote to it by hand, so host-kit had two group-signal paths and the one every runner-tree kill already used was the one this file could not mock. The probe also decided nothing: EPERM made it report the group reachable and the following write was refused all the same. It is gone, and the detached branch is one call to `signalProcessGroupBestEffort`. That seam now lives in `exec.ts`, below the module that already reached it. `host-process.ts` imports `exec.ts` for `runCmd`, so importing its signal helper back up would close a production value-import cycle, which `check:layering` R4 rejects outright; and giving the two of them a new shared module below both is a module every one of those entries starts evaluating, which the eager-closure budgets reject. `@agent-device/host-kit/process` exports the same name from the new home, and nothing outside host-kit noticed. Two tests moved with the function. The two group-kill tests now answer writes at a guard which records what the kill aimed at and refuses to deliver it — the seam the hermetic signal setup points real kill paths at — and a source-shape test fails if a second `process.kill(-…)` ever appears in this module beside the seam. Reverting the detached branch to a raw group write turns that one red. `AppLogProcessCommand`'s host variant takes `Omit<HostCommandRequest, 'timeoutMs'>`. The background exec it feeds passes `allowFailure`, `cwd`, and `env` and cannot pass a timeout, so a producer that wrote one was writing a budget that never fires. Co-authored-by: Apex by Callstack <[email protected]>
1 parent a36dd28 commit 3678353

6 files changed

Lines changed: 100 additions & 101 deletions

File tree

‎packages/contracts/src/app-log-runtime.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,12 @@ export type AppLogBackgroundProcess = AsyncDisposable &
110110
export type AppLogProcessCommand =
111111
| Readonly<{
112112
kind: 'host';
113-
request: HostCommandRequest;
113+
/**
114+
* A streamed log tail is stopped by its owner, so a host command here has no deadline to
115+
* honour: the background exec drops `timeoutMs`. It stays out of the type so a producer
116+
* cannot pass a budget that silently never fires.
117+
*/
118+
request: Omit<HostCommandRequest, 'timeoutMs'>;
114119
}>
115120
| Readonly<{
116121
kind: 'android-adb';

‎packages/host-kit/src/internal/exec-kill-settle.test.ts‎

Lines changed: 66 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import assert from 'node:assert/strict';
22
import fs from 'node:fs';
33
import path from 'node:path';
4-
import { test } from 'vitest';
4+
import { test, vi } from 'vitest';
55
import {
66
isCommandTimeoutError,
77
runCmd,
88
runCmdBackground,
99
runCmdStreaming,
10+
signalProcessGroupBestEffort,
1011
type ExecBackgroundOptions,
1112
} from './exec.ts';
1213
import { shellQuote } from './shell-quote.ts';
@@ -164,37 +165,75 @@ test.runIf(process.platform !== 'win32')(
164165
// would wait forever. Whether the kill request or the child's exit arrives first is not a
165166
// question the callers answer, so both report to one settlement.
166167
//
167-
// The kill paths below address a process group whose leader this worker already reaped,
168-
// and the hermetic signal setup ends a worker's authority over a pid at that moment.
169-
// So the group writes are intercepted here, which is the seam that setup points at for
170-
// a real kill path, and the probe answer is what each test is choosing between.
168+
// The kill paths below address a process group whose leader this worker already reaped, and
169+
// the hermetic signal setup ends a worker's authority over a pid at that moment. So every
170+
// group write is answered by `guardGroupWrites` below, which is the seam that setup points a
171+
// real kill path at: it records what the kill aimed at and refuses to deliver it.
171172

172173
type GroupWrite = { readonly pid: number; readonly signal: string | number };
173174

174-
function interceptGroupWrites(probeAnswer: 'reachable' | 'gone'): {
175-
restore: () => void;
176-
signals: GroupWrite[];
177-
} {
175+
function guardGroupWrites(): { restore: () => void; writes: GroupWrite[] } {
178176
const original = process.kill.bind(process);
179-
const signals: GroupWrite[] = [];
177+
const writes: GroupWrite[] = [];
180178
process.kill = ((pid: number, signal: string | number = 'SIGTERM') => {
181-
if (pid >= 0) return original(pid, signal as NodeJS.Signals);
182-
if (signal === 0) {
183-
if (probeAnswer === 'gone') {
184-
throw Object.assign(new Error('no such process group'), { code: 'ESRCH' });
185-
}
186-
return true;
179+
if (pid < 0) {
180+
writes.push({ pid, signal });
181+
return false;
187182
}
188-
signals.push({ pid, signal });
189-
return true;
183+
return original(pid, signal as NodeJS.Signals);
190184
}) as typeof process.kill;
191-
return { signals, restore: () => (process.kill = original) };
185+
return { writes, restore: () => (process.kill = original) };
192186
}
193187

188+
test('group signaling addresses the negative pid and reports delivery', () => {
189+
const calls: GroupWrite[] = [];
190+
const killSpy = vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {
191+
calls.push({ pid: Number(pid), signal: signal ?? '' });
192+
return true;
193+
});
194+
195+
try {
196+
assert.equal(signalProcessGroupBestEffort(101, 'SIGKILL'), true);
197+
assert.deepEqual(calls, [{ pid: -101, signal: 'SIGKILL' }]);
198+
} finally {
199+
killSpy.mockRestore();
200+
}
201+
});
202+
203+
test('a group write in this module can only come from the seam', () => {
204+
// A second group-signal path in here would be the second seam the callers were written
205+
// against once more, and nothing at runtime distinguishes the two.
206+
const source = fs.readFileSync(new URL('./exec.ts', import.meta.url), 'utf8');
207+
const seam = source.indexOf('export function signalProcessGroupBestEffort');
208+
const writes = [...source.matchAll(/process\.kill\(-/g)].map((match) => match.index ?? -1);
209+
210+
assert.ok(seam >= 0);
211+
assert.deepEqual(writes, [seam + source.slice(seam).indexOf('process.kill(-')]);
212+
});
213+
214+
test('group signaling reports a vanished group and never signals an invalid pid', () => {
215+
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => {
216+
const error = new Error('not found') as NodeJS.ErrnoException;
217+
error.code = 'ESRCH';
218+
throw error;
219+
});
220+
221+
try {
222+
assert.equal(signalProcessGroupBestEffort(101, 'SIGTERM'), false);
223+
assert.equal(signalProcessGroupBestEffort(0, 'SIGTERM'), false);
224+
assert.equal(signalProcessGroupBestEffort(-1, 'SIGTERM'), false);
225+
// A zero or negative pid would address the caller's own group, or every
226+
// process the user owns, so it must not reach process.kill at all.
227+
assert.equal(killSpy.mock.calls.length, 1);
228+
} finally {
229+
killSpy.mockRestore();
230+
}
231+
});
232+
194233
test.runIf(process.platform !== 'win32')(
195234
'a detached deadline still kills the group its reaped child left behind',
196235
async () => {
197-
const groupWrites = interceptGroupWrites('reachable');
236+
const groupWrites = guardGroupWrites();
198237
let childPid = 0;
199238
try {
200239
const startedAt = Date.now();
@@ -213,7 +252,7 @@ test.runIf(process.platform !== 'win32')(
213252
},
214253
);
215254
assert.ok(Date.now() - startedAt < 1_000, 'settled only once the pipe holder finished');
216-
assert.deepEqual(groupWrites.signals, [{ pid: -childPid, signal: 'SIGKILL' }]);
255+
assert.deepEqual(groupWrites.writes, [{ pid: -childPid, signal: 'SIGKILL' }]);
217256
} finally {
218257
groupWrites.restore();
219258
}
@@ -222,11 +261,12 @@ test.runIf(process.platform !== 'win32')(
222261
);
223262

224263
test.runIf(process.platform !== 'win32')(
225-
'a detached deadline whose group is already gone signals nothing and still settles',
264+
'a detached deadline whose group cannot be signalled still settles',
226265
async () => {
227-
// A group with no members left has an id the kernel can hand to anyone, so a stale
228-
// deadline must not aim a signal at it.
229-
const groupWrites = interceptGroupWrites('gone');
266+
// A vanished group, an empty group, and a group owned by someone else all answer this
267+
// write with nothing, and the seam swallows that. The command still cannot wait on a pipe
268+
// holder it just asked to be killed.
269+
const groupWrites = guardGroupWrites();
230270
try {
231271
const startedAt = Date.now();
232272
await assert.rejects(
@@ -237,7 +277,7 @@ test.runIf(process.platform !== 'win32')(
237277
},
238278
);
239279
assert.ok(Date.now() - startedAt < 1_000, 'settled only once the pipe holder finished');
240-
assert.deepEqual(groupWrites.signals, []);
280+
assert.equal(groupWrites.writes.length, 1);
241281
} finally {
242282
groupWrites.restore();
243283
}

‎packages/host-kit/src/internal/exec.ts‎

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -869,20 +869,36 @@ function watchCommandAbort(
869869
}
870870

871871
/**
872-
* A detached command owns a process group, and the descendants we are trying to reach
873-
* are its members — which is what keeps the group id reserved. So the group is still
874-
* signalled after the direct child is reaped: those members are holding the pipes this
875-
* command is waiting on. An empty group's id is not reserved, and a group id that no
876-
* longer resolves tells us the members are gone, so the signal is skipped rather than
877-
* aimed at whatever process holds that id now.
872+
* Signals the process group led by `pid` — the tree a detached child spawned — best-effort,
873+
* and reports whether the write went through. One seam for every group kill in host-kit, so
874+
* a caller outside this module can mock it instead of delivering a real signal to a
875+
* fabricated pid (#1824). `host-process.ts` reaches it from here rather than the reverse:
876+
* that module imports `exec.ts` for `runCmd`, and a value import back up would close a cycle
877+
* the layering rules reject.
878+
*
879+
* A pid that is not a positive integer is refused without signalling: `0` would address this
880+
* process's own group, and a negative one every process this user owns.
881+
*/
882+
export function signalProcessGroupBestEffort(pid: number, signal: NodeJS.Signals): boolean {
883+
if (!Number.isInteger(pid) || pid <= 0) return false;
884+
try {
885+
process.kill(-pid, signal);
886+
return true;
887+
} catch {
888+
return false;
889+
}
890+
}
891+
892+
/**
893+
* A detached command owns a process group, and the descendants we are trying to reach are
894+
* its members — which is what keeps the group id reserved. So the group is still signalled
895+
* after the direct child is reaped: those members are holding the pipes this command is
896+
* waiting on. The one group-signal seam reports whether anything was reached rather than
897+
* throwing, and a group that is gone or not ours to signal is the case it reports false.
878898
*/
879899
function killProcessTree(child: ChildProcess, detached: boolean | undefined): void {
880900
if (detached && child.pid && process.platform !== 'win32') {
881-
if (isProcessGroupReachable(child.pid)) {
882-
try {
883-
process.kill(-child.pid, 'SIGKILL');
884-
} catch {}
885-
}
901+
signalProcessGroupBestEffort(child.pid, 'SIGKILL');
886902
return;
887903
}
888904
// A non-detached child leaves its pid free for the kernel to hand to an unrelated
@@ -893,16 +909,6 @@ function killProcessTree(child: ChildProcess, detached: boolean | undefined): vo
893909
child.kill('SIGKILL');
894910
}
895911

896-
function isProcessGroupReachable(pid: number): boolean {
897-
try {
898-
process.kill(-pid, 0);
899-
return true;
900-
} catch (error) {
901-
// EPERM means the group exists and simply isn't ours to signal.
902-
return (error as NodeJS.ErrnoException).code === 'EPERM';
903-
}
904-
}
905-
906912
/**
907913
* A kill that cannot reach an inherited-pipe holder must at least stop this process
908914
* from holding the other end of those pipes open after it has settled.

‎packages/host-kit/src/internal/host-process.test.ts‎

Lines changed: 0 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import {
99
readProcessCommand,
1010
readProcessStartTime,
1111
signalPidsBestEffort,
12-
signalProcessGroupBestEffort,
1312
stopPidsWithEscalation,
1413
uniquePositivePids,
1514
} from './host-process.ts';
@@ -123,40 +122,6 @@ test('best-effort signaling ignores invalid, current, and failed pids', () => {
123122
}
124123
});
125124

126-
test('group signaling addresses the negative pid and reports delivery', () => {
127-
const calls: Array<{ pid: number; signal: string | number | undefined }> = [];
128-
const killSpy = vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {
129-
calls.push({ pid: Number(pid), signal });
130-
return true;
131-
});
132-
133-
try {
134-
assert.equal(signalProcessGroupBestEffort(101, 'SIGKILL'), true);
135-
assert.deepEqual(calls, [{ pid: -101, signal: 'SIGKILL' }]);
136-
} finally {
137-
killSpy.mockRestore();
138-
}
139-
});
140-
141-
test('group signaling reports a vanished group and never signals an invalid pid', () => {
142-
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => {
143-
const error = new Error('not found') as NodeJS.ErrnoException;
144-
error.code = 'ESRCH';
145-
throw error;
146-
});
147-
148-
try {
149-
assert.equal(signalProcessGroupBestEffort(101, 'SIGTERM'), false);
150-
assert.equal(signalProcessGroupBestEffort(0, 'SIGTERM'), false);
151-
assert.equal(signalProcessGroupBestEffort(-1, 'SIGTERM'), false);
152-
// A zero or negative pid would address the caller's own group, or every
153-
// process the user owns, so it must not reach process.kill at all.
154-
assert.equal(killSpy.mock.calls.length, 1);
155-
} finally {
156-
killSpy.mockRestore();
157-
}
158-
});
159-
160125
test('pid escalation sends TERM, then KILL only to live pids', async () => {
161126
vi.useFakeTimers();
162127
const alivePids = new Set([101, 202, 303]);

‎packages/host-kit/src/internal/host-process.ts‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -267,23 +267,6 @@ export function signalPidsBestEffort(
267267
return signaled;
268268
}
269269

270-
/**
271-
* Signals the process group led by `pid` (the tree a detached child spawned),
272-
* best-effort. Lives beside `signalPidsBestEffort` so a runner-tree kill has one
273-
* seam for both writes, and a unit test that mocks this module's liveness reads
274-
* mocks the signal writes in the same place instead of delivering a real signal
275-
* to a fabricated pid (#1824).
276-
*/
277-
export function signalProcessGroupBestEffort(pid: number, signal: NodeJS.Signals): boolean {
278-
if (!Number.isInteger(pid) || pid <= 0) return false;
279-
try {
280-
process.kill(-pid, signal);
281-
return true;
282-
} catch {
283-
return false;
284-
}
285-
}
286-
287270
export async function waitForProcessExit(pid: number, timeoutMs: number): Promise<boolean> {
288271
if (!isProcessAlive(pid)) return true;
289272
const start = Date.now();

‎packages/host-kit/src/process.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,12 @@ export {
1919
readProcessIdentityFacts,
2020
readProcessStartTime,
2121
signalPidsBestEffort,
22-
signalProcessGroupBestEffort,
2322
stopPidsWithEscalation,
2423
uniquePositivePids,
2524
waitForProcessExit,
2625
writeHostStderr,
2726
} from './internal/host-process.ts';
27+
export { signalProcessGroupBestEffort } from './internal/exec.ts';
2828
export { reapOwnedProcessRecordsAtStartup } from './internal/owned-process-reaper.ts';
2929
export {
3030
createOwnedProcessRecordStore,

0 commit comments

Comments
 (0)