Skip to content

Commit c31f320

Browse files
shanselmanCopilot
andcommitted
fix(mxc): bound launcher cancellation cleanup
Co-authored-by: Copilot App <[email protected]>
1 parent 4206611 commit c31f320

2 files changed

Lines changed: 213 additions & 14 deletions

File tree

‎src/OpenClaw.Shared/Mxc/MxcExecutor.cs‎

Lines changed: 75 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,14 @@ public sealed class MxcExecutor
1313
{
1414
private const int DefaultStdoutCapBytes = 40_000;
1515
private const int DefaultStderrCapBytes = 5_000;
16+
private static readonly TimeSpan s_defaultCleanupTimeout = TimeSpan.FromMilliseconds(500);
1617

1718
private readonly string _wxcExePath;
1819
private readonly int _stdoutCapBytes;
1920
private readonly int _stderrCapBytes;
21+
private readonly Func<ProcessStartInfo, Process> _processFactory;
22+
private readonly Action<Process> _processTreeKiller;
23+
private readonly TimeSpan _cleanupTimeout;
2024

2125
private static readonly JsonSerializerOptions s_jsonOptions = new()
2226
{
@@ -25,13 +29,38 @@ public sealed class MxcExecutor
2529
};
2630

2731
public MxcExecutor(string wxcExePath, int? stdoutCapBytes = null, int? stderrCapBytes = null)
32+
: this(
33+
wxcExePath,
34+
stdoutCapBytes,
35+
stderrCapBytes,
36+
static startInfo => new Process { StartInfo = startInfo },
37+
static process => process.Kill(entireProcessTree: true),
38+
s_defaultCleanupTimeout)
39+
{
40+
}
41+
42+
internal MxcExecutor(
43+
string wxcExePath,
44+
int? stdoutCapBytes,
45+
int? stderrCapBytes,
46+
Func<ProcessStartInfo, Process> processFactory,
47+
Action<Process> processTreeKiller,
48+
TimeSpan cleanupTimeout)
2849
{
2950
if (string.IsNullOrEmpty(wxcExePath)) throw new ArgumentException("wxcExePath required", nameof(wxcExePath));
3051
if (!File.Exists(wxcExePath))
3152
throw new FileNotFoundException($"wxc-exec.exe not found at: {wxcExePath}", wxcExePath);
53+
ArgumentNullException.ThrowIfNull(processFactory);
54+
ArgumentNullException.ThrowIfNull(processTreeKiller);
55+
if (cleanupTimeout <= TimeSpan.Zero)
56+
throw new ArgumentOutOfRangeException(nameof(cleanupTimeout), "Cleanup timeout must be positive.");
57+
3258
_wxcExePath = wxcExePath;
3359
_stdoutCapBytes = stdoutCapBytes is > 0 ? stdoutCapBytes.Value : DefaultStdoutCapBytes;
3460
_stderrCapBytes = stderrCapBytes is > 0 ? stderrCapBytes.Value : DefaultStderrCapBytes;
61+
_processFactory = processFactory;
62+
_processTreeKiller = processTreeKiller;
63+
_cleanupTimeout = cleanupTimeout;
3564
}
3665

3766
public async Task<MxcResult> RunAsync(
@@ -78,7 +107,6 @@ private async Task<MxcResult> RunWithArgumentsAsync(
78107
CancellationToken ct,
79108
string? workingDirectory)
80109
{
81-
using var process = new Process();
82110
var startInfo = new ProcessStartInfo
83111
{
84112
FileName = _wxcExePath,
@@ -94,18 +122,27 @@ private async Task<MxcResult> RunWithArgumentsAsync(
94122
// ArgumentList avoids the manual-quoting trap that bites Process.Arguments
95123
// (each entry is escaped per Win32 CommandLineToArgvW rules by the BCL).
96124
foreach (var arg in arguments) startInfo.ArgumentList.Add(arg);
97-
process.StartInfo = startInfo;
125+
using var process = _processFactory(startInfo)
126+
?? throw new InvalidOperationException("Process factory returned null.");
98127

99128
var stdoutBuilder = new StringBuilder();
100129
var stderrBuilder = new StringBuilder();
101130
// StringBuilder is not thread-safe; the async event handlers can fire
102131
// concurrently with each other and with the post-kill ToString() read.
103132
var outLock = new object();
104133
var errLock = new object();
134+
var processExited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
135+
var stdoutClosed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
136+
var stderrClosed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
105137

106138
process.OutputDataReceived += (_, e) =>
107139
{
108-
if (e.Data is null) return;
140+
if (e.Data is null)
141+
{
142+
stdoutClosed.TrySetResult();
143+
return;
144+
}
145+
109146
lock (outLock)
110147
{
111148
if (stdoutBuilder.Length < _stdoutCapBytes * 2)
@@ -114,25 +151,34 @@ private async Task<MxcResult> RunWithArgumentsAsync(
114151
};
115152
process.ErrorDataReceived += (_, e) =>
116153
{
117-
if (e.Data is null) return;
154+
if (e.Data is null)
155+
{
156+
stderrClosed.TrySetResult();
157+
return;
158+
}
159+
118160
lock (errLock)
119161
{
120162
if (stderrBuilder.Length < _stderrCapBytes * 2)
121163
stderrBuilder.AppendLine(e.Data);
122164
}
123165
};
166+
process.EnableRaisingEvents = true;
167+
process.Exited += (_, _) => processExited.TrySetResult();
124168

125169
var sw = Stopwatch.StartNew();
126170
try
127171
{
128172
process.Start();
129173
process.BeginOutputReadLine();
130174
process.BeginErrorReadLine();
175+
if (process.HasExited)
176+
processExited.TrySetResult();
131177

132178
bool completed;
133179
try
134180
{
135-
await process.WaitForExitAsync(ct);
181+
await processExited.Task.WaitAsync(ct);
136182
completed = true;
137183
}
138184
catch (OperationCanceledException)
@@ -142,13 +188,11 @@ private async Task<MxcResult> RunWithArgumentsAsync(
142188

143189
if (!completed)
144190
{
145-
try { process.Kill(entireProcessTree: true); }
191+
try { _processTreeKiller(process); }
146192
catch (Exception ex) { Trace.WriteLine($"MxcExecutor: process kill (cancellation path) failed: {ex.Message}"); }
147-
// WaitForExit() (sync) blocks until both stdout and stderr async
148-
// readers have drained the redirected pipes. Without this the
149-
// event handlers can still be appending while ToString() runs.
150-
try { process.WaitForExit(); }
151-
catch (Exception ex) { Trace.WriteLine($"MxcExecutor: process drain (cancellation path) failed: {ex.Message}"); }
193+
if (!await WaitForCleanupAsync(processExited.Task, stdoutClosed.Task, stderrClosed.Task, _cleanupTimeout))
194+
Trace.WriteLine("MxcExecutor: cancellation cleanup timed out.");
195+
152196
sw.Stop();
153197
string capturedOut;
154198
lock (outLock) { capturedOut = stdoutBuilder.ToString(); }
@@ -163,9 +207,9 @@ private async Task<MxcResult> RunWithArgumentsAsync(
163207
};
164208
}
165209

166-
// Flush async readers before reading the StringBuilders.
167-
try { process.WaitForExit(); }
168-
catch (Exception ex) { Trace.WriteLine($"MxcExecutor: post-exit drain WaitForExit failed: {ex.Message}"); }
210+
if (!await WaitForCleanupAsync(processExited.Task, stdoutClosed.Task, stderrClosed.Task, _cleanupTimeout))
211+
Trace.WriteLine("MxcExecutor: post-exit output drain timed out.");
212+
169213
sw.Stop();
170214
string outRaw, errRaw;
171215
lock (outLock) { outRaw = stdoutBuilder.ToString().Trim(); }
@@ -196,6 +240,23 @@ private async Task<MxcResult> RunWithArgumentsAsync(
196240
}
197241
}
198242

243+
internal static async Task<bool> WaitForCleanupAsync(
244+
Task processExited,
245+
Task stdoutClosed,
246+
Task stderrClosed,
247+
TimeSpan timeout)
248+
{
249+
try
250+
{
251+
await Task.WhenAll(processExited, stdoutClosed, stderrClosed).WaitAsync(timeout);
252+
return true;
253+
}
254+
catch (TimeoutException)
255+
{
256+
return false;
257+
}
258+
}
259+
199260
private static string Truncate(string text, int maxLength)
200261
{
201262
if (text.Length <= maxLength) return text;
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
using System.Diagnostics;
2+
using System.Runtime.InteropServices;
3+
using OpenClaw.Shared.Mxc;
4+
using Xunit;
5+
6+
namespace OpenClaw.Shared.Tests.Mxc;
7+
8+
public class MxcExecutorTests
9+
{
10+
[Fact]
11+
public async Task RunAsync_CapturesOutput_WhenLauncherExitsNormally()
12+
{
13+
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
14+
return;
15+
16+
var cmdPath = Path.Combine(
17+
Environment.GetFolderPath(Environment.SpecialFolder.System),
18+
"cmd.exe");
19+
var executor = new MxcExecutor(
20+
cmdPath,
21+
stdoutCapBytes: null,
22+
stderrCapBytes: null,
23+
processFactory: _ => CreateProcess(
24+
cmdPath,
25+
"echo stdout-line & echo stderr-line 1>&2"),
26+
processTreeKiller: process => process.Kill(entireProcessTree: true),
27+
cleanupTimeout: TimeSpan.FromSeconds(1));
28+
29+
var result = await executor.RunAsync(new MxcConfig
30+
{
31+
ContainerId = "output-capture-test",
32+
Process = new MxcProcess { CommandLine = "ignored-by-test-process" },
33+
});
34+
35+
Assert.True(result.Success);
36+
Assert.False(result.TimedOut);
37+
Assert.Equal(0, result.ExitCode);
38+
Assert.Contains("stdout-line", result.Output);
39+
Assert.Contains("stderr-line", result.Error);
40+
}
41+
42+
[Fact]
43+
public async Task RunAsync_CancellationCleanupIsBounded_WhenProcessTreeKillDoesNotStopLauncher()
44+
{
45+
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
46+
return;
47+
48+
var launcherPid = 0;
49+
var cmdPath = Path.Combine(
50+
Environment.GetFolderPath(Environment.SpecialFolder.System),
51+
"cmd.exe");
52+
var executor = new MxcExecutor(
53+
cmdPath,
54+
stdoutCapBytes: null,
55+
stderrCapBytes: null,
56+
processFactory: _ => CreateProcess(
57+
cmdPath,
58+
"echo launcher-started & ping -n 31 127.0.0.1 >nul"),
59+
processTreeKiller: process => launcherPid = process.Id,
60+
cleanupTimeout: TimeSpan.FromMilliseconds(100));
61+
using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
62+
var stopwatch = Stopwatch.StartNew();
63+
64+
try
65+
{
66+
var result = await executor.RunAsync(
67+
new MxcConfig
68+
{
69+
ContainerId = "bounded-cleanup-test",
70+
Process = new MxcProcess { CommandLine = "ignored-by-test-process" },
71+
},
72+
cancellation.Token).WaitAsync(TimeSpan.FromSeconds(2));
73+
74+
stopwatch.Stop();
75+
Assert.True(result.TimedOut);
76+
Assert.Equal(-1, result.ExitCode);
77+
Assert.Contains("cancelled", result.Error, StringComparison.OrdinalIgnoreCase);
78+
Assert.True(
79+
stopwatch.Elapsed < TimeSpan.FromSeconds(1),
80+
$"Cancellation cleanup took {stopwatch.ElapsedMilliseconds} ms.");
81+
}
82+
finally
83+
{
84+
KillProcessTree(launcherPid);
85+
}
86+
}
87+
88+
[Fact]
89+
public async Task WaitForCleanupAsync_ReturnsTrue_WhenProcessAndPipesComplete()
90+
{
91+
var completed = Task.CompletedTask;
92+
93+
var result = await MxcExecutor.WaitForCleanupAsync(
94+
completed,
95+
completed,
96+
completed,
97+
TimeSpan.FromSeconds(1));
98+
99+
Assert.True(result);
100+
}
101+
102+
private static Process CreateProcess(string cmdPath, string command)
103+
{
104+
var startInfo = new ProcessStartInfo(cmdPath)
105+
{
106+
RedirectStandardOutput = true,
107+
RedirectStandardError = true,
108+
UseShellExecute = false,
109+
CreateNoWindow = true,
110+
};
111+
startInfo.ArgumentList.Add("/d");
112+
startInfo.ArgumentList.Add("/s");
113+
startInfo.ArgumentList.Add("/c");
114+
startInfo.ArgumentList.Add(command);
115+
return new Process { StartInfo = startInfo };
116+
}
117+
118+
private static void KillProcessTree(int processId)
119+
{
120+
if (processId <= 0)
121+
return;
122+
123+
try
124+
{
125+
using var process = Process.GetProcessById(processId);
126+
process.Kill(entireProcessTree: true);
127+
process.WaitForExit(2_000);
128+
}
129+
catch (ArgumentException)
130+
{
131+
// The process already exited.
132+
}
133+
catch (InvalidOperationException)
134+
{
135+
// The process already exited.
136+
}
137+
}
138+
}

0 commit comments

Comments
 (0)