Skip to content

Commit 9c48c15

Browse files
committed
fix(setup): preserve trailing command output while bounding inherited-pipe waits
CommandRunner previously always applied a short bounded grace to the stdout/stderr drain after the child exited, which could truncate trailing output on high-volume commands. Await full output-close on the normal path so complete output is preserved, and apply the bounded grace only on timeout cleanup or when a caller opts in via allowInheritedPipeHandleEscape for WSL inspection commands whose descendants can hold inherited pipe handles open. Opt the wsl.exe --list/--verbose inspection callers into the bounded escape (CleanupStaleDistroStep, CreateWslInstanceStep, ExistingConfigDetector, StartGatewayStep). Add regression tests: high-volume stdout/stderr drain with trailing markers on the default path, a bounded-timeout test, and update the pipe-holder test to use the opt-in. Fixes #1194 Co-authored-by: Copilot App <[email protected]>
1 parent ccd64bb commit 9c48c15

9 files changed

Lines changed: 134 additions & 23 deletions

File tree

‎src/OpenClaw.SetupEngine/CleanupStaleDistroStep.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,12 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
2424
if (!DistroInstallPathPolicy.TryGetManagedInstallPath(ctx.LocalDataDir, distro, out var wslDir, out var pathError))
2525
return StepResult.Terminal(pathError);
2626

27-
var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
27+
var list = await ctx.Commands.RunAsync(
28+
WslConstants.WslExePath,
29+
["--list", "--quiet"],
30+
TimeSpan.FromSeconds(15),
31+
ct: ct,
32+
allowInheritedPipeHandleEscape: true);
2833
if (list.ExitCode != 0)
2934
return StepResult.Ok("WSL not available or no distros - nothing to clean");
3035

‎src/OpenClaw.SetupEngine/CommandRunner.cs‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ Task<CommandResult> RunAsync(
1717
string? workingDirectory = null,
1818
string? stdinInput = null,
1919
CancellationToken ct = default,
20-
Stream? stdinStream = null);
20+
Stream? stdinStream = null,
21+
bool allowInheritedPipeHandleEscape = false);
2122

2223
/// <summary>
2324
/// Run a command inside a WSL distro.
@@ -86,7 +87,8 @@ public async Task<CommandResult> RunAsync(
8687
string? workingDirectory = null,
8788
string? stdinInput = null,
8889
CancellationToken ct = default,
89-
Stream? stdinStream = null)
90+
Stream? stdinStream = null,
91+
bool allowInheritedPipeHandleEscape = false)
9092
{
9193
ArgumentNullException.ThrowIfNull(executable);
9294
ArgumentNullException.ThrowIfNull(arguments);
@@ -192,12 +194,17 @@ public async Task<CommandResult> RunAsync(
192194
throw;
193195
}
194196

195-
// A surviving descendant can keep inherited pipe handles open after the child
196-
// exits. Preserve output already in flight without charging the command's full
197-
// timeout to an EOF that may never arrive.
198-
await Task.WhenAny(
199-
Task.WhenAll(stdoutClosed.Task, stderrClosed.Task),
200-
Task.Delay(s_outputDrainGrace));
197+
var outputClosed = Task.WhenAll(stdoutClosed.Task, stderrClosed.Task);
198+
if (timedOut || allowInheritedPipeHandleEscape)
199+
{
200+
// Some WSL inspection commands can leave a descendant holding inherited
201+
// pipe handles. Bound only those known waits, plus timeout cleanup.
202+
await Task.WhenAny(outputClosed, Task.Delay(s_outputDrainGrace));
203+
}
204+
else
205+
{
206+
await outputClosed;
207+
}
201208

202209
sw.Stop();
203210
var result = new CommandResult(

‎src/OpenClaw.SetupEngine/CreateWslInstanceStep.cs‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,12 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
4141

4242
ctx.Logger.Info($"Creating clean app-owned WSL distro '{distro}' from '{baseDistro}' at '{installPath}'");
4343

44-
var existing = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
44+
var existing = await ctx.Commands.RunAsync(
45+
WslConstants.WslExePath,
46+
["--list", "--quiet"],
47+
TimeSpan.FromSeconds(15),
48+
ct: ct,
49+
allowInheritedPipeHandleEscape: true);
4550
if (existing.ExitCode != 0)
4651
return StepResult.Fail($"Failed to list WSL distros before creating '{distro}': {existing.Stderr}");
4752

@@ -108,7 +113,12 @@ private static StepResult EnsureInstallPathReady(string installPath)
108113

109114
private static async Task<StepResult> VerifyFreshDistro(SetupContext ctx, string distro, string installPath, CancellationToken ct)
110115
{
111-
var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
116+
var list = await ctx.Commands.RunAsync(
117+
WslConstants.WslExePath,
118+
["--list", "--quiet"],
119+
TimeSpan.FromSeconds(15),
120+
ct: ct,
121+
allowInheritedPipeHandleEscape: true);
112122
if (list.ExitCode != 0 || !WslInstallSupport.ContainsDistro(list.Stdout, distro))
113123
{
114124
var environmentIssue = await PreflightWslStep.DetectEnvironmentIssueAsync(ctx, ct);
@@ -120,7 +130,8 @@ private static async Task<StepResult> VerifyFreshDistro(SetupContext ctx, string
120130
WslConstants.WslExePath,
121131
["--list", "--verbose"],
122132
DistroVersionVerificationTimeout,
123-
ct: ct);
133+
ct: ct,
134+
allowInheritedPipeHandleEscape: true);
124135
if (verbose.ExitCode != 0 || !WslInstallSupport.TryGetDistroVersion(verbose.Stdout, distro, out var version))
125136
return StepResult.Fail($"Fresh WSL install registered '{distro}', but setup could not verify it is WSL2.");
126137

@@ -164,7 +175,12 @@ private static async Task<string> CleanupPartialInstall(SetupContext ctx, string
164175
{
165176
var cleanupErrors = new List<string>();
166177
var installPathExists = Directory.Exists(installPath) || File.Exists(installPath);
167-
var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
178+
var list = await ctx.Commands.RunAsync(
179+
WslConstants.WslExePath,
180+
["--list", "--quiet"],
181+
TimeSpan.FromSeconds(15),
182+
ct: ct,
183+
allowInheritedPipeHandleEscape: true);
168184
var registrationStateKnown = list.ExitCode == 0;
169185
var distroExists = registrationStateKnown && WslInstallSupport.ContainsDistro(list.Stdout, distro);
170186
var canDeleteInstallPath = registrationStateKnown && !distroExists;

‎src/OpenClaw.SetupEngine/ExistingConfigDetector.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@ public static ExistingConfig Detect(string dataDir, string targetDistroName)
3131

3232
var logger = new SetupLogger(filePath: null, LogLevel.Warn);
3333
var result = new CommandRunner(logger)
34-
.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(5))
34+
.RunAsync(
35+
WslConstants.WslExePath,
36+
["--list", "--quiet"],
37+
TimeSpan.FromSeconds(5),
38+
allowInheritedPipeHandleEscape: true)
3539
.GetAwaiter()
3640
.GetResult();
3741
var hasDistro = InterpretDistroList(result, targetDistroName);

‎src/OpenClaw.SetupEngine/PreflightWslStep.cs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ public static async Task<WslViabilityResult> InspectAsync(
4848
WslConstants.WslExePath,
4949
["--version"],
5050
TimeSpan.FromSeconds(5),
51-
ct: ct);
51+
ct: ct,
52+
allowInheritedPipeHandleEscape: true);
5253
}
5354
catch (Exception ex) when (ex is not OperationCanceledException)
5455
{
@@ -106,7 +107,8 @@ public static async Task<WslViabilityResult> InspectAsync(
106107
WslConstants.WslExePath,
107108
["--status"],
108109
TimeSpan.FromSeconds(10),
109-
ct: ct);
110+
ct: ct,
111+
allowInheritedPipeHandleEscape: true);
110112
}
111113
catch (Exception ex) when (ex is not OperationCanceledException)
112114
{
@@ -186,7 +188,8 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
186188
WslConstants.WslExePath,
187189
["--status"],
188190
TimeSpan.FromSeconds(10),
189-
ct: ct);
191+
ct: ct,
192+
allowInheritedPipeHandleEscape: true);
190193
var combined = $"{status.Stdout}\n{status.Stderr}";
191194
if (!WslInstallSupport.TryGetEnvironmentIssue(combined, out var message))
192195
return null;
@@ -230,7 +233,8 @@ internal static async Task<StepResult> InstallWslPlatformAsync(SetupContext ctx,
230233
WslConstants.WslExePath,
231234
["--version"],
232235
TimeSpan.FromSeconds(5),
233-
ct: ct);
236+
ct: ct,
237+
allowInheritedPipeHandleEscape: true);
234238
if (probe.ExitCode != 0 || WslViabilityInspector.LooksUnavailable(probe))
235239
{
236240
return StepResult.Terminal(

‎src/OpenClaw.SetupEngine/StartGatewayStep.cs‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,15 +148,25 @@ public override async Task RollbackAsync(SetupContext ctx, CancellationToken ct)
148148
var distro = ctx.DistroName!;
149149

150150
// Check if distro is running before trying systemctl stop
151-
var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct);
151+
var list = await ctx.Commands.RunAsync(
152+
WslConstants.WslExePath,
153+
["--list", "--quiet"],
154+
TimeSpan.FromSeconds(15),
155+
ct: ct,
156+
allowInheritedPipeHandleEscape: true);
152157
if (!WslInstallSupport.ContainsDistro(list.Stdout, distro))
153158
{
154159
ctx.Logger.Info("[Uninstall] Distro not registered — skipping gateway stop");
155160
return;
156161
}
157162

158163
// Check distro state — only stop if Running
159-
var verbose = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--verbose"], TimeSpan.FromSeconds(15), ct: ct);
164+
var verbose = await ctx.Commands.RunAsync(
165+
WslConstants.WslExePath,
166+
["--list", "--verbose"],
167+
TimeSpan.FromSeconds(15),
168+
ct: ct,
169+
allowInheritedPipeHandleEscape: true);
160170
var isRunning = WslInstallSupport.Normalize(verbose.Stdout)
161171
.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
162172
.Any(line => line.Contains(distro, StringComparison.OrdinalIgnoreCase)

‎tests/OpenClaw.SetupEngine.Tests/CommandRunnerTests.cs‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,23 @@ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => runner.RunAsync(
4141
Assert.InRange(stopwatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(5));
4242
}
4343

44+
[Fact]
45+
public async Task RunAsync_ProcessTimeoutRemainsBounded()
46+
{
47+
var runner = CreateRunner();
48+
var (executable, arguments) = SleepingCommand();
49+
var stopwatch = Stopwatch.StartNew();
50+
51+
var result = await runner.RunAsync(
52+
executable,
53+
arguments,
54+
TimeSpan.FromMilliseconds(250));
55+
56+
Assert.True(result.TimedOut);
57+
Assert.Equal(-1, result.ExitCode);
58+
Assert.InRange(stopwatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(5));
59+
}
60+
4461
[Fact]
4562
public async Task RunAsync_StreamStdinPreservesBinaryBytes()
4663
{
@@ -87,13 +104,36 @@ public async Task RunAsync_ReturnsWhenDescendantKeepsOutputPipesOpen()
87104
var (executable, arguments) = ExitsLeavingPipeHolderCommand();
88105
var stopwatch = Stopwatch.StartNew();
89106

90-
var result = await runner.RunAsync(executable, arguments, TimeSpan.FromSeconds(30));
107+
var result = await runner.RunAsync(
108+
executable,
109+
arguments,
110+
TimeSpan.FromSeconds(30),
111+
allowInheritedPipeHandleEscape: true);
91112

92113
Assert.False(result.TimedOut);
93114
Assert.Equal(0, result.ExitCode);
94115
Assert.InRange(stopwatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(5));
95116
}
96117

118+
[Fact]
119+
public async Task RunAsync_DrainsHighVolumeStdoutAndStderrThroughTrailingMarkers()
120+
{
121+
const int lineCount = 8_000;
122+
var (executable, arguments) = HighVolumeOutputCommand(lineCount);
123+
124+
var result = await CreateRunner().RunAsync(
125+
executable,
126+
arguments,
127+
TimeSpan.FromSeconds(30));
128+
129+
Assert.False(result.TimedOut);
130+
Assert.Equal(0, result.ExitCode);
131+
Assert.Equal(lineCount, CountLinesStartingWith(result.Stdout, "stdout-"));
132+
Assert.Equal(lineCount, CountLinesStartingWith(result.Stderr, "stderr-"));
133+
Assert.EndsWith($"STDOUT_MARKER{Environment.NewLine}", result.Stdout, StringComparison.Ordinal);
134+
Assert.EndsWith($"STDERR_MARKER{Environment.NewLine}", result.Stderr, StringComparison.Ordinal);
135+
}
136+
97137
private static CommandRunner CreateRunner()
98138
=> new(new SetupLogger(filePath: null, LogLevel.Trace));
99139

@@ -107,6 +147,29 @@ private static (string Executable, string[] Arguments) SleepingCommand()
107147
? ("cmd.exe", ["/d", "/s", "/c", "ping 127.0.0.1 -n 30 >nul"])
108148
: ("/bin/sh", ["-c", "sleep 30"]);
109149

150+
private static (string Executable, string[] Arguments) HighVolumeOutputCommand(int lineCount)
151+
{
152+
if (!OperatingSystem.IsWindows())
153+
{
154+
var shellScript =
155+
$"i=0; while [ $i -lt {lineCount} ]; do echo stdout-$i; echo stderr-$i >&2; i=$((i+1)); done; " +
156+
"echo STDOUT_MARKER; echo STDERR_MARKER >&2";
157+
return ("/bin/sh", ["-c", shellScript]);
158+
}
159+
160+
var powerShellScript =
161+
$"for ($i = 0; $i -lt {lineCount}; $i++) {{ " +
162+
"[Console]::Out.WriteLine(\"stdout-$i\"); " +
163+
"[Console]::Error.WriteLine(\"stderr-$i\") }; " +
164+
"[Console]::Out.WriteLine('STDOUT_MARKER'); " +
165+
"[Console]::Error.WriteLine('STDERR_MARKER')";
166+
return ("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", powerShellScript]);
167+
}
168+
169+
private static int CountLinesStartingWith(string value, string prefix)
170+
=> value.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)
171+
.Count(line => line.StartsWith(prefix, StringComparison.Ordinal));
172+
110173
private static (string Executable, string[] Arguments) CopyStdinCommand(string path)
111174
{
112175
if (!OperatingSystem.IsWindows())

‎tests/OpenClaw.SetupEngine.Tests/LocalAiGatewayUninstallTests.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,8 @@ public Task<CommandResult> RunAsync(
194194
string? workingDirectory = null,
195195
string? stdinInput = null,
196196
CancellationToken ct = default,
197-
Stream? stdinStream = null) => throw new NotSupportedException();
197+
Stream? stdinStream = null,
198+
bool allowInheritedPipeHandleEscape = false) => throw new NotSupportedException();
198199

199200
public Task<CommandResult> RunInWslAsync(
200201
string distroName,

‎tests/OpenClaw.SetupEngine.Tests/SetupStepsTests.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4592,7 +4592,8 @@ public Task<CommandResult> RunAsync(
45924592
string? workingDirectory = null,
45934593
string? stdinInput = null,
45944594
CancellationToken ct = default,
4595-
Stream? stdinStream = null)
4595+
Stream? stdinStream = null,
4596+
bool allowInheritedPipeHandleEscape = false)
45964597
{
45974598
Calls.Add((executable, arguments));
45984599
TimedCalls.Add((executable, arguments, timeout));

0 commit comments

Comments
 (0)