Skip to content

Commit 2665364

Browse files
committed
fix(exec): forward SIGHUP and SIGQUIT so a hung-up terminal stops the build too
The child leads its own session, so terminal hangup reached only the wrapper and its default action killed it before the release: the claim named a dead pid while the build kept mutating the device. attachSignalForwarding now owns one list of forwarded signals (SIGINT, SIGTERM, SIGHUP, SIGQUIT), registers and disposes every handler from it, and replays all signals received before the child existed. The claim is released only after the child exits. - exec tests: real-process SIGHUP case (fails on the previous code: wrapper killed, claim stranded, child alive) asserting release-before-exit, the child group stopping, and exit 129. - help and docs name the full forwarded set. - delete the dead outcome assignment in releaseExecDeviceClaim. - fix the stale device-claim-conflict.ts path in the help-conformance sample.
1 parent 6318cb0 commit 2665364

7 files changed

Lines changed: 133 additions & 24 deletions

File tree

‎scripts/help-conformance-sample-outputs.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ Hint: Run agent-device session list to inspect active sessions. To reuse this de
9191
};
9292

9393
// Enforced cross-daemon device claim conflict from
94-
// packages/daemon/src/resources/device/device-claim-conflict.ts. This path is deliberately non-retriable:
94+
// packages/daemon-contracts/src/device-claim-conflict.ts. This path is deliberately non-retriable:
9595
// the exact status command is the only safe next step while ownership is live.
9696
export const DEVICE_CLAIM_IN_USE_SAMPLE = {
9797
command: 'agent-device open Demo --platform android --serial emulator-5554',
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import fs from 'node:fs';
2+
import path from 'node:path';
3+
import { withTestDeviceInventory } from '@agent-device/device-selection/inventory-gateways-fixtures';
4+
import { ANDROID_EMULATOR } from '@agent-device/test-kit';
5+
import type { CliFlags } from '@agent-device/contracts/command';
6+
import { runExecCommand } from '../exec.ts';
7+
8+
// The child-process half of the SIGHUP case in exec.test.ts: a real `exec`
9+
// wrapper receiving a real SIGHUP, exactly as a closed terminal delivers it.
10+
// Only a real signal exercises the wrapper process's own default disposition,
11+
// so the stub inventory runs in the wrapper's process like exec-cli-fixture.ts.
12+
// The child records its pid and replaces the shell with `exec sleep`, keeping
13+
// that pid, so the test can prove the group — not just the wrapper — stopped.
14+
const dirs = JSON.parse(process.env.EXEC_TEST_DIRS ?? '{}') as {
15+
claimsDir?: string;
16+
stateDir?: string;
17+
};
18+
const claimsDir = dirs.claimsDir;
19+
const stateDir = dirs.stateDir;
20+
if (!claimsDir || !stateDir) {
21+
process.stderr.write('exec-hup-fixture: EXEC_TEST_DIRS missing\n');
22+
process.exit(2);
23+
}
24+
process.env.AGENT_DEVICE_CLAIMS_DIR = claimsDir;
25+
26+
const flags: CliFlags = {
27+
json: false,
28+
help: false,
29+
version: false,
30+
platform: 'android',
31+
serial: ANDROID_EMULATOR.id,
32+
};
33+
34+
const childPidFile = path.join(stateDir, 'hup-child.pid');
35+
fs.mkdirSync(path.join(stateDir, 'exec'), { recursive: true });
36+
const exitCode = await withTestDeviceInventory(
37+
{ local: async () => [ANDROID_EMULATOR] },
38+
async () =>
39+
await runExecCommand(['sh', '-c', `echo $$ > ${JSON.stringify(childPidFile)}; exec sleep 8`], {
40+
flags,
41+
stateDir,
42+
}),
43+
);
44+
process.exit(exitCode);

‎src/cli/commands/__tests__/exec.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,16 @@ async function waitFor(condition: () => boolean | Promise<boolean>): Promise<voi
118118
}
119119
}
120120

121+
/** Liveness probe by pid; signal 0 sends nothing, ESRCH means the process is gone. */
122+
function processAlive(pid: number): boolean {
123+
try {
124+
process.kill(pid, 0);
125+
return true;
126+
} catch {
127+
return false;
128+
}
129+
}
130+
121131
/**
122132
* A child that runs until the test releases it: the loop is bounded so a failed
123133
* assertion ends the child instead of hanging the run, and every release path
@@ -317,6 +327,43 @@ test('forwards SIGTERM to the child and exits with the signal code after releasi
317327
assert.equal(storedClaim(dirs.claimsDir), undefined);
318328
});
319329

330+
test('a real SIGHUP stops the child group and releases the claim before the wrapper exits', async () => {
331+
const dirs = useDirs();
332+
// Only a real signal exercises the wrapper's own default disposition, so this
333+
// runs the wrapper as a real process like the SIGKILL case. Before the
334+
// SIGHUP handler existed the wrapper died on its default action, leaving the
335+
// claim pointing at a dead pid while the child kept running — so the release
336+
// and child-liveness assertions below are the fail-before, not the exit code
337+
// (a default-action death also reports failure there).
338+
const hupFixture = path.join(import.meta.dirname, 'exec-hup-fixture.ts');
339+
const child = runCmdBackground(process.execPath, ['--experimental-strip-types', hupFixture], {
340+
cwd: process.cwd(),
341+
env: { ...process.env, EXEC_TEST_DIRS: JSON.stringify(dirs) },
342+
captureOutput: false,
343+
stdio: 'ignore',
344+
allowFailure: true,
345+
});
346+
try {
347+
await waitFor(() => claimEntry()?.claim?.session === 'exec:sh');
348+
const childPidFile = path.join(dirs.stateDir, 'hup-child.pid');
349+
await waitFor(() => fs.existsSync(childPidFile));
350+
const childPid = Number(fs.readFileSync(childPidFile, 'utf8'));
351+
assert.ok(Number.isInteger(childPid) && childPid > 0);
352+
353+
child.child.kill('SIGHUP');
354+
const exited = await child.wait;
355+
// The rule: the wrapper outlives the signal, waits for the child, and the
356+
// claim is already gone once its exit is observable.
357+
assert.equal(storedClaim(dirs.claimsDir), undefined);
358+
await waitFor(() => !processAlive(childPid));
359+
assert.equal(exited.exitCode, 128 + 1);
360+
} finally {
361+
// The wrapper's child leads its own session, so no test-side group kill can
362+
// reach it; the fixture bounds it with `sleep 8` instead.
363+
child.child.kill('SIGKILL');
364+
}
365+
});
366+
320367
test('refuses to run on a Windows host before touching the device or the claim store', async () => {
321368
const dirs = useDirs();
322369
const originalPlatform = process.platform;

‎src/cli/commands/exec.ts‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -176,37 +176,52 @@ async function runClaimedChild(
176176
}
177177

178178
type SignalForwarding = Readonly<{
179-
/** Forwards to the child's process group once it exists; a signal received earlier killed it at attach. */
179+
/** Forwards to the child's process group once it exists; signals received earlier are replayed at attach. */
180180
attach(child: { pid?: number }): void;
181181
readonly signal: NodeJS.Signals | null;
182182
dispose(): void;
183183
}>;
184184

185+
// Every terminating signal the wrapper can catch. The child leads its own
186+
// session, so terminal-generated signals reach only the wrapper: forwarding
187+
// them all is what keeps the claim and the build dying together. SIGHUP is the
188+
// closed terminal or dropped SSH connection, SIGQUIT the Ctrl-\; without a
189+
// handler either one would take the wrapper down before the release, leaving a
190+
// dead owner's claim while the build keeps mutating the device. SIGTSTP is
191+
// deliberately absent: stopping the wrapper with the child left running is the
192+
// shell's own semantics, and job control here would need a controlling
193+
// terminal the detached child does not share.
194+
const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'] as const;
195+
185196
function attachSignalForwarding(): SignalForwarding {
186-
let signal: NodeJS.Signals | null = null;
197+
let first: NodeJS.Signals | null = null;
187198
let child: { pid?: number } | undefined;
188-
const forward = (received: NodeJS.Signals) => {
189-
// The first signal owns the exit code; every received signal still reaches
190-
// the group, so a child that traps or ignores one signal stays stoppable
191-
// by the next.
192-
if (!signal) signal = received;
193-
if (child?.pid !== undefined) signalProcessGroupBestEffort(child.pid, received);
194-
};
195-
const onSigint = () => forward('SIGINT');
196-
const onSigterm = () => forward('SIGTERM');
197-
process.on('SIGINT', onSigint);
198-
process.on('SIGTERM', onSigterm);
199+
const received: NodeJS.Signals[] = [];
200+
const handlers = new Map<NodeJS.Signals, () => void>();
201+
for (const name of FORWARDED_SIGNALS) {
202+
const handler = () => {
203+
// The first signal owns the exit code; every received signal still reaches
204+
// the group, so a child that traps or ignores one stays stoppable by the
205+
// next, and the wrapper always lives to await the child and release.
206+
if (!first) first = name;
207+
received.push(name);
208+
if (child?.pid !== undefined) signalProcessGroupBestEffort(child.pid, name);
209+
};
210+
handlers.set(name, handler);
211+
process.on(name, handler);
212+
}
199213
return {
200214
attach(next) {
201215
child = next;
202-
if (signal && next.pid !== undefined) signalProcessGroupBestEffort(next.pid, signal);
216+
if (next.pid !== undefined) {
217+
for (const name of received) signalProcessGroupBestEffort(next.pid, name);
218+
}
203219
},
204220
get signal() {
205-
return signal;
221+
return first;
206222
},
207223
dispose() {
208-
process.off('SIGINT', onSigint);
209-
process.off('SIGTERM', onSigterm);
224+
for (const [name, handler] of handlers) process.off(name, handler);
210225
},
211226
};
212227
}
@@ -221,12 +236,13 @@ async function releaseExecDeviceClaim(ownership: DeviceClaimSessionOwnership): P
221236
try {
222237
outcome = await clearDeviceClaim(ownership);
223238
} catch (error) {
224-
outcome = 'unattributable';
225239
process.stderr.write(
226240
`agent-device exec: could not release the device claim: ${
227241
error instanceof Error ? error.message : String(error)
228242
}\n`,
229243
);
244+
// The wrapper is about to exit, so a claim left behind names a process that
245+
// is gone and every acquirer reconciles it as stale.
230246
return;
231247
}
232248
// The wrapper is about to exit, so a claim left behind names a process that is

‎src/commands/schema/command-overrides.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
7272
text: {
7373
summary: 'Run a command while holding the device claim',
7474
description:
75-
'Hold the host-local exclusive device claim for the selected local device for the whole lifetime of an external command, so a build that installs or reinstalls through the platform tools directly (expo run:ios, xcodebuild, adb install) is fenced against agent-device sessions on that device. Refuses to start while another session or wrapper holds the claim, forwards SIGINT/SIGTERM to the command, exits with its exit code, and attempts to release the claim on every exit path; a release that fails leaves a claim that device release --stale reports. A killed wrapper leaves a claim that the next acquirer reconciles once its owner is proven dead. Claims cover local devices of every platform family, never provider-leased cloud devices. macOS and Linux hosts only.',
75+
'Hold the host-local exclusive device claim for the selected local device for the whole lifetime of an external command, so a build that installs or reinstalls through the platform tools directly (expo run:ios, xcodebuild, adb install) is fenced against agent-device sessions on that device. Refuses to start while another session or wrapper holds the claim, forwards SIGINT, SIGHUP, SIGQUIT and SIGTERM to the command, exits with its exit code, and attempts to release the claim on every exit path; a release that fails leaves a claim that device release --stale reports. A killed wrapper leaves a claim that the next acquirer reconciles once its owner is proven dead. Claims cover local devices of every platform family, never provider-leased cloud devices. macOS and Linux hosts only.',
7676
},
7777
usageOverride:
7878
'exec [--platform <platform>] [--target mobile|tv|desktop] [--device <name>] [--udid <udid>] [--serial <serial>] [--ios-simulator-device-set <path>] -- <command> [args…]',

‎website/docs/docs/commands.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,10 @@ agent-device exec --platform android --serial emulator-5554 -- adb install app-d
216216
One exception, shared with every other claim: if the device reboots while `exec` holds the claim,
217217
the reboot already ended the build, so `open` settles the holder's durable resources, takes the
218218
claim, and reports the release in `warnings`.
219-
- The command's exit code is `exec`'s exit code. Ctrl+C (or `SIGTERM`) is forwarded to the command
220-
and its whole process group before `exec` exits, and `exec` attempts to release the claim on every
221-
exit path; a release that fails or can't attribute the record prints to stderr and leaves a claim
219+
- The command's exit code is `exec`'s exit code. Ctrl+C, terminal hangup, and Ctrl-\ (`SIGINT`,
220+
`SIGHUP`, `SIGQUIT`, `SIGTERM`) are forwarded to the command and its whole process group, `exec`
221+
waits for it to exit, and only then attempts to release the claim; a release that fails or can't
222+
attribute the record prints to stderr and leaves a claim
222223
that `device release --stale` reports. A killed `exec` leaves a claim that the next `open` or `exec`
223224
reconciles once its owner process is proven dead.
224225
- Claims exist only for local devices: `exec` refuses targets on a cloud provider lease. `exec` runs

‎website/docs/docs/sessions.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,8 @@ The claim is held by the `exec` process itself, not by a daemon, so it lasts exa
200200
command: while `exec` runs, another workspace's `open`, `boot`, or `install` on that device fails with
201201
`DEVICE_IN_USE` naming the holder, and succeeds again once `exec` exits. `exec` refuses to start the
202202
same way while another session holds the device. `exec` exits with your command's exit code,
203-
forwards Ctrl+C to it, and attempts to release the claim on every exit path; a release that fails
203+
forwards Ctrl+C, terminal hangup, and Ctrl-\ (`SIGINT`, `SIGHUP`, `SIGQUIT`, `SIGTERM`) to it,
204+
and attempts to release the claim only after the command exits; a release that fails
204205
leaves a claim `device release --stale` reports. If `exec` is killed outright, its claim appears in
205206
`agent-device device status --stale`. The next `open` or `exec` reconciles it automatically only
206207
when the recorded owner process is proven dead; a claim whose owner is uncertain — its PID now

0 commit comments

Comments
 (0)