Skip to content

Commit 1e18866

Browse files
shanselmanCopilot
andauthored
fix: classify indeterminate WSL restart outcomes (#1231)
Preserve ambiguous WSL timeout and launch outcomes through automatic gateway repair so detached Core updates are not killed by forced distro termination. Definitive failures still use the existing cold-restart recovery path. Co-authored-by: Copilot App <[email protected]>
1 parent 951c27a commit 1e18866

4 files changed

Lines changed: 124 additions & 11 deletions

File tree

‎src/OpenClaw.Connection/WslCommandRunner.cs‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,15 @@
55

66
namespace OpenClaw.Connection;
77

8-
public sealed record WslCommandResult(int ExitCode, string StandardOutput, string StandardError)
8+
public sealed record WslCommandResult(
9+
int ExitCode,
10+
string StandardOutput,
11+
string StandardError,
12+
bool TimedOut = false,
13+
bool OutcomeIndeterminate = false)
914
{
1015
public bool Success => ExitCode == 0;
16+
public bool IsIndeterminate => TimedOut || OutcomeIndeterminate;
1117
}
1218

1319
public sealed record WslDistroInfo(string Name, string State, int Version);
@@ -153,7 +159,11 @@ private async Task<WslCommandResult> RunProcessAsync(
153159
}
154160
catch (Exception ex)
155161
{
156-
return new WslCommandResult(-1, string.Empty, $"Failed to start wsl.exe: {ex.Message}");
162+
return new WslCommandResult(
163+
-1,
164+
string.Empty,
165+
$"Failed to start wsl.exe: {ex.Message}",
166+
OutcomeIndeterminate: true);
157167
}
158168

159169
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
@@ -172,7 +182,6 @@ private async Task<WslCommandResult> RunProcessAsync(
172182
await process.StandardInput.WriteAsync(
173183
standardInput.AsMemory(),
174184
timeoutCts.Token);
175-
process.StandardInput.Close();
176185
}
177186
catch (IOException)
178187
{
@@ -183,6 +192,12 @@ await process.StandardInput.WriteAsync(
183192
{
184193
// The process closed stdin while failing. Preserve its result.
185194
}
195+
finally
196+
{
197+
try { process.StandardInput.Close(); }
198+
catch (IOException) { }
199+
catch (ObjectDisposedException) { }
200+
}
186201
}
187202

188203
await process.WaitForExitAsync(timeoutCts.Token);
@@ -205,7 +220,7 @@ await process.StandardInput.WriteAsync(
205220
try { stderr = await stderrTask; } catch { stderr = string.Empty; }
206221

207222
return timedOut
208-
? new WslCommandResult(-1, stdout, "wsl.exe timed out")
223+
? new WslCommandResult(-1, stdout, "wsl.exe timed out", TimedOut: true)
209224
: new WslCommandResult(process.ExitCode, stdout, stderr);
210225
}
211226
}

‎src/OpenClaw.Connection/WslGatewayController.cs‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,12 @@ public sealed record WslGatewayControlResult(
1414
WslGatewayControlAction Action,
1515
int ExitCode,
1616
string StandardOutput,
17-
string StandardError)
17+
string StandardError,
18+
bool TimedOut = false,
19+
bool OutcomeIndeterminate = false)
1820
{
1921
public bool Success => ExitCode == 0;
22+
public bool IsIndeterminate => TimedOut || OutcomeIndeterminate;
2023

2124
public string OutputSummary
2225
{
@@ -93,7 +96,9 @@ public async Task<WslGatewayControlResult> RunAsync(
9396
action,
9497
result.ExitCode,
9598
result.StandardOutput,
96-
result.StandardError);
99+
result.StandardError,
100+
result.TimedOut,
101+
result.OutcomeIndeterminate);
97102
}
98103

99104
/// <summary>
@@ -113,12 +118,17 @@ public async Task<WslGatewayControlResult> ForceRestartAsync(
113118
}
114119

115120
var normalizedDistroName = distroName.Trim();
121+
cancellationToken.ThrowIfCancellationRequested();
116122
logger.Info($"Force-terminating WSL distro '{normalizedDistroName}' before restart (in-place restart failed).");
117123

118124
// Terminate is best-effort: a "not running" distro still returns success, and any failure here
119125
// should not stop the cold restart below from surfacing the real error.
120126
// slopwatch-ignore: SW003 Terminate is best-effort; its failure cannot improve the caller state and the restart below is authoritative.
121-
try { await commandRunner.TerminateDistroAsync(normalizedDistroName, cancellationToken).ConfigureAwait(false); }
127+
try
128+
{
129+
cancellationToken.ThrowIfCancellationRequested();
130+
await commandRunner.TerminateDistroAsync(normalizedDistroName, cancellationToken).ConfigureAwait(false);
131+
}
122132
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
123133
catch (Exception ex) { logger.Warn($"Force-terminate of '{normalizedDistroName}' failed (continuing to restart): {ex.Message}"); }
124134

‎src/OpenClaw.Tray.WinUI/Services/ManagedLocalGatewayRepairAdapters.cs‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,27 @@ public async Task<ManagedLocalGatewayRestartResult> RestartAsync(
3131
if (result.Success)
3232
return new ManagedLocalGatewayRestartResult(true);
3333

34+
// An indeterminate result only proves that the host-side wsl.exe client stopped waiting or
35+
// could not start. The in-distro restart (or a detached update handoff that triggered it)
36+
// may still be running. Terminating the whole distro here can kill healthy, long-running
37+
// maintenance, so fail closed and let the normal reconnect/repair loop observe the outcome.
38+
if (result.IsIndeterminate)
39+
{
40+
var unknownDetail = result.TimedOut
41+
? "Gateway restart timed out"
42+
: "Gateway restart outcome is unknown";
43+
return new ManagedLocalGatewayRestartResult(
44+
false,
45+
$"{unknownDetail}; skipped forced distro termination because completion is unknown.");
46+
}
47+
3448
if (!canContinue())
3549
return new ManagedLocalGatewayRestartResult(false, "Gateway changed before forced restart.");
3650

37-
// The in-place restart failed — the distro/VM may be wedged and unable to run an in-distro
38-
// command (an in-distro command also times out to a failure rather than hanging forever).
39-
// Escalate to a host-side terminate + cold restart, which recovers a hung WSL instance
40-
// (ForceRestartAsync logs the terminate).
51+
cancellationToken.ThrowIfCancellationRequested();
52+
53+
// The in-place restart returned a definitive failure. Escalate to a host-side terminate +
54+
// cold restart (ForceRestartAsync logs the terminate).
4155
result = await _controller
4256
.ForceRestartAsync(distroName, cancellationToken)
4357
.ConfigureAwait(false);

‎tests/OpenClaw.Tray.Tests/WslGatewayControllerTests.cs‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,52 @@ public async Task Restarter_WhenInPlaceRestartFails_EscalatesToTerminateAndForce
128128
Assert.Equal(2, runner.InDistroCount); // in-place attempt + post-terminate cold restart
129129
}
130130

131+
[Fact]
132+
public async Task Restarter_WhenInPlaceRestartTimesOut_DoesNotForceTerminate()
133+
{
134+
var runner = new FakeWslCommandRunner
135+
{
136+
Distros = [new WslDistroInfo("OpenClawGateway", "Running", 2)],
137+
Result = new WslCommandResult(
138+
-1,
139+
string.Empty,
140+
"wsl.exe timed out",
141+
TimedOut: true),
142+
};
143+
var controller = new WslGatewayController(runner, NullLogger.Instance);
144+
var restarter = new OpenClawTray.Services.WslManagedLocalGatewayRestarter(controller);
145+
146+
var result = await restarter.RestartAsync("OpenClawGateway", CancellationToken.None);
147+
148+
Assert.False(result.Success);
149+
Assert.Contains("completion is unknown", result.Detail, StringComparison.OrdinalIgnoreCase);
150+
Assert.Equal(0, runner.TerminateCount);
151+
Assert.Equal(1, runner.InDistroCount);
152+
}
153+
154+
[Fact]
155+
public async Task Restarter_WhenInPlaceRestartIsIndeterminate_DoesNotForceTerminate()
156+
{
157+
var runner = new FakeWslCommandRunner
158+
{
159+
Distros = [new WslDistroInfo("OpenClawGateway", "Running", 2)],
160+
Result = new WslCommandResult(
161+
-1,
162+
string.Empty,
163+
"Failed to start wsl.exe",
164+
OutcomeIndeterminate: true),
165+
};
166+
var controller = new WslGatewayController(runner, NullLogger.Instance);
167+
var restarter = new OpenClawTray.Services.WslManagedLocalGatewayRestarter(controller);
168+
169+
var result = await restarter.RestartAsync("OpenClawGateway", CancellationToken.None);
170+
171+
Assert.False(result.Success);
172+
Assert.Contains("outcome is unknown", result.Detail, StringComparison.OrdinalIgnoreCase);
173+
Assert.Equal(0, runner.TerminateCount);
174+
Assert.Equal(1, runner.InDistroCount);
175+
}
176+
131177
[Fact]
132178
public async Task Restarter_WhenBothRestartsFail_ReportsFailure()
133179
{
@@ -172,6 +218,34 @@ public async Task Restarter_GatewayChangesAfterInPlaceFailure_DoesNotForceTermin
172218
Assert.Equal(1, runner.InDistroCount);
173219
}
174220

221+
[Fact]
222+
public async Task Restarter_CancelledBeforeForcedRestart_DoesNotForceTerminate()
223+
{
224+
using var cts = new CancellationTokenSource();
225+
var runner = new FakeWslCommandRunner
226+
{
227+
Distros = [new WslDistroInfo("OpenClawGateway", "Running", 2)],
228+
Result = new WslCommandResult(1, string.Empty, "wedged"),
229+
};
230+
var controller = new WslGatewayController(runner, NullLogger.Instance);
231+
var restarter = new OpenClawTray.Services.WslManagedLocalGatewayRestarter(controller);
232+
var checks = 0;
233+
234+
await Assert.ThrowsAnyAsync<OperationCanceledException>(
235+
() => restarter.RestartAsync(
236+
"OpenClawGateway",
237+
cts.Token,
238+
canContinue: () =>
239+
{
240+
if (++checks == 2)
241+
cts.Cancel();
242+
return true;
243+
}));
244+
245+
Assert.Equal(0, runner.TerminateCount);
246+
Assert.Equal(1, runner.InDistroCount);
247+
}
248+
175249
private sealed class FakeWslCommandRunner : IWslCommandRunner
176250
{
177251
public IReadOnlyList<WslDistroInfo> Distros { get; init; } = [];

0 commit comments

Comments
 (0)