Skip to content

Commit ca2108d

Browse files
fix(host-kit): both the kill request and the child exit can settle a command
A deadline that fired after the child had already exited left the command waiting for a `close` its pipe-holding descendant would never release: the group kill that ends that descendant cannot run through a child Node already reaped. Kill requests and child exits now report to one settlement that does not care which arrives first, a detached process group is still killed while its members are reachable, and settling closes our end of the pipes instead of holding them open for a stranger. The fake adb reads its marker path from the environment instead of having it spliced into the source it is generated from. Co-authored-by: Apex by Callstack <[email protected]>
1 parent 5b31383 commit ca2108d

5 files changed

Lines changed: 334 additions & 79 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import { createCommandKillSettlement } from './command-kill-settlement.ts';
4+
5+
function buildSettlement(): {
6+
state: { kills: number; settled: (number | null)[] };
7+
settlement: ReturnType<typeof createCommandKillSettlement>;
8+
} {
9+
const state = { kills: 0, settled: [] as (number | null)[] };
10+
const settlement = createCommandKillSettlement({
11+
killProcessTree: () => {
12+
state.kills += 1;
13+
},
14+
settle: (code) => state.settled.push(code),
15+
});
16+
return { state, settlement };
17+
}
18+
19+
test('a kill request waits for the child it signalled', () => {
20+
const { state, settlement } = buildSettlement();
21+
settlement.requestKill();
22+
assert.equal(state.kills, 1);
23+
assert.deepEqual(state.settled, []);
24+
});
25+
26+
test('a kill request settles the child exit that follows it', () => {
27+
const { state, settlement } = buildSettlement();
28+
settlement.requestKill();
29+
settlement.recordExit(137);
30+
assert.equal(state.kills, 1);
31+
assert.deepEqual(state.settled, [137]);
32+
});
33+
34+
test('a child that exited on its own settles at the kill request that follows', () => {
35+
const { state, settlement } = buildSettlement();
36+
settlement.recordExit(0);
37+
settlement.requestKill();
38+
assert.equal(state.kills, 1);
39+
assert.deepEqual(state.settled, [0]);
40+
});
41+
42+
test('an exit with no kill request behind it settles nothing', () => {
43+
const { state, settlement } = buildSettlement();
44+
settlement.recordExit(0);
45+
assert.equal(state.kills, 0);
46+
assert.deepEqual(state.settled, []);
47+
});
48+
49+
test('a missing exit code reaches settlement as a failure', () => {
50+
const { state, settlement } = buildSettlement();
51+
settlement.recordExit(null);
52+
settlement.requestKill();
53+
assert.deepEqual(state.settled, [1]);
54+
});
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* A command this module asked to be killed is finished once its child is gone, without
3+
* waiting for the stdio pipes to drain: a descendant that inherited them keeps `close`
4+
* from arriving, and the request behind the command — and the device lock it holds —
5+
* would wait forever. Whether the kill request or the child's exit arrives first is not
6+
* a question each caller should answer, so both report here and settlement happens once.
7+
*/
8+
export type CommandKillSettlement = {
9+
/** Signals the command's process tree, then settles the command if its child is gone. */
10+
readonly requestKill: () => void;
11+
/** Records the child's exit, then settles the command if a kill was already requested. */
12+
readonly recordExit: (code: number | null) => void;
13+
};
14+
15+
export function createCommandKillSettlement(input: {
16+
readonly killProcessTree: () => void;
17+
readonly settle: (exitCode: number | null) => void;
18+
}): CommandKillSettlement {
19+
let killRequested = false;
20+
let exited = false;
21+
let exitCode: number | null = null;
22+
const settleIfKilledAndGone = (): void => {
23+
if (killRequested && exited) input.settle(exitCode);
24+
};
25+
return {
26+
requestKill: () => {
27+
killRequested = true;
28+
input.killProcessTree();
29+
settleIfKilledAndGone();
30+
},
31+
recordExit: (code) => {
32+
exited = true;
33+
exitCode = code ?? 1;
34+
settleIfKilledAndGone();
35+
},
36+
};
37+
}

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

Lines changed: 134 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -140,33 +140,147 @@ test.runIf(process.platform !== 'win32')(
140140
);
141141

142142
test.runIf(process.platform !== 'win32')(
143-
'a cancellation arriving after the child was reaped signals no process group',
143+
'a deadline that fires after the child exited settles without waiting for the pipe holder',
144144
async () => {
145-
// The direct child exits at once and leaves `sleep 0.4` draining the streams.
146-
// Its pid — and therefore its process-group id — is reusable from the moment it
147-
// is reaped, so the cancellation must not address that group any more.
148-
let childReaped: () => void = () => {};
149-
const reaped = new Promise<void>((resolve) => {
150-
childReaped = resolve;
151-
});
145+
// The direct child is gone, so no kill can reach the descendant that inherited its
146+
// pipes, and `close` only arrives when that descendant finishes. Settlement has to
147+
// come from the deadline noticing an already-exited child.
148+
const startedAt = Date.now();
149+
await assert.rejects(
150+
() => runCmd('/bin/sh', ['-c', 'sleep 2 & exit 0'], { timeoutMs: 100 }),
151+
(error: unknown) => {
152+
assert.equal(isCommandTimeoutError(error), true);
153+
return true;
154+
},
155+
);
156+
assert.ok(Date.now() - startedAt < 1_000, 'settled only once the pipe holder finished');
157+
},
158+
10_000,
159+
);
160+
161+
// The kill paths below address a process group whose leader this worker already reaped,
162+
// and the hermetic signal setup ends a worker's authority over a pid at that moment.
163+
// So the group writes are intercepted here, which is the seam that setup points at for
164+
// a real kill path, and the probe answer is what each test is choosing between.
165+
166+
type GroupWrite = { readonly pid: number; readonly signal: string | number };
167+
168+
function interceptGroupWrites(probeAnswer: 'reachable' | 'gone'): {
169+
restore: () => void;
170+
signals: GroupWrite[];
171+
} {
172+
const original = process.kill.bind(process);
173+
const signals: GroupWrite[] = [];
174+
process.kill = ((pid: number, signal: string | number = 'SIGTERM') => {
175+
if (pid >= 0) return original(pid, signal as NodeJS.Signals);
176+
if (signal === 0) {
177+
if (probeAnswer === 'gone') {
178+
throw Object.assign(new Error('no such process group'), { code: 'ESRCH' });
179+
}
180+
return true;
181+
}
182+
signals.push({ pid, signal });
183+
return true;
184+
}) as typeof process.kill;
185+
return { signals, restore: () => (process.kill = original) };
186+
}
187+
188+
test.runIf(process.platform !== 'win32')(
189+
'a detached deadline still kills the group its reaped child left behind',
190+
async () => {
191+
const groupWrites = interceptGroupWrites('reachable');
192+
let childPid = 0;
193+
try {
194+
const startedAt = Date.now();
195+
await assert.rejects(
196+
() =>
197+
runCmdStreaming('/bin/sh', ['-c', 'sleep 2 & exit 0'], {
198+
detached: true,
199+
timeoutMs: 100,
200+
onSpawn: (child) => {
201+
childPid = child.pid ?? 0;
202+
},
203+
}),
204+
(error: unknown) => {
205+
assert.equal(isCommandTimeoutError(error), true);
206+
return true;
207+
},
208+
);
209+
assert.ok(Date.now() - startedAt < 1_000, 'settled only once the pipe holder finished');
210+
assert.deepEqual(groupWrites.signals, [{ pid: -childPid, signal: 'SIGKILL' }]);
211+
} finally {
212+
groupWrites.restore();
213+
}
214+
},
215+
10_000,
216+
);
217+
218+
test.runIf(process.platform !== 'win32')(
219+
'a detached deadline whose group is already gone signals nothing and still settles',
220+
async () => {
221+
// A group with no members left has an id the kernel can hand to anyone, so a stale
222+
// deadline must not aim a signal at it.
223+
const groupWrites = interceptGroupWrites('gone');
224+
try {
225+
const startedAt = Date.now();
226+
await assert.rejects(
227+
() => runCmd('/bin/sh', ['-c', 'sleep 2 & exit 0'], { detached: true, timeoutMs: 100 }),
228+
(error: unknown) => {
229+
assert.equal(isCommandTimeoutError(error), true);
230+
return true;
231+
},
232+
);
233+
assert.ok(Date.now() - startedAt < 1_000, 'settled only once the pipe holder finished');
234+
assert.deepEqual(groupWrites.signals, []);
235+
} finally {
236+
groupWrites.restore();
237+
}
238+
},
239+
10_000,
240+
);
241+
242+
test.runIf(process.platform !== 'win32')(
243+
'a request that was already canceled kills the command it arrives on',
244+
async () => {
245+
// The kill is issued before the caller finishes wiring, so a settlement that read
246+
// the watcher mid-construction would fail here rather than at the next await.
152247
const controller = new AbortController();
153-
const running = runCmdStreaming('/bin/sh', ['-c', 'sleep 0.4 &'], {
154-
signal: controller.signal,
155-
detached: true,
156-
onSpawn: (child) => {
157-
child.once('exit', childReaped);
248+
controller.abort();
249+
await assert.rejects(
250+
() => runCmd('/bin/sh', ['-c', 'sleep 5'], { signal: controller.signal }),
251+
(error: unknown) => {
252+
assert.equal(
253+
(error as { details?: Record<string, unknown> }).details?.reason,
254+
'request_canceled',
255+
);
256+
return true;
158257
},
159-
});
160-
const rejection = settledRejection(running);
258+
);
259+
},
260+
5_000,
261+
);
161262

162-
await reaped;
263+
test.runIf(process.platform !== 'win32')(
264+
'a background request that was already canceled ends its wait',
265+
async () => {
266+
const controller = new AbortController();
163267
controller.abort();
164-
const outcome = await rejection;
268+
const background = runCmdBackground('/bin/sh', ['-c', 'sleep 5'], {
269+
signal: controller.signal,
270+
});
165271

166-
assert.ok(outcome, 'a canceled command must not resolve');
167-
const details = (outcome.error as { details?: Record<string, unknown> }).details;
168-
assert.equal(details?.reason, 'request_canceled');
272+
await assert.rejects(
273+
() => background.wait,
274+
(error: unknown) => {
275+
assert.equal(
276+
(error as { details?: Record<string, unknown> }).details?.reason,
277+
'request_canceled',
278+
);
279+
return true;
280+
},
281+
);
169282
},
283+
5_000,
170284
);
171285

172286
test.runIf(process.platform !== 'win32')(

0 commit comments

Comments
 (0)