fix(workers): fail fast when the worker exits before connecting; launch-cleanup Kill never masks the launch error (WRK-002, WRK-006, #253)

This commit is contained in:
Joseph Doherty
2026-12-03 09:56:05 -05:00
parent 2c22ae6bd4
commit 196465ef9c
6 changed files with 236 additions and 22 deletions
@@ -79,7 +79,8 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
.ConfigureAwait(false);
session.TransitionTo(SessionState.WaitingForPipe);
await WaitForPipeConnectionAsync(pipe, startupCancellation.Token).ConfigureAwait(false);
await WaitForPipeConnectionAsync(pipe, processHandle.Process, session.SessionId, startupCancellation.Token)
.ConfigureAwait(false);
session.TransitionTo(SessionState.Handshaking);
WorkerFrameProtocolOptions frameOptions = new(
@@ -126,23 +127,30 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
}
else
{
if (processHandle is not null)
// Must not throw (WRK-006): Kill can raise Win32Exception or AggregateException for
// a process that is mid-termination, and an exception here would replace the
// startup failure the caller is owed and skip the pipe dispose, leaking the
// pipe server handle.
try
{
try
if (processHandle is not null && !processHandle.Process.HasExited)
{
if (!processHandle.Process.HasExited)
{
processHandle.Process.Kill(entireProcessTree: true);
_metrics.WorkerKilled("OpenSessionFailed");
}
}
finally
{
processHandle.Dispose();
processHandle.Process.Kill(entireProcessTree: true);
_metrics.WorkerKilled("OpenSessionFailed");
}
}
pipe?.Dispose();
catch (Exception killException)
{
_loggerFactory.CreateLogger<SessionWorkerClientFactory>().LogWarning(
killException,
"Killing the worker of session {SessionId} after a failed open failed.",
session.SessionId);
}
finally
{
processHandle?.Dispose();
pipe?.Dispose();
}
}
if (exception is OperationCanceledException
@@ -193,14 +201,63 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
outBufferSize: PipeBufferSizeBytes);
}
/// <summary>Waits for a client to connect to the pipe.</summary>
/// <summary>
/// Waits for the worker to connect to the pipe, failing fast if the worker process exits
/// first (WRK-002).
/// </summary>
/// <remarks>
/// The launcher's startup probe checks <c>HasExited</c> once, right after the process starts,
/// which is almost always false. A worker that then dies before connecting (a missing
/// dependency, a bad argument, security software, an unhandled startup exception) used to
/// hold the open — and its session slot — for the full startup timeout and surface as a
/// timeout with no exit code. Racing the connect against the process exit reports the crash
/// as <see cref="WorkerProcessLaunchErrorCode.StartupFailed"/> with the exit code at once.
/// Once connected, a worker exit shows up as pipe EOF in the handshake reads.
/// </remarks>
/// <param name="pipe">The named pipe.</param>
/// <param name="cancellationToken">Cancellation token.</param>
private static async Task WaitForPipeConnectionAsync(
/// <param name="process">The launched worker process.</param>
/// <param name="sessionId">Session id, for the failure message.</param>
/// <param name="cancellationToken">Cancellation token (the startup deadline and the caller's).</param>
/// <returns>A task that represents the asynchronous operation.</returns>
internal static async Task WaitForPipeConnectionAsync(
NamedPipeServerStream pipe,
IWorkerProcess process,
string sessionId,
CancellationToken cancellationToken)
{
await pipe.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
using CancellationTokenSource raceCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
Task connect = pipe.WaitForConnectionAsync(raceCancellation.Token);
Task exit = process.WaitForExitAsync(raceCancellation.Token).AsTask();
Task first = await Task.WhenAny(connect, exit).ConfigureAwait(false);
if (first == exit && exit.IsCompletedSuccessfully && !connect.IsCompletedSuccessfully)
{
await raceCancellation.CancelAsync().ConfigureAwait(false);
await ObserveQuietlyAsync(connect).ConfigureAwait(false);
int? exitCode = process.ExitCode;
throw new WorkerProcessLaunchException(
WorkerProcessLaunchErrorCode.StartupFailed,
$"Worker process for session {sessionId} exited with code "
+ $"{(exitCode?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unknown")} "
+ "before it connected to its pipe.");
}
// The connect won (or the exit wait itself failed, which says nothing about the worker):
// stop watching the process and let the connect decide the outcome.
await raceCancellation.CancelAsync().ConfigureAwait(false);
await ObserveQuietlyAsync(exit).ConfigureAwait(false);
await connect.ConfigureAwait(false);
}
private static async Task ObserveQuietlyAsync(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (Exception exception) when (exception is OperationCanceledException or IOException or ObjectDisposedException or InvalidOperationException)
{
}
}
/// <summary>
@@ -293,6 +293,10 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
return workingDirectory;
}
// Called from the launch-failure catch blocks, so it must never throw: Kill can raise
// Win32Exception (the process is mid-termination, or access is denied) or AggregateException
// (a descendant could not be terminated), and an exception escaping here would replace the
// WorkerProcessLaunchException the caller is owed (WRK-006).
private void KillAndDispose(IWorkerProcess process, string reason)
{
try
@@ -303,12 +307,32 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
_metrics.WorkerKilled(reason);
}
}
catch (Exception exception)
{
_logger.LogWarning(
exception,
"Killing worker process {ProcessId} after a failed launch ({Reason}) failed.",
SafeProcessId(process),
reason);
}
finally
{
process.Dispose();
}
}
private static int? SafeProcessId(IWorkerProcess process)
{
try
{
return process.Id;
}
catch (InvalidOperationException)
{
return null;
}
}
private static void ValidateRequest(WorkerProcessLaunchRequest request)
{
if (string.IsNullOrWhiteSpace(request.SessionId))
@@ -124,6 +124,63 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
Assert.True(launcher.Process.IsDisposed);
}
/// <summary>
/// WRK-002: a worker that exits before it connects to its pipe fails the open at once with
/// <see cref="WorkerProcessLaunchErrorCode.StartupFailed"/> and its exit code, instead of
/// holding the open for the whole startup timeout and reporting a timeout.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CreateAsync_WhenWorkerExitsBeforeConnecting_FailsFastWithExitCode()
{
ExitBeforeConnectLauncher launcher = new();
using GatewayMetrics metrics = new();
SessionWorkerClientFactory factory = new(
launcher,
Options.Create(CreateOptions(startupTimeoutSeconds: 20)),
metrics,
NullLoggerFactory.Instance);
GatewaySession session = CreateSession(startupTimeout: TimeSpan.FromSeconds(20));
System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();
WorkerProcessLaunchException exception = await Assert.ThrowsAsync<WorkerProcessLaunchException>(
async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout));
stopwatch.Stop();
Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode);
Assert.Contains("exited with code 3", exception.Message);
Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(10), $"open took {stopwatch.Elapsed}");
Assert.Equal(0, launcher.Process.KillCount);
Assert.True(launcher.Process.IsDisposed);
}
/// <summary>
/// WRK-006: a <c>Kill</c> that throws during launch-failure cleanup does not replace the
/// startup failure, and the process handle is still disposed.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CreateAsync_WhenCleanupKillThrows_SurfacesTheStartupFailure()
{
// The worker never connects, so the open fails in the pipe wait — before a worker client
// exists — and the cleanup kills the process handle directly.
NeverConnectLauncher launcher = new();
launcher.Process.KillException = new System.ComponentModel.Win32Exception(5, "Access is denied.");
using GatewayMetrics metrics = new();
SessionWorkerClientFactory factory = new(
launcher,
Options.Create(CreateOptions(startupTimeoutSeconds: 1)),
metrics,
NullLoggerFactory.Instance);
GatewaySession session = CreateSession(startupTimeout: TimeSpan.FromSeconds(1));
TimeoutException exception = await Assert.ThrowsAsync<TimeoutException>(
async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout));
Assert.Contains("did not complete startup", exception.Message);
Assert.True(launcher.Process.IsDisposed);
}
/// <summary>
/// mxaccessgw#192: every <see cref="WorkerClientOptions"/> field comes from configuration.
/// The heartbeat check interval binds from <c>HeartbeatCheckIntervalSeconds</c> (not the
@@ -391,6 +448,35 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
}
}
/// <summary>Fake launcher whose worker stays alive but never connects to its pipe.</summary>
private sealed class NeverConnectLauncher : IWorkerProcessLauncher
{
/// <summary>Gets the fake worker process.</summary>
public FakeWorkerProcess Process { get; } = new(processId: 6802);
/// <inheritdoc />
public Task<WorkerProcessHandle> LaunchAsync(
WorkerProcessLaunchRequest request,
CancellationToken cancellationToken = default) => Task.FromResult(CreateHandle(Process));
}
/// <summary>Fake launcher whose worker exits with code 3 shortly after start, never connecting.</summary>
private sealed class ExitBeforeConnectLauncher : IWorkerProcessLauncher
{
/// <summary>Gets the fake worker process.</summary>
public FakeWorkerProcess Process { get; } = new(processId: 5791);
/// <inheritdoc />
public Task<WorkerProcessHandle> LaunchAsync(
WorkerProcessLaunchRequest request,
CancellationToken cancellationToken = default)
{
_ = Task.Delay(TimeSpan.FromMilliseconds(50), CancellationToken.None)
.ContinueWith(_ => Process.MarkExited(3), TaskScheduler.Default);
return Task.FromResult(CreateHandle(Process));
}
}
private static WorkerProcessHandle CreateHandle(IWorkerProcess process)
{
return new WorkerProcessHandle(
@@ -216,6 +216,35 @@ public sealed class WorkerProcessLauncherTests
Assert.Equal(1, metrics.GetSnapshot().WorkerKills);
}
/// <summary>
/// WRK-006: a <c>Kill</c> that throws during launch-failure cleanup is logged, not thrown, so
/// the caller still gets the launch error code and the process is still disposed.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LaunchAsync_WhenCleanupKillThrows_StillThrowsLaunchErrorAndDisposes()
{
using TestDirectory directory = TestDirectory.Create();
string executablePath = directory.CreateWorkerExecutable(machine: 0x014c);
FakeWorkerProcess process = new(processId: 1234)
{
KillException = new System.ComponentModel.Win32Exception(5, "Access is denied."),
};
GatewayMetrics metrics = new();
WorkerProcessLauncher launcher = CreateLauncher(
executablePath,
new FakeWorkerProcessFactory(process),
new FailingStartupProbe(),
metrics);
WorkerProcessLaunchException exception =
await Assert.ThrowsAsync<WorkerProcessLaunchException>(
async () => await launcher.LaunchAsync(CreateRequest()));
Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode);
Assert.True(process.DisposeCalled);
}
/// <summary>Verifies that a startup probe timeout kills and disposes the worker process.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -57,11 +57,19 @@ public sealed class FakeWorkerProcess(int processId) : IWorkerProcess
/// <inheritdoc />
public void Kill(bool entireProcessTree)
{
if (KillException is not null)
{
throw KillException;
}
KillCount++;
KillEntireProcessTree = entireProcessTree;
MarkExited(-1);
}
/// <summary>Gets or sets an exception <see cref="Kill"/> throws instead of killing, as <c>Process.Kill</c> can for a process that is mid-termination.</summary>
public Exception? KillException { get; set; }
/// <summary>Marks this fake as disposed so tests can assert <see cref="Dispose"/> was called.</summary>
public void Dispose() => IsDisposed = true;