Skip to content

Commit 8987e93

Browse files
authored
fix(parallels): recover Windows poll transport failures (#118479)
1 parent ed8881c commit 8987e93

3 files changed

Lines changed: 183 additions & 28 deletions

File tree

‎scripts/e2e/parallels/guest-transports.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ function throwIfParallelsVmStopped(label: string, result: CommandResult): void {
9292
const POSIX_GUEST_SCRIPT_CLEANUP_TIMEOUT_MS = 30_000;
9393
const POSIX_BACKGROUND_LOG_MAX_BYTES = 8 * 1024 * 1024;
9494
const WINDOWS_BACKGROUND_LOG_MAX_BYTES = 8 * 1024 * 1024;
95+
const WINDOWS_BACKGROUND_CLEANUP_RESERVE_MS = 120_000;
96+
const WINDOWS_BACKGROUND_POLL_FAILURE_LIMIT = 3;
9597

9698
function appendCommandResult(phases: PhaseRunner, result: CommandResult): void {
9799
phases.append(result.stdout);
@@ -324,7 +326,22 @@ export async function runWindowsBackgroundPowerShell(
324326
const windowsLogPath = `%WINDIR%\\Temp\\${guestRunDir}\\run.log`;
325327
const backgroundExitPrefix = `__OPENCLAW_BACKGROUND_EXIT__:${nonce}:`;
326328
const backgroundDoneMarker = `__OPENCLAW_BACKGROUND_DONE__:${nonce}`;
327-
const deadline = Date.now() + options.timeoutMs;
329+
// PhaseRunner cannot cancel an in-flight callback. Keep cleanup inside the
330+
// helper budget so a timed-out lane cannot overlap the next snapshot restore.
331+
const deadline =
332+
Date.now() + Math.max(1, options.timeoutMs - WINDOWS_BACKGROUND_CLEANUP_RESERVE_MS);
333+
let consecutivePollFailures = 0;
334+
const recordPollFailure = (stage: string, result: CommandResult): void => {
335+
consecutivePollFailures++;
336+
options.onLaunchRetry?.(
337+
`${options.label} ${stage} transport failure ${consecutivePollFailures}/${WINDOWS_BACKGROUND_POLL_FAILURE_LIMIT} (exit ${result.status})`,
338+
);
339+
if (consecutivePollFailures >= WINDOWS_BACKGROUND_POLL_FAILURE_LIMIT) {
340+
throw new Error(
341+
`${options.label} ${stage} failed after ${WINDOWS_BACKGROUND_POLL_FAILURE_LIMIT} consecutive guest transport errors`,
342+
);
343+
}
344+
};
328345
const pathsScript = `$runDir = Join-Path (Join-Path $env:WINDIR 'Temp\\openclaw-parallels') ${psSingleQuote(nonce)}
329346
$scriptPath = Join-Path $runDir 'run.ps1'
330347
$logPath = Join-Path $runDir 'run.log'
@@ -506,9 +523,18 @@ cmd.exe /d /s /c start "" /b powershell.exe -NoProfile -ExecutionPolicy Bypass -
506523
appendOutput(append, doneProbe);
507524
throwIfParallelsVmStopped(options.label, doneProbe);
508525
if (doneProbe.stdout.split(/\r?\n/u).some((line) => line.trim() === "done")) {
526+
consecutivePollFailures = 0;
509527
doneFileSeen = true;
510528
completedLogDrainDeadline ||= Date.now() + completedLogDrainGraceMs;
529+
} else if (
530+
doneProbe.status === 0 &&
531+
doneProbe.stdout.split(/\r?\n/u).some((line) => line.trim() === "wait")
532+
) {
533+
consecutivePollFailures = 0;
534+
await sleep(pollIntervalMs);
535+
continue;
511536
} else {
537+
recordPollFailure("done poll", doneProbe);
512538
await sleep(pollIntervalMs);
513539
continue;
514540
}
@@ -529,13 +555,15 @@ cmd.exe /d /s /c start "" /b powershell.exe -NoProfile -ExecutionPolicy Bypass -
529555
appendOutput(append, poll);
530556
throwIfParallelsVmStopped(options.label, poll);
531557
if (hasControlLine(poll.stdout, backgroundDoneMarker)) {
558+
consecutivePollFailures = 0;
532559
doneSeen = true;
533560
const backgroundExit = findControlValue(poll.stdout, backgroundExitPrefix) ?? "0";
534561
if (backgroundExit !== "0" || (poll.status !== 0 && poll.status !== 124)) {
535562
throw new Error(`${options.label} failed`);
536563
}
537564
return;
538565
}
566+
recordPollFailure("log poll", poll);
539567
await sleep(Math.min(pollIntervalMs, 100));
540568
}
541569
if (doneSeen) {

‎scripts/e2e/parallels/host-command.ts‎

Lines changed: 73 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -79,17 +79,33 @@ function signalHostCommandProcess(pid: number | undefined, signal: NodeJS.Signal
7979
if (!pid) {
8080
return;
8181
}
82-
try {
83-
if (process.platform === "win32") {
82+
if (process.platform === "win32") {
83+
try {
8484
process.kill(pid, signal);
85-
} else {
86-
process.kill(-pid, signal);
85+
} catch (error) {
86+
const code = (error as NodeJS.ErrnoException).code;
87+
if (code !== "ESRCH") {
88+
warn(`failed to send ${signal} to host command process ${pid}: ${code ?? String(error)}`);
89+
}
8790
}
91+
return;
92+
}
93+
try {
94+
process.kill(-pid, signal);
8895
} catch (error) {
8996
const code = (error as NodeJS.ErrnoException).code;
90-
if (code !== "ESRCH") {
97+
if (code === "ESRCH") {
98+
return;
99+
}
100+
try {
101+
process.kill(pid, signal);
102+
} catch (fallbackError) {
103+
const fallbackCode = (fallbackError as NodeJS.ErrnoException).code;
104+
if (fallbackCode === "ESRCH") {
105+
return;
106+
}
91107
warn(
92-
`failed to send ${signal} to timed host command process ${pid}: ${code ?? String(error)}`,
108+
`failed to send ${signal} to host command process ${pid}: group ${code ?? String(error)}, leader ${fallbackCode ?? String(fallbackError)}`,
93109
);
94110
}
95111
}
@@ -115,8 +131,8 @@ writeSync(
115131
);
116132
117133
let timedOut = false;
118-
let killTimer;
119134
let killDeadlineAt = 0;
135+
let timedOutCleanupStarted = false;
120136
let outputExceeded = false;
121137
let forwardedSignal;
122138
let forwardedSignalKillTimer;
@@ -137,9 +153,17 @@ function signalGroup(signal) {
137153
}
138154
try {
139155
process.kill(-child.pid, signal);
156+
return;
140157
} catch (error) {
141-
if (error && error.code !== "ESRCH") {
142-
process.stderr.write("failed to send " + signal + " to timed host command process " + child.pid + ": " + (error.code || String(error)) + "\n");
158+
if (error && error.code === "ESRCH") {
159+
return;
160+
}
161+
try {
162+
process.kill(child.pid, signal);
163+
} catch (fallbackError) {
164+
if (!fallbackError || fallbackError.code !== "ESRCH") {
165+
process.stderr.write("failed to send " + signal + " to host command process " + child.pid + ": group " + ((error && error.code) || String(error)) + ", leader " + ((fallbackError && fallbackError.code) || String(fallbackError)) + "\n");
166+
}
143167
}
144168
}
145169
}
@@ -152,19 +176,31 @@ function groupAlive() {
152176
process.kill(-child.pid, 0);
153177
return true;
154178
} catch (error) {
155-
return Boolean(error && error.code === "EPERM");
179+
if (!error || error.code !== "EPERM") {
180+
return false;
181+
}
182+
if (child.exitCode !== null || child.signalCode !== null) {
183+
return false;
184+
}
185+
try {
186+
process.kill(child.pid, 0);
187+
return true;
188+
} catch {
189+
return false;
190+
}
156191
}
157192
}
158193
159194
function finishTimedOut() {
160-
if (killTimer) {
161-
clearTimeout(killTimer);
162-
}
163195
writeSync(3, ${JSON.stringify(HOST_COMMAND_TIMEOUT_PREFIX)} + "{}\n");
164196
process.exit(124);
165197
}
166198
167199
function finishTimedOutAfterCleanup() {
200+
if (timedOutCleanupStarted) {
201+
return;
202+
}
203+
timedOutCleanupStarted = true;
168204
if (!groupAlive()) {
169205
finishTimedOut();
170206
return;
@@ -273,8 +309,7 @@ const timeout = setTimeout(() => {
273309
timedOut = true;
274310
signalGroup("SIGTERM");
275311
killDeadlineAt = Date.now() + payload.timeoutKillGraceMs;
276-
killTimer = setTimeout(() => signalGroup("SIGKILL"), payload.timeoutKillGraceMs);
277-
killTimer.unref();
312+
finishTimedOutAfterCleanup();
278313
}, payload.timeoutMs);
279314
timeout.unref();
280315
@@ -287,9 +322,6 @@ child.stdin.on("error", (error) => {
287322
});
288323
child.on("error", (error) => {
289324
clearTimeout(timeout);
290-
if (killTimer) {
291-
clearTimeout(killTimer);
292-
}
293325
writeSync(
294326
3,
295327
${JSON.stringify(HOST_COMMAND_SPAWN_ERROR_PREFIX)} + JSON.stringify({
@@ -310,9 +342,6 @@ child.on("close", (code, signal) => {
310342
finishTimedOutAfterCleanup();
311343
return;
312344
}
313-
if (killTimer) {
314-
clearTimeout(killTimer);
315-
}
316345
if (outputExceeded) {
317346
process.exit(1);
318347
}
@@ -583,7 +612,18 @@ export async function runStreaming(
583612
process.kill(-childPid, 0);
584613
return true;
585614
} catch (error) {
586-
return (error as NodeJS.ErrnoException).code === "EPERM";
615+
if ((error as NodeJS.ErrnoException).code !== "EPERM") {
616+
return false;
617+
}
618+
if (child.exitCode !== null || child.signalCode !== null) {
619+
return false;
620+
}
621+
try {
622+
process.kill(childPid, 0);
623+
return true;
624+
} catch {
625+
return false;
626+
}
587627
}
588628
};
589629
const waitForStreamingProcessGroupExit = async (timeoutBudgetMs: number): Promise<boolean> => {
@@ -703,6 +743,7 @@ export async function runStreaming(
703743
let timedOut = false;
704744
let killTimer: NodeJS.Timeout | undefined;
705745
let killDeadlineAt = 0;
746+
let forceKillSent = false;
706747
const waitForStreamingTimeoutCleanup = async (): Promise<void> => {
707748
if (!detached) {
708749
signalStreamingChild("SIGKILL");
@@ -712,7 +753,12 @@ export async function runStreaming(
712753
if (remainingGraceMs > 0) {
713754
await waitForStreamingProcessGroupExit(remainingGraceMs);
714755
}
715-
if (streamingProcessGroupAlive()) {
756+
if (streamingProcessGroupAlive() && !forceKillSent) {
757+
if (killTimer) {
758+
clearTimeout(killTimer);
759+
killTimer = undefined;
760+
}
761+
forceKillSent = true;
716762
signalStreamingChild("SIGKILL");
717763
await waitForStreamingProcessGroupExit(HOST_COMMAND_POST_FORCE_KILL_WAIT_MS);
718764
}
@@ -724,10 +770,10 @@ export async function runStreaming(
724770
timedOut = true;
725771
signalHostCommandProcess(childPid, "SIGTERM");
726772
killDeadlineAt = Date.now() + HOST_COMMAND_STREAMING_TIMEOUT_KILL_GRACE_MS;
727-
killTimer = setTimeout(
728-
() => signalHostCommandProcess(childPid, "SIGKILL"),
729-
HOST_COMMAND_STREAMING_TIMEOUT_KILL_GRACE_MS,
730-
);
773+
killTimer = setTimeout(() => {
774+
forceKillSent = true;
775+
signalHostCommandProcess(childPid, "SIGKILL");
776+
}, HOST_COMMAND_STREAMING_TIMEOUT_KILL_GRACE_MS);
731777
killTimer.unref();
732778
}, timeoutMs);
733779

‎test/scripts/parallels-smoke-model.test.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1621,6 +1621,41 @@ kill -TERM "$$"`,
16211621
expect(runCommand).toHaveBeenCalledTimes(1);
16221622
});
16231623

1624+
it("fails boundedly when Windows background polling loses guest transport", async () => {
1625+
const retries: string[] = [];
1626+
let donePolls = 0;
1627+
const runCommand = vi.fn((_command: string, args: string[], options?: { input?: string }) => {
1628+
const command = args.at(-1) ?? "";
1629+
if (options?.input) {
1630+
return { status: 0, stderr: "", stdout: "" };
1631+
}
1632+
if (args.includes("--current-user")) {
1633+
return { status: 0, stderr: "", stdout: "started\n" };
1634+
}
1635+
if (args.includes("cmd.exe") && command.includes("echo wait")) {
1636+
donePolls++;
1637+
return { status: 124, stderr: "", stdout: "" };
1638+
}
1639+
return { status: 0, stderr: "", stdout: "" };
1640+
});
1641+
1642+
await expect(
1643+
runWindowsBackgroundPowerShell({
1644+
label: "ref-onboard",
1645+
onLaunchRetry: (message) => retries.push(message),
1646+
pollIntervalMs: 1,
1647+
runCommand,
1648+
script: "Write-Output ok",
1649+
timeoutMs: 720_000,
1650+
vmName: "Windows 11",
1651+
}),
1652+
).rejects.toThrow("ref-onboard done poll failed after 3 consecutive guest transport errors");
1653+
1654+
expect(donePolls).toBe(3);
1655+
expect(retries).toHaveLength(3);
1656+
expect(retries.at(-1)).toContain("transport failure 3/3");
1657+
});
1658+
16241659
it("returns timed-out host command status when check is disabled", () => {
16251660
const result = runNode("process.stdout.write('partial'); setTimeout(() => {}, 1000);", {
16261661
check: false,
@@ -1708,6 +1743,52 @@ kill -TERM "$$"`,
17081743
},
17091744
);
17101745

1746+
it.runIf(process.platform !== "win32")(
1747+
"settles timed host commands when an escaped descendant retains child pipes",
1748+
() => {
1749+
const tempDir = makeTempDir(tempDirs, "openclaw-parallels-host-command-pipes-");
1750+
const grandchildPidPath = join(tempDir, "grandchild.pid");
1751+
let grandchildPid = 0;
1752+
const grandchildScript = [
1753+
"const { writeFileSync } = require('node:fs');",
1754+
"writeFileSync(process.env.GRANDCHILD_PID_PATH, String(process.pid));",
1755+
"setInterval(() => {}, 1000);",
1756+
].join("\n");
1757+
const parentScript = [
1758+
"const { spawn } = require('node:child_process');",
1759+
`const child = spawn(process.execPath, ['-e', ${JSON.stringify(grandchildScript)}], {`,
1760+
" detached: true,",
1761+
" env: process.env,",
1762+
" stdio: ['ignore', 'inherit', 'inherit'],",
1763+
"});",
1764+
"child.unref();",
1765+
"setInterval(() => {}, 1000);",
1766+
].join("\n");
1767+
const startedAt = Date.now();
1768+
1769+
try {
1770+
const result = run(process.execPath, ["-e", parentScript], {
1771+
check: false,
1772+
env: {
1773+
...process.env,
1774+
GRANDCHILD_PID_PATH: grandchildPidPath,
1775+
},
1776+
quiet: true,
1777+
timeoutMs: 100,
1778+
});
1779+
1780+
expect(result.status).toBe(124);
1781+
expect(Date.now() - startedAt).toBeLessThan(2_000);
1782+
grandchildPid = Number.parseInt(readFileSync(grandchildPidPath, "utf8"), 10);
1783+
expect(Number.isInteger(grandchildPid)).toBe(true);
1784+
} finally {
1785+
if (grandchildPid && isProcessAlive(grandchildPid)) {
1786+
process.kill(-grandchildPid, "SIGKILL");
1787+
}
1788+
}
1789+
},
1790+
);
1791+
17111792
it.runIf(process.platform !== "win32")(
17121793
"reaps externally signaled timed host command descendants",
17131794
async () => {

0 commit comments

Comments
 (0)