Skip to content

Commit 83e0be6

Browse files
authored
fix(restart): give the stale-pid lsof scan a 5s budget (#117036)
The initial stale-pid scan gave lsof a 2000 ms spawn budget. On macOS hosts with many mounted volumes, lsof can exceed that budget, leaving the stale listener in place and making gateway restart fail on the busy port. Give only the initial lsof scan a 5000 ms default. Keep process and ancestor ps inspection at 2000 ms, and keep the post-kill poll at 400 ms. An explicit findGatewayPidsOnPortSync timeout continues to bound every child process used by that probe. Add regressions for the split defaults and explicit override behavior. This is a bounded mitigation for the residual slow-scan case related to #116950; the broader macOS polling architecture remains tracked by #90548. Reported by @NirvanaCh7. Co-authored-by: guptaishaan <[email protected]>
1 parent 7bae247 commit 83e0be6

3 files changed

Lines changed: 57 additions & 19 deletions

File tree

‎src/infra/restart-stale-pids.test.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,24 @@ describe.skipIf(isWindows)("restart-stale-pids", () => {
272272
expectWarningContaining(`lsof failed during initial stale-pid scan for port 18789: ${code}`);
273273
});
274274

275+
it("finds stale pids when lsof needs seconds to answer", () => {
276+
// macOS hosts with many mounted volumes need seconds per lsof call. When
277+
// the default budget expires first, spawnSync reports ETIMEDOUT and the
278+
// stale gateway is never killed, so the restart fails on the busy port.
279+
const slowLsofMs = 3000;
280+
const stalePid = process.pid + 105;
281+
mockSpawnSync.mockImplementation((command: unknown, _args: unknown, options: unknown) => {
282+
if (command !== "lsof") {
283+
return createLsofResult();
284+
}
285+
const timeout = (options as { timeout?: number }).timeout ?? 0;
286+
return timeout >= slowLsofMs
287+
? createOpenClawBusyResult(stalePid)
288+
: createErrnoResult("ETIMEDOUT", "lsof timed out");
289+
});
290+
expect(findGatewayPidsOnPortSync(18789)).toStrictEqual([stalePid]);
291+
});
292+
275293
it("parses openclaw-gateway pids and excludes the current process", () => {
276294
const stalePid = process.pid + 1;
277295
mockSpawnSync.mockReturnValue({
@@ -525,7 +543,7 @@ describe.skipIf(isWindows)("restart-stale-pids", () => {
525543
expect(findGatewayPidsOnPortSync(18789)).toStrictEqual([]);
526544
});
527545

528-
it("forwards the spawnTimeoutMs argument to spawnSync", () => {
546+
it("uses the explicit timeout for the lsof scan", () => {
529547
mockSpawnSync.mockReturnValue({ error: null, status: 0, stdout: "", stderr: "" });
530548
findGatewayPidsOnPortSync(18789, 400);
531549
const lsofCall = mockCall(mockSpawnSync);
@@ -534,7 +552,7 @@ describe.skipIf(isWindows)("restart-stale-pids", () => {
534552
expect(mockCallRecordArg(mockSpawnSync, 0, 2, "lsof options").timeout).toBe(400);
535553
});
536554

537-
it("uses the caller timeout for macOS ancestor ps probes", () => {
555+
it("uses the explicit timeout for macOS ancestor ps probes", () => {
538556
const origDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
539557
const gatewayParentPid = process.pid + 3151;
540558
Object.defineProperty(process, "platform", { value: "darwin", configurable: true });
@@ -1512,6 +1530,12 @@ describe.skipIf(isWindows)("restart-stale-pids", () => {
15121530
call[0] === "ps" && Array.isArray(call[1]) && (call[1] as unknown[])[0] === "-o",
15131531
)
15141532
.map((call) => (call[2] as { timeout?: number } | undefined)?.timeout);
1533+
const initialLsofTimeout = (
1534+
mockSpawnSync.mock.calls.find((call) => call[0] === "lsof")?.[2] as
1535+
| { timeout?: number }
1536+
| undefined
1537+
)?.timeout;
1538+
expect(initialLsofTimeout).toBe(5000);
15151539
expect(ancestorPsTimeouts).toContain(2000);
15161540
expect(ancestorPsTimeouts).not.toContain(400);
15171541
expect(lsofCall).toBe(3);

‎src/infra/restart-stale-pids.ts‎

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ import {
2121
type WindowsListeningPidsResult,
2222
} from "./windows-port-pids.js";
2323

24-
const SPAWN_TIMEOUT_MS = 2000;
24+
// macOS lsof needs seconds on hosts with many mounted volumes; keep that
25+
// allowance separate so process and ancestor probes retain their tighter bound.
26+
const INITIAL_LSOF_TIMEOUT_MS = 5000;
27+
const PROCESS_INSPECTION_TIMEOUT_MS = 2000;
2528
const STALE_SIGTERM_WAIT_MS = 600;
2629
const STALE_SIGKILL_WAIT_MS = 400;
2730
/**
@@ -31,7 +34,7 @@ const STALE_SIGKILL_WAIT_MS = 400;
3134
* `systemctl restart`). Without this wait the new process races the dying
3235
* process for the port and systemd enters an EADDRINUSE restart loop.
3336
*
34-
* POLL_SPAWN_TIMEOUT_MS is intentionally much shorter than SPAWN_TIMEOUT_MS
37+
* POLL_SPAWN_TIMEOUT_MS is intentionally much shorter than the initial scan
3538
* so that a single slow or hung lsof invocation does not consume the entire
3639
* polling budget. At 400 ms per call, up to five independent lsof attempts
3740
* fit within PORT_FREE_TIMEOUT_MS = 2000 ms, each with a definitive outcome.
@@ -154,7 +157,9 @@ function readParentPidFromPs(pid: number, spawnTimeoutMs: number): number | null
154157
* `/proc/<pid>/status` payloads) — there is no reachable override for
155158
* runtime callers to mutate.
156159
*/
157-
export function getSelfAndAncestorPidsSync(spawnTimeoutMs = SPAWN_TIMEOUT_MS): Set<number> {
160+
export function getSelfAndAncestorPidsSync(
161+
spawnTimeoutMs = PROCESS_INSPECTION_TIMEOUT_MS,
162+
): Set<number> {
158163
const pids = new Set<number>([process.pid]);
159164
const immediateParent = getParentPid();
160165
if (!Number.isFinite(immediateParent) || immediateParent <= 0) {
@@ -202,7 +207,7 @@ function getExcludedGatewayPidsSync(spawnTimeoutMs: number, protectedPid?: numbe
202207
* `MAX_ANCESTOR_WALK_DEPTH` entries from `/proc/<pid>/status`; each read is
203208
* a virtual-filesystem access (no disk I/O, no external process), wrapped
204209
* in try/catch and degrades silently. On macOS the lookup shells out to `ps`
205-
* with the caller's spawn timeout. Windows only uses the in-memory direct
210+
* with the process-inspection timeout. Windows only uses the in-memory direct
206211
* parent from `process.ppid`.
207212
*/
208213
function parseLsofEntries(stdout: string): Array<{ pid: number; cmd?: string }> {
@@ -295,7 +300,7 @@ function parsePidsFromLsofOutput(
295300
* `getSelfAndAncestorPidsSync`).
296301
*/
297302
function filterVerifiedWindowsGatewayPids(rawPids: number[], protectedPid?: number): number[] {
298-
const excluded = getExcludedGatewayPidsSync(SPAWN_TIMEOUT_MS, protectedPid);
303+
const excluded = getExcludedGatewayPidsSync(PROCESS_INSPECTION_TIMEOUT_MS, protectedPid);
299304
return uniqueValues(rawPids)
300305
.filter((pid) => Number.isFinite(pid) && pid > 0 && !excluded.has(pid))
301306
.filter((pid) => {
@@ -309,7 +314,7 @@ function filterVerifiedWindowsGatewayPidsResult(
309314
processArgsResult: (pid: number) => WindowsProcessArgsResult,
310315
protectedPid?: number,
311316
): WindowsListeningPidsResult {
312-
const excluded = getExcludedGatewayPidsSync(SPAWN_TIMEOUT_MS, protectedPid);
317+
const excluded = getExcludedGatewayPidsSync(PROCESS_INSPECTION_TIMEOUT_MS, protectedPid);
313318
const verified: number[] = [];
314319
for (const pid of uniqueValues(rawPids)) {
315320
if (!Number.isFinite(pid) || pid <= 0 || excluded.has(pid)) {
@@ -364,7 +369,8 @@ function findVerifiedWindowsGatewayPidsOnPortResultSync(
364369

365370
function findGatewayPidsOnPortWithProtectedPidSync(
366371
port: number,
367-
spawnTimeoutMs: number,
372+
lsofTimeoutMs: number,
373+
processInspectionTimeoutMs: number,
368374
options?: CleanStaleGatewayProcessesOptions,
369375
): number[] {
370376
if (process.platform === "win32") {
@@ -375,7 +381,7 @@ function findGatewayPidsOnPortWithProtectedPidSync(
375381
const lsof = resolveLsofCommandSync();
376382
const res = spawnSync(lsof, ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], {
377383
encoding: "utf8",
378-
timeout: spawnTimeoutMs,
384+
timeout: lsofTimeoutMs,
379385
});
380386
if (res.error) {
381387
const code = (res.error as NodeJS.ErrnoException).code;
@@ -404,7 +410,7 @@ function findGatewayPidsOnPortWithProtectedPidSync(
404410
}
405411
return parsePidsFromLsofOutput(
406412
res.stdout,
407-
spawnTimeoutMs,
413+
processInspectionTimeoutMs,
408414
resolveProtectedPidAfterEnumeration(options),
409415
);
410416
}
@@ -413,11 +419,14 @@ function findGatewayPidsOnPortWithProtectedPidSync(
413419
* Find PIDs of gateway processes listening on the given port using synchronous lsof.
414420
* Returns only PIDs that belong to openclaw gateway processes (not the current process).
415421
*/
416-
export function findGatewayPidsOnPortSync(
417-
port: number,
418-
spawnTimeoutMs = SPAWN_TIMEOUT_MS,
419-
): number[] {
420-
return findGatewayPidsOnPortWithProtectedPidSync(port, spawnTimeoutMs);
422+
export function findGatewayPidsOnPortSync(port: number, spawnTimeoutMs?: number): number[] {
423+
// An explicit timeout keeps the existing contract: it bounds every child
424+
// process used by this probe. Only the default path splits slow lsof from ps.
425+
return findGatewayPidsOnPortWithProtectedPidSync(
426+
port,
427+
spawnTimeoutMs ?? INITIAL_LSOF_TIMEOUT_MS,
428+
spawnTimeoutMs ?? PROCESS_INSPECTION_TIMEOUT_MS,
429+
);
421430
}
422431

423432
/**
@@ -657,7 +666,12 @@ export function cleanStaleGatewayProcessesSync(
657666
waitForPortFreeSync(port);
658667
return [];
659668
})()
660-
: findGatewayPidsOnPortWithProtectedPidSync(port, SPAWN_TIMEOUT_MS, options);
669+
: findGatewayPidsOnPortWithProtectedPidSync(
670+
port,
671+
INITIAL_LSOF_TIMEOUT_MS,
672+
PROCESS_INSPECTION_TIMEOUT_MS,
673+
options,
674+
);
661675
if (stalePids.length === 0) {
662676
return [];
663677
}

‎src/infra/restart.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ describe.runIf(process.platform !== "win32")("findGatewayPidsOnPortSync", () =>
102102
expect((options as { encoding?: unknown; timeout?: unknown } | undefined)?.encoding).toBe(
103103
"utf8",
104104
);
105-
expect((options as { encoding?: unknown; timeout?: unknown } | undefined)?.timeout).toBe(2000);
105+
expect((options as { encoding?: unknown; timeout?: unknown } | undefined)?.timeout).toBe(5000);
106106
});
107107

108108
it("returns empty when lsof fails", () => {
@@ -171,7 +171,7 @@ describe.runIf(process.platform !== "win32")("cleanStaleGatewayProcessesSync", (
171171
expect((options as { encoding?: unknown; timeout?: unknown } | undefined)?.encoding).toBe(
172172
"utf8",
173173
);
174-
expect((options as { encoding?: unknown; timeout?: unknown } | undefined)?.timeout).toBe(2000);
174+
expect((options as { encoding?: unknown; timeout?: unknown } | undefined)?.timeout).toBe(5000);
175175
expect(killSpy).toHaveBeenCalledWith(stalePid, "SIGTERM");
176176
expect(killSpy).toHaveBeenCalledWith(stalePid, "SIGKILL");
177177
});

0 commit comments

Comments
 (0)