Skip to content

Commit bed5daf

Browse files
authored
fix(qa): cancellation is ignored during command cleanup (#133143)
* fix(qa): honor cancellation while command cleanup is pending * refactor(qa): remove redundant settlement timer wrappers
1 parent 4b65ebd commit bed5daf

2 files changed

Lines changed: 69 additions & 50 deletions

File tree

‎extensions/qa-lab/src/posix-command-settlement.ts‎

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,22 +37,16 @@ export function createQaPosixCommandSettlement(params: QaPosixCommandSettlementP
3737
let drainIdle: NodeJS.Timeout | undefined;
3838
let drainTimedOut = false;
3939
let executionTimer: NodeJS.Timeout | undefined;
40+
let parentSignal: "SIGINT" | "SIGTERM" | undefined;
4041
let primary: QaPosixCommandPrimary | undefined;
4142
let stdioDrained = false;
4243
const windows = params.windowsCleanup;
4344

4445
const schedule = (fn: () => void, delay: number) => {
45-
const timer = setTimeout(() => {
46-
fn();
47-
}, delay);
46+
const timer = setTimeout(fn, delay);
4847
timers.push(timer);
4948
return timer;
5049
};
51-
const cancel = (timer: NodeJS.Timeout | undefined) => {
52-
if (timer) {
53-
clearTimeout(timer);
54-
}
55-
};
5650
// Cleanup owns only the original PGID; a descendant that calls setsid can escape it.
5751
const alive = () =>
5852
windows?.alive?.() ??
@@ -92,7 +86,6 @@ export function createQaPosixCommandSettlement(params: QaPosixCommandSettlementP
9286
if (disposed || !primary || !cleanupDone || !stdioDrained) {
9387
return;
9488
}
95-
const parentSignal = primary.type === "parent-signal" ? primary.signal : undefined;
9689
const settlementFailure =
9790
errors.length > 1 ? new AggregateError(errors, params.settlementFailureMessage) : errors[0];
9891
dispose();
@@ -162,15 +155,15 @@ export function createQaPosixCommandSettlement(params: QaPosixCommandSettlementP
162155
};
163156
const freeze = (nextPrimary: QaPosixCommandPrimary, initialSignal = params.initialSignal) => {
164157
primary ??= nextPrimary;
165-
cancel(executionTimer);
158+
clearTimeout(executionTimer);
166159
// Every terminal path needs a drain bound: an escaped descendant can retain
167160
// inherited stdio even after the original process group is gone.
168161
armDrainDeadline();
169162
startCleanup(initialSignal);
170163
settle();
171164
};
172165
const armIdle = () => {
173-
cancel(drainIdle);
166+
clearTimeout(drainIdle);
174167
drainIdle = schedule(startCleanup, 100);
175168
};
176169
const onOutput = () => {
@@ -204,7 +197,7 @@ export function createQaPosixCommandSettlement(params: QaPosixCommandSettlementP
204197
// `exit` freezes the leader tuple; only `close` can prove stdio drained.
205198
function onExit(exitCode: number | null, nextSignal: NodeJS.Signals | null) {
206199
primary ??= { type: "exit", exitCode, signal: nextSignal };
207-
cancel(executionTimer);
200+
clearTimeout(executionTimer);
208201
armDrainDeadline();
209202
armIdle();
210203
if (cleanupStarted && !cleanupDone && !alive()) {
@@ -213,8 +206,8 @@ export function createQaPosixCommandSettlement(params: QaPosixCommandSettlementP
213206
}
214207
function onClose() {
215208
stdioDrained = true;
216-
cancel(drainIdle);
217-
cancel(drainDeadline);
209+
clearTimeout(drainIdle);
210+
clearTimeout(drainDeadline);
218211
if (!cleanupStarted && windows) {
219212
cleanupDone = true;
220213
} else if (cleanupStarted && windows?.closeCompletesCleanup) {
@@ -238,6 +231,9 @@ export function createQaPosixCommandSettlement(params: QaPosixCommandSettlementP
238231
process.kill(process.pid, nextSignal);
239232
return;
240233
}
234+
// The command outcome may already be frozen while descendants drain.
235+
// Parent cancellation still has to be re-raised after cleanup.
236+
parentSignal ??= nextSignal;
241237
freeze({ type: "parent-signal", signal: nextSignal }, nextSignal);
242238
};
243239
function onParentSigint() {

‎extensions/qa-lab/src/test-file-scenario-command-lifecycle.test.ts‎

Lines changed: 59 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -395,41 +395,64 @@ describe.skipIf(process.platform === "win32")("qa scenario command lifecycle", (
395395
expect(parentHandlers.size).toBe(0);
396396
});
397397

398-
it("forwards parent signals, cleans handlers, and preserves interruption details", async () => {
399-
createChild();
400-
setQaScenarioCommandCleanupTimings({ killGraceMs: 20, forceSettleMs: 10 });
401-
let processGroupAlive = true;
402-
processKill.mockImplementation((pid, signal) => {
403-
if (pid === -42 && signal === "SIGKILL") {
404-
processGroupAlive = false;
405-
}
406-
if (pid === -42 && signal === 0 && !processGroupAlive) {
407-
throw Object.assign(new Error("gone"), { code: "ESRCH" });
408-
}
409-
return true;
410-
});
411-
412-
const resultPromise = runCommand();
413-
const signalHandler = parentHandlers.get("SIGTERM") as
414-
| ((signal: ParentSignal) => void)
415-
| undefined;
416-
expect(signalHandler).toBeDefined();
417-
signalHandler?.("SIGTERM");
418-
await vi.advanceTimersByTimeAsync(20);
419-
const child = spawnMock.mock.results[0]?.value as ChildProcess;
420-
child.emit("exit", null, "SIGKILL");
421-
child.emit("close", null, "SIGKILL");
422-
await vi.advanceTimersByTimeAsync(10);
398+
it.each([
399+
{
400+
phase: "running",
401+
result: {
402+
exitCode: 1,
403+
failureMessage: "scenario-command interrupted by SIGTERM",
404+
signal: "SIGTERM",
405+
},
406+
},
407+
{ phase: "exited", result: { exitCode: 7, signal: null } },
408+
{
409+
phase: "timed out",
410+
result: {
411+
exitCode: 1,
412+
failureMessage: "scenario-command timed out after 100ms",
413+
signal: null,
414+
},
415+
},
416+
])(
417+
"re-raises a parent signal when the command is $phase without changing its outcome",
418+
async ({ phase, result }) => {
419+
const child = createChild();
420+
setQaScenarioCommandCleanupTimings({ killGraceMs: 20, forceSettleMs: 10 });
421+
let processGroupAlive = true;
422+
processKill.mockImplementation((pid, signal) => {
423+
if (pid === -42 && signal === "SIGKILL") {
424+
processGroupAlive = false;
425+
}
426+
if (pid === -42 && signal === 0 && !processGroupAlive) {
427+
throw Object.assign(new Error("gone"), { code: "ESRCH" });
428+
}
429+
return true;
430+
});
423431

424-
await expect(resultPromise).resolves.toEqual({
425-
exitCode: 1,
426-
failureMessage: "scenario-command interrupted by SIGTERM",
427-
signal: "SIGTERM",
428-
stdout: "",
429-
stderr: "",
430-
});
431-
expect(processKill).toHaveBeenCalledWith(-42, "SIGTERM");
432-
expect(processKill).toHaveBeenCalledWith(process.pid, "SIGTERM");
433-
expect(parentHandlers.size).toBe(0);
434-
});
432+
const resultPromise = runCommand(100);
433+
if (phase === "exited") {
434+
child.emit("exit", 7, null);
435+
} else if (phase === "timed out") {
436+
await vi.advanceTimersByTimeAsync(100);
437+
}
438+
const signalHandler = parentHandlers.get("SIGTERM") as
439+
| ((signal: ParentSignal) => void)
440+
| undefined;
441+
expect(signalHandler).toBeDefined();
442+
signalHandler?.("SIGTERM");
443+
await vi.advanceTimersByTimeAsync(20);
444+
child.emit("exit", null, "SIGKILL");
445+
child.emit("close", null, "SIGKILL");
446+
await vi.advanceTimersByTimeAsync(10);
447+
448+
await expect(resultPromise).resolves.toEqual({
449+
...result,
450+
stdout: "",
451+
stderr: "",
452+
});
453+
expect(processKill).toHaveBeenCalledWith(-42, "SIGTERM");
454+
expect(processKill).toHaveBeenCalledWith(process.pid, "SIGTERM");
455+
expect(parentHandlers.size).toBe(0);
456+
},
457+
);
435458
});

0 commit comments

Comments
 (0)