Skip to content

Commit 2e7ec5a

Browse files
d13claude
andcommitted
Fixes a failed git spawn keeping the process alive for its timeout
Node's `spawn` clears its `timeout` timer only on 'exit', which a launch that fails (e.g. a missing cwd, ENOENT) never emits, so each failed spawn left a ref'd timer that kept the process alive for the full git timeout (60s by default). This held git-cli's unit test run open ~55s after its tests finished, and would hang a short-lived core-gitlens consumer after any failed spawn, such as repo discovery on a deleted folder. Adds `spawnProcess`, the default spawner for `runSpawn` and `Git.stream`, which mirrors Node's timeout validation and kill handling but also clears the timer on 'close', as upstream does in nodejs/node#65506. Custom spawners still receive `timeout` unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 1b2ff5a commit 2e7ec5a

3 files changed

Lines changed: 110 additions & 7 deletions

File tree

‎packages/git-cli/src/exec/git.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { spawn } from 'child_process';
21
import { resolve as resolvePath } from 'path';
32
import * as process from 'process';
43
import type {
@@ -34,6 +33,7 @@ import type { SigningFormat } from '@gitlens/git/models/signature.js';
3433
import type { GitRunCancellation } from '@gitlens/git/run.types.js';
3534
import { CancellationError, getAbortSignalId, isCancellationError } from '@gitlens/utils/cancellation.js';
3635
import { getScopedCounter } from '@gitlens/utils/counter.js';
36+
import { spawnProcess } from '@gitlens/utils/env/node/exec.js';
3737
import { getDurationMilliseconds, hrtime } from '@gitlens/utils/hrtime.js';
3838
import { chunkByStringLength } from '@gitlens/utils/iterable.js';
3939
import type { LogChannel } from '@gitlens/utils/logger.js';
@@ -653,7 +653,7 @@ export interface GitOptions {
653653
hooks?: GitHooks;
654654
/** Optional dedicated logger for git command logging */
655655
logger?: LogChannel;
656-
/** Launches the git process of every run and stream (not the locator's); defaults to Node's `spawn`. Set it to start git from a helper process when the host's own is too large to fork cheaply. */
656+
/** Launches the git process of every run and stream (not the locator's); defaults to `spawnProcess`. Set it to start git from a helper process when the host's own is too large to fork cheaply. */
657657
spawn?: ProcessSpawner;
658658
}
659659

@@ -1588,7 +1588,7 @@ export class Git {
15881588
}
15891589

15901590
const command = await this.path();
1591-
const proc = (this.options.spawn ?? spawn)(command, runArgs, spawnOpts);
1591+
const proc = (this.options.spawn ?? spawnProcess)(command, runArgs, spawnOpts);
15921592

15931593
if (stdin) {
15941594
endStdin(proc.stdin, stdin, stdinEncoding);

‎packages/utils/src/env/node/__tests__/exec.test.ts‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as assert from 'assert';
22
import { spawn } from 'child_process';
33
import * as process from 'process';
44
import type { ProcessSpawner } from '../exec.js';
5-
import { CancelledRunError, run, RunError, runSpawn } from '../exec.js';
5+
import { CancelledRunError, run, RunError, runSpawn, spawnProcess } from '../exec.js';
66

77
// Far past any OS pipe buffer, so the write is still in flight when the child goes away
88
const largeInput = Buffer.alloc(32 * 1024 * 1024, 'x');
@@ -114,3 +114,60 @@ suite('runSpawn spawner Test Suite', () => {
114114
);
115115
});
116116
});
117+
118+
async function countTimers(): Promise<number> {
119+
// Mocha arms its own test timer only once the test returns its promise, so count after yielding to it. Callers
120+
// assert no MORE timers than before: an earlier test's timer may fire in between, but a leak only ever adds one
121+
await Promise.resolve();
122+
return process.getActiveResourcesInfo().filter(r => r === 'Timeout').length;
123+
}
124+
125+
function settled(proc: ReturnType<typeof spawnProcess>): Promise<void> {
126+
return new Promise(resolve => {
127+
proc.once('error', () => {});
128+
proc.once('close', () => resolve());
129+
});
130+
}
131+
132+
suite('spawnProcess Test Suite', () => {
133+
test('spawnProcess leaves no timeout timer behind when the launch fails', async () => {
134+
const before = await countTimers();
135+
// A missing `cwd` fails the launch (ENOENT), which emits `'error'` and `'close'` but never `'exit'`
136+
const proc = spawnProcess(process.execPath, ['-e', ''], {
137+
cwd: `${process.cwd()}/missing-cwd-${Date.now()}`,
138+
timeout: 30000,
139+
});
140+
await settled(proc);
141+
142+
assert.ok((await countTimers()) <= before, 'a timeout timer outlived the process');
143+
});
144+
145+
test('spawnProcess clears its timeout timer once the process exits', async () => {
146+
const before = await countTimers();
147+
const proc = spawnProcess(process.execPath, ['-e', ''], { timeout: 30000 });
148+
await settled(proc);
149+
150+
assert.strictEqual(proc.exitCode, 0);
151+
assert.ok((await countTimers()) <= before, 'a timeout timer outlived the process');
152+
});
153+
154+
test('spawnProcess throws, before spawning, on a timeout Node would reject', () => {
155+
for (const timeout of [1.5, -1, Number.NaN, Number.POSITIVE_INFINITY]) {
156+
assert.throws(
157+
() => spawnProcess(process.execPath, ['-e', ''], { timeout: timeout }),
158+
(ex: unknown) =>
159+
ex instanceof RangeError && (ex as RangeError & { code?: string }).code === 'ERR_OUT_OF_RANGE',
160+
);
161+
}
162+
});
163+
164+
test('runSpawn rejects a timeout Node would reject', async () => {
165+
for (const timeout of [1.5, -1]) {
166+
await assert.rejects(
167+
runSpawn(process.execPath, ['-e', ''], 'utf8', { timeout: timeout }),
168+
(ex: unknown) =>
169+
ex instanceof RangeError && (ex as RangeError & { code?: string }).code === 'ERR_OUT_OF_RANGE',
170+
);
171+
}
172+
});
173+
});

‎packages/utils/src/env/node/exec.ts‎

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ExecFileException, ExecFileOptions } from 'child_process';
1+
import type { ChildProcess, ExecFileException, ExecFileOptions } from 'child_process';
22
import { exec, execFile, spawn } from 'child_process';
33
import type { Stats } from 'fs';
44
import { access, constants } from 'fs';
@@ -226,6 +226,52 @@ export interface ProcessSpawnOptions {
226226
*/
227227
export type ProcessSpawner = (command: string, args: readonly string[], options: ProcessSpawnOptions) => SpawnedProcess;
228228

229+
/**
230+
* The default {@link ProcessSpawner}: Node's `spawn`, but with its `timeout` handled here. Node clears its timeout
231+
* timer only on `'exit'`, which a failed launch (e.g. a missing `cwd`) never emits, so the timer outlives the
232+
* process and keeps Node alive for the full timeout. This mirrors Node's timeout handling but also clears on
233+
* `'close'`, as https://github.com/nodejs/node/pull/65506 does; remove it once the minimum supported Node/Electron
234+
* includes that fix.
235+
*/
236+
export function spawnProcess(command: string, args: readonly string[], options: ProcessSpawnOptions): ChildProcess {
237+
const { timeout, ...spawnOptions } = options;
238+
// Node's own validation, thrown before anything spawns
239+
if (timeout != null && !(Number.isInteger(timeout) && timeout >= 0)) {
240+
const ex = new RangeError(
241+
`The value of "timeout" is out of range. It must be an unsigned integer. Received ${String(timeout)}`,
242+
);
243+
(ex as RangeError & { code: string }).code = 'ERR_OUT_OF_RANGE';
244+
throw ex;
245+
}
246+
247+
const child = spawn(command, args, spawnOptions);
248+
249+
if (timeout != null && timeout > 0) {
250+
let timeoutId: ReturnType<typeof setTimeout> | undefined = setTimeout(() => {
251+
if (timeoutId != null) {
252+
try {
253+
child.kill();
254+
} catch (ex) {
255+
child.emit('error', ex);
256+
}
257+
timeoutId = undefined;
258+
}
259+
}, timeout);
260+
261+
const clear = () => {
262+
if (timeoutId != null) {
263+
clearTimeout(timeoutId);
264+
timeoutId = undefined;
265+
}
266+
};
267+
// `'exit'` keeps Node's timing; `'close'` covers a launch that fails and never exits
268+
child.once('exit', clear);
269+
child.once('close', clear);
270+
}
271+
272+
return child;
273+
}
274+
229275
export interface RunOptions<TEncoding = BufferEncoding | 'buffer'> {
230276
cwd?: string;
231277
readonly env?: Record<string, string | undefined>;
@@ -262,7 +308,7 @@ export interface RunOptions<TEncoding = BufferEncoding | 'buffer'> {
262308
* Use for commands whose failure is expected (e.g. paired with `errors: 'ignore'`).
263309
*/
264310
readonly quiet?: boolean;
265-
/** Launches the process; defaults to Node's `spawn`. Only used by `runSpawn` */
311+
/** Launches the process; defaults to {@link spawnProcess}. Only used by `runSpawn` */
266312
readonly spawn?: ProcessSpawner;
267313
}
268314

@@ -443,7 +489,7 @@ export function runSpawn<T extends string | Buffer>(
443489
const { stdin, stdinEncoding, cancellation, decode, spawn: spawner, ...opts }: RunOptions = options;
444490

445491
const promise = new Promise<RunExitResult | RunResult<T>>((resolve, reject) => {
446-
const proc = (spawner ?? spawn)(command, args, {
492+
const proc = (spawner ?? spawnProcess)(command, args, {
447493
cwd: opts.cwd,
448494
env: opts.env,
449495
// 0 disables it, which the spawner contract spells as absent

0 commit comments

Comments
 (0)