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>