Skip to content

Commit cd91a89

Browse files
authored
fix(gateway): frozen worker processes never resume when the host ps stalls (#123976)
* fix(gateway): bound quiescence identity lookups so thaw cannot hang processIdentity() ran `ps` through execFileSync with no timeout, while its two siblings in the same script (processes(), processStatus()) both pass timeout: 2000. Every thaw path gates on it — resumeProcesses(), the watchdog expiry loop, and REMOTE_WORKSPACE_RESUME_JS all call processIdentity before each SIGCONT — so a host whose `ps` stalls leaves the entire lease frozen with no remaining resumer. SIGSTOP cannot be caught, so those processes never run again and never release their memory. Bring processIdentity to parity with its siblings. Measured with the exported scripts against a fixture whose `ps` stalls on the identity lookup: unbounded resume was still hung when a 20s cap killed it (exit 124); bounded resume fails in 2s with `spawnSync ps ETIMEDOUT`. * fix(gateway): thaw frozen processes before retiring the quiescence watchdog A bounded identity lookup still fails on a stalled host ps. Resume retired the watchdog first, so an aborted sweep left the lease with no resumer at all and the frozen workers stopped forever. Thawing first keeps the watchdog as the recovery owner that clears the lease at expiry; the orphan sweep had the same inverted order. * fix(gateway): keep the quiescence watchdog retrying a stalled identity probe At lease expiry the watchdog ran the same bounded ps lookup and its catch retired the process on the first ETIMEDOUT, so a stall spanning expiry left the frozen workers with no resumer at all. It now re-probes on a bounded schedule and still verifies pid start time before every SIGCONT. * fix(gateway): make the quiescence ps probes killable so their timeout can fire execFileSync's timeout only sends killSignal and then waits for the child to exit, so under the default SIGTERM a ps that ignores it blocked the thaw forever and the added timeout bounded nothing. All three probes now kill the stuck child; verified a TERM-ignoring ps returns in ~2s instead of hanging. * fix(gateway): retire the quiescence watchdog on recovery, not on a retry count A fixed 150-attempt budget reinstated the permanent freeze for any ps stall longer than five minutes. The watchdog now backs off up to 60s and keeps retrying until its sweep completes or the lease file is gone, which is the condition that actually means the workers no longer need a resumer. * fix(gateway): thaw before retiring the watchdog in initial quiescence rollback ClawSweeper on 0162987: the explicit resume path was reordered to thaw before retiring its watchdog, but the initial quiescence sweep's rollback still retired first. A bounded identity probe can throw inside resumeProcesses, and by then the watchdog was already gone, leaving a stopped worker with no remaining recovery owner and the lease still present. Apply the same owner-preserving order to the rollback path, so the last resumer outlives a failed thaw exactly as it does on explicit resume. Production +3/-1: the resume call moves ahead of the watchdog retirement, plus a two-line contract comment. * fix(gateway): harden quiescence recovery after two-phase code review Review fixes on top of the killable-probe change, from one native pass and two cold passes: - The watchdog retried forever on an unparseable lease, leaving an immortal detached process. The pids to resume live in that file, so retrying cannot recover them; an unusable lease is now terminal. - A missing ps binary throws ENOENT too, so the watchdog retired as if the lease were gone while its workers stayed SIGSTOPped. Only the lease path retires it now, discriminated on error.path. - The thaw-first reorder stretched two unlink races. The resume script and the orphan sweep now tolerate a lease that another owner already removed, so a fully successful thaw cannot report the sync as failed. - The stalled-ps recovery test polled 5s against a backoff that doubles to 8s and never resets; widened to outlast the retry ladder. Test-file hygiene, required to land lint-clean: the additions pushed workspace-sync-scripts.test.ts past the repo max-lines cap and introduced two no-promise-executor-return errors, neither of which fires at the PR base. The promise executors now use block bodies, and the file is split by subject rather than suppressed: manifest transaction tests move to workspace-sync-manifest.test.ts, quiescence tests stay. The moved block is byte-identical and no helper crosses the boundary. Proof gap: the gateway vitest project cannot run in this checkout (pre-existing configureFsSafeNative import failure from stale node_modules), so the split and the new tests are verified by git comparison, static analysis, oxlint, and isolated execution of the embedded scripts rather than by a suite run. * test(gateway): clean up stalled probe watchdog Restore the healthy process probe after the expected failure, resume the lease, and wait for the detached watchdog to exit so repeated runs do not leak recovery processes. Co-authored-by: jesse-merhi <[email protected]> * fix(gateway): clean up failed watchdog startup * fix(gateway): release empty quiescence leases
1 parent b5460ee commit cd91a89

3 files changed

Lines changed: 1042 additions & 773 deletions

File tree

‎src/gateway/worker-environments/workspace-quiescence-scripts.ts‎

Lines changed: 54 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const REMOTE_QUIESCENCE_PS_JS = String.raw`function processes() {
33
encoding: "utf8",
44
maxBuffer: 4 * 1024 * 1024,
55
timeout: 2000,
6+
killSignal: "SIGKILL",
67
});
78
const rows = new Map();
89
for (const line of output.split("\n")) {
@@ -28,9 +29,14 @@ function ancestors(rows) {
2829
}
2930
function processIdentity(pid) {
3031
try {
32+
// Identity gates every thaw, and execFileSync's timeout only signals before waiting for
33+
// the child: under the default SIGTERM a ps that ignores it still blocks forever, so every
34+
// probe here must be killable to stay bounded.
3135
const start = require("node:child_process").execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
3236
encoding: "utf8",
3337
maxBuffer: 4096,
38+
timeout: 2000,
39+
killSignal: "SIGKILL",
3440
}).trim();
3541
return start || null;
3642
} catch (error) {
@@ -40,7 +46,7 @@ function processIdentity(pid) {
4046
}
4147
function processStatus(pid) {
4248
try {
43-
const output = childProcess.execFileSync("ps", ["-o", "stat=,lstart=", "-p", String(pid)], { encoding: "utf8", maxBuffer: 4096, timeout: 2000 }).trim();
49+
const output = childProcess.execFileSync("ps", ["-o", "stat=,lstart=", "-p", String(pid)], { encoding: "utf8", maxBuffer: 4096, timeout: 2000, killSignal: "SIGKILL" }).trim();
4450
const match = /^(\S+)\s+(.+)$/u.exec(output);
4551
return match ? { state: match[1], start: match[2] } : null;
4652
} catch (error) {
@@ -153,11 +159,13 @@ for (const name of orphanNames) {
153159
if (!match) continue;
154160
const orphanPath = path.join(leaseDirectory, name);
155161
const lease = parseLease(fs.readFileSync(orphanPath, "utf8"), match[1]);
162+
resumeProcesses(lease.processes);
156163
if (lease.watchdog !== null && processIdentity(lease.watchdog.pid) === lease.watchdog.start) {
157164
try { process.kill(lease.watchdog.pid, "SIGTERM"); } catch (error) { if (!error || (error.code !== "ESRCH" && error.code !== "EPERM")) throw error; }
158165
}
159-
resumeProcesses(lease.processes);
160-
fs.unlinkSync(orphanPath);
166+
// The orphan's own watchdog can resume and unlink first; a lease that is already gone
167+
// is the outcome we wanted, so it must not fail this sweep.
168+
try { fs.unlinkSync(orphanPath); } catch (error) { if (!error || error.code !== "ENOENT") throw error; }
161169
}
162170
writeLease();
163171
const watchdog = childProcess.spawn(
@@ -171,17 +179,21 @@ if (!Number.isSafeInteger(watchdog.pid) || watchdog.pid < 1) {
171179
throw new Error("workspace quiescence watchdog did not start");
172180
}
173181
let watchdogStart = null;
174-
for (let attempt = 0; attempt < 100 && !watchdogStart; attempt += 1) {
175-
watchdogStart = processIdentity(watchdog.pid);
176-
if (!watchdogStart) Atomics.wait(sleeper, 0, 0, 10);
177-
}
178-
if (!watchdogStart) {
179-
try { process.kill(watchdog.pid, "SIGTERM"); } catch {}
180-
fs.unlinkSync(leasePath);
181-
throw new Error("workspace quiescence watchdog identity was not observable");
182+
try {
183+
for (let attempt = 0; attempt < 100 && !watchdogStart; attempt += 1) {
184+
watchdogStart = processIdentity(watchdog.pid);
185+
if (!watchdogStart) Atomics.wait(sleeper, 0, 0, 10);
186+
}
187+
if (!watchdogStart) {
188+
throw new Error("workspace quiescence watchdog identity was not observable");
189+
}
190+
watchdogReference = { pid: watchdog.pid, start: watchdogStart };
191+
writeLease();
192+
} catch (error) {
193+
try { process.kill(watchdog.pid, "SIGTERM"); } catch (killError) { if (!killError || (killError.code !== "ESRCH" && killError.code !== "EPERM")) throw killError; }
194+
try { fs.unlinkSync(leasePath); } catch (unlinkError) { if (!unlinkError || unlinkError.code !== "ENOENT") throw unlinkError; }
195+
throw error;
182196
}
183-
watchdogReference = { pid: watchdog.pid, start: watchdogStart };
184-
writeLease();
185197
let quietScans = 0;
186198
try {
187199
if (sharedHost) {
@@ -232,14 +244,17 @@ try {
232244
throw new Error("worker processes did not reach a quiescent state");
233245
}
234246
} catch (error) {
247+
// Thaw before retiring the watchdog: a bounded identity probe can throw here, and
248+
// retiring first would leave a stopped worker with no remaining resumer.
249+
resumeProcesses([...frozen].map(([pid, start]) => ({ pid, start })));
235250
if (processIdentity(watchdog.pid) === watchdogStart) {
236251
try { process.kill(watchdog.pid, "SIGTERM"); } catch (killError) { if (!killError || (killError.code !== "ESRCH" && killError.code !== "EPERM")) throw killError; }
237252
}
238-
resumeProcesses([...frozen].map(([pid, start]) => ({ pid, start })));
239253
try { fs.unlinkSync(leasePath); } catch (unlinkError) { if (!unlinkError || unlinkError.code !== "ENOENT") throw unlinkError; }
240254
throw error;
241255
}
242256
function watchdogMain(watchedLeasePath, watchedNonce) {
257+
let retryDelayMs = 1000;
243258
const check = () => {
244259
try {
245260
const watchdogFs = require("node:fs");
@@ -281,7 +296,18 @@ function watchdogMain(watchedLeasePath, watchedNonce) {
281296
}
282297
watchdogFs.unlinkSync(watchedLeasePath);
283298
} catch (error) {
284-
if (!error || error.code !== "ENOENT") process.exitCode = 1;
299+
// Only the lease disappearing or being unusable retires this watchdog. A missing ps also throws
300+
// ENOENT, and treating that as "someone else finished" would exit with the workers
301+
// still stopped, which is the freeze this loop exists to prevent.
302+
if (error && error.code === "ENOENT" && error.path === watchedLeasePath) return;
303+
// An unreadable lease is terminal: the pids to resume live in that file, so retrying
304+
// cannot recover them and would leave this detached process alive forever.
305+
if (error instanceof SyntaxError) return;
306+
// Otherwise this is the lease's last resumer, so it retries with backoff until the sweep
307+
// completes or the lease file is gone. Any attempt cap would just re-create the permanent
308+
// freeze for a longer stall; whoever removes the lease retires this watchdog next tick.
309+
setTimeout(check, retryDelayMs);
310+
retryDelayMs = Math.min(retryDelayMs * 2, 60000);
285311
}
286312
};
287313
check();
@@ -421,12 +447,21 @@ try { raw = fs.readFileSync(leasePath, "utf8"); } catch (error) {
421447
${REMOTE_QUIESCENCE_PS_JS}
422448
${REMOTE_QUIESCENCE_LEASE_JS}
423449
const input = parseLease(raw, nonce);
424-
if (input.watchdog !== null && processIdentity(input.watchdog.pid) === input.watchdog.start) {
425-
try { process.kill(input.watchdog.pid, "SIGTERM"); } catch (error) { if (!error || (error.code !== "ESRCH" && error.code !== "EPERM")) throw error; }
426-
}
450+
// Thaw before retiring the watchdog: a bounded identity lookup can still fail, and
451+
// retiring the last resumer first would strand whatever the aborted sweep never reached.
427452
for (const entry of input.processes) {
428453
if (processIdentity(entry.pid) !== entry.start) continue;
429454
try { process.kill(entry.pid, "SIGCONT"); } catch (error) { if (!error || (error.code !== "ESRCH" && error.code !== "EPERM")) throw error; }
430455
}
431-
fs.unlinkSync(leasePath);
456+
let watchdogStart = null;
457+
try { if (input.watchdog !== null) watchdogStart = processIdentity(input.watchdog.pid); } catch (error) {
458+
// An empty shared-host lease has nothing to strand, so ps cannot block its release.
459+
if (input.processes.length > 0) throw error;
460+
}
461+
if (input.watchdog !== null && watchdogStart === input.watchdog.start) {
462+
try { process.kill(input.watchdog.pid, "SIGTERM"); } catch (error) { if (!error || (error.code !== "ESRCH" && error.code !== "EPERM")) throw error; }
463+
}
464+
// The watchdog stays alive across the whole resume loop now, so it can win the unlink race.
465+
// Everything is thawed either way; a missing lease must not fail the sync.
466+
try { fs.unlinkSync(leasePath); } catch (error) { if (!error || error.code !== "ENOENT") throw error; }
432467
`;

0 commit comments

Comments
 (0)