mxc icon indicating copy to clipboard operation
mxc copied to clipboard

.NET SDK: a timed-out captured execution can lose the output written before the timeout

Open adpa-ms opened this issue 3 weeks ago • 1 comments

Relevant area(s)

Windows

Brief description of your issue

In the .NET SDK, a captured execution that times out can lose all the output its command wrote before the timeout.

MxcProcess.WaitForExitWithOutputAsync reads stdout and stderr with blocking reads on thread-pool threads. On timeout, it closes both readers, which discards any bytes they have not read yet.

This loses output when the thread pool is busy and a child process keeps the pipes open after the timeout. One read then blocks the pool thread that the other read is queued on. The queued read runs only after the close, so its output is gone.

MxcLifecycle.RunInContainerAsync and the V1.Dev RunInContainerJsonAsync use this method, so captured execution in an existing container can be affected. Callers can also use WaitForExitWithOutputAsync directly.

IsolationSession shows the problem. Its timeout ends only the foreground process, so the command's child processes keep the pipes open. ProcessContainer kills the whole process tree at the timeout and did not lose output. WSLC was not tested.

The test MxcLifecycleE2ETests.Exec_CapturedTimeoutClosesDescendantHeldOutput fails this way intermittently. It failed in 2 of 8 runs of the whole test project, and passed in 10 of 10 runs on its own.

Steps to reproduce

Run at 40df784b2 on Windows 11 x64 with 6 processors and isolation sessions available. The app targets .NET 10 and uses the SDK built with MxcWithIsolationSession=true.

  1. Provision and start an IsolationSession container.
  2. Make the thread pool busy. Cap worker threads at the processor count with ThreadPool.SetMaxThreads, then queue four times as many work items that each block for 20 ms and queue themselves again.
  3. From a pool thread (Task.Run), call MxcLifecycle.RunInContainerAsync with TimeoutMs = 750 and this command: C:\Windows\System32\cmd.exe /c echo MXC_TIMEOUT_PARTIAL & start /b C:\Windows\System32\cmd.exe /c ping -n 60 127.0.0.1 >nul & ping -n 60 127.0.0.1 >nul
  4. Check whether Stdout contains MXC_TIMEOUT_PARTIAL. Run this 10 times, then 10 more times without step 2.

For ProcessContainer, steps 2 to 4 used MxcContainer.Spawn with TimeoutMs = 750 and the command C:\Windows\System32\cmd.exe /v:on /c echo MXC_TIMEOUT_PARTIAL & set /p x=. The app held StandardInput open and called WaitForExitWithOutputAsync().

Backend Marker captured, idle pool Marker captured, busy pool
IsolationSession 10/10 0/10
ProcessContainer 10/10 10/10

Expected behavior

A captured execution that times out returns the output its command wrote before the timeout, however busy the thread pool is. The .NET API reference says it "returns the text collected so far with TimedOut = true".

Actual behavior

With a busy thread pool, all 10 IsolationSession runs timed out with an empty Stdout, although the command prints the marker first. With an idle pool, all 10 runs returned the marker.

adpa-ms avatar Nov 05 '26 23:11 adpa-ms

A possible fix: read each output stream on its own thread instead of as thread-pool work. Then neither a busy pool nor the other stream's blocked read can hold a read back until the timeout closes it. The Rust SDK's MxcProcess::wait_with_output already reads each stream on its own thread.

In MxcProcess.WaitForExitWithOutputAsync:

-        Task<byte[]> ReadAll(Stream? s) =>
-            s is null ? Task.FromResult(Array.Empty<byte>()) : ReadToEndAsync(s, cancellationToken);
+        Task<byte[]> ReadAll(Stream? s) =>
+            s is null
+                ? Task.FromResult(Array.Empty<byte>())
+                : Task.Factory.StartNew(
+                    () => ReadToEnd(s),
+                    CancellationToken.None,
+                    TaskCreationOptions.LongRunning,
+                    TaskScheduler.Default);

With a synchronous helper, which leaves ReadToEndAsync unused:

private static byte[] ReadToEnd(Stream s)
{
    using var ms = new MemoryStream();
    s.CopyTo(ms);
    return ms.ToArray();
}

Cancellation still ends the reads. The existing cancellation path closes the readers, and kills the process if it cannot. The cost is two threads per captured execution while it runs, as in the Rust SDK.

With only this change, the repro above captured the marker in 10 of 10 busy-pool IsolationSession runs, up from 0 of 10. The idle-pool and ProcessContainer runs stayed at 10 of 10. The SDK's test project also passed with the change on net8.0 and net10.0, with the IsolationSession tests running live.

The capture code is the same on every platform, but only Windows was tested. Whether Linux or macOS lose output depends on whether a timeout there can leave a child process holding the pipes.

adpa-ms avatar Nov 05 '26 23:11 adpa-ms