From 196465ef9c6b01ee2dd12420daa087b3aa0af051 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:56:05 -0500 Subject: [PATCH] fix(workers): fail fast when the worker exits before connecting; launch-cleanup Kill never masks the launch error (WRK-002, WRK-006, #253) --- docs/WorkerProcessLauncher.md | 18 +++- .../Sessions/SessionWorkerClientFactory.cs | 93 +++++++++++++++---- .../Workers/WorkerProcessLauncher.cs | 24 +++++ ...ssionWorkerClientFactoryFakeWorkerTests.cs | 86 +++++++++++++++++ .../Workers/WorkerProcessLauncherTests.cs | 29 ++++++ .../TestSupport/FakeWorkerProcess.cs | 8 ++ 6 files changed, 236 insertions(+), 22 deletions(-) diff --git a/docs/WorkerProcessLauncher.md b/docs/WorkerProcessLauncher.md index b78739f4..82d0cedc 100644 --- a/docs/WorkerProcessLauncher.md +++ b/docs/WorkerProcessLauncher.md @@ -54,9 +54,15 @@ path exists, has a `.exe` extension, contains a valid Windows Portable Executable header, and matches the configured `RequiredArchitecture`. After the process starts, `IWorkerStartupProbe` waits for startup readiness. -The default probe only verifies that the worker did not exit immediately. The -worker client replaces this probe when pipe connection, hello, and -`WorkerReady` handling are implemented. +The default probe only verifies that the worker did not exit immediately, which +it checks once, microseconds after the process is created. A worker that dies +after that and before it connects is caught by the session factory instead: +`SessionWorkerClientFactory` races the pipe connect against the process exit, +so an early exit fails the open at once with `StartupFailed` and the worker's +exit code rather than holding the open (and its session slot) for the whole +startup timeout and reporting a timeout. Once the pipe is connected, a worker +exit surfaces as pipe end-of-stream in the handshake reads. The worker's stderr +is not redirected, so the failure carries the exit code only. The startup probe runs once, bounded by `WorkerOptions.StartupTimeoutSeconds`; it is not retried. The default probe only checks that the process is still @@ -71,7 +77,11 @@ retry loop. If startup fails or exceeds `WorkerOptions.StartupTimeoutSeconds`, the launcher kills the worker process tree, disposes the process handle, disposes the optional pipe reservation, records a worker kill metric, and reports a -`WorkerProcessLaunchException`. +`WorkerProcessLaunchException`. A `Kill` that throws during this cleanup (the +process is mid-termination, access is denied, a descendant could not be +terminated) is logged and does not replace the launch error; the process handle +and the pipe are disposed regardless. The session factory's own cleanup follows +the same rule. ## Verification diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionWorkerClientFactory.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionWorkerClientFactory.cs index 072fa5ee..8db661a2 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionWorkerClientFactory.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionWorkerClientFactory.cs @@ -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().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); } - /// Waits for a client to connect to the pipe. + /// + /// Waits for the worker to connect to the pipe, failing fast if the worker process exits + /// first (WRK-002). + /// + /// + /// The launcher's startup probe checks HasExited 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 with the exit code at once. + /// Once connected, a worker exit shows up as pipe EOF in the handshake reads. + /// /// The named pipe. - /// Cancellation token. - private static async Task WaitForPipeConnectionAsync( + /// The launched worker process. + /// Session id, for the failure message. + /// Cancellation token (the startup deadline and the caller's). + /// A task that represents the asynchronous operation. + 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) + { + } } /// diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs index a9c99db1..7ec8ef29 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs @@ -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)) diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs index 3ec73b96..b46b9c0b 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs @@ -124,6 +124,63 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime Assert.True(launcher.Process.IsDisposed); } + /// + /// WRK-002: a worker that exits before it connects to its pipe fails the open at once with + /// and its exit code, instead of + /// holding the open for the whole startup timeout and reporting a timeout. + /// + /// A task that represents the asynchronous operation. + [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( + 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); + } + + /// + /// WRK-006: a Kill that throws during launch-failure cleanup does not replace the + /// startup failure, and the process handle is still disposed. + /// + /// A task that represents the asynchronous operation. + [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( + async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout)); + + Assert.Contains("did not complete startup", exception.Message); + Assert.True(launcher.Process.IsDisposed); + } + /// /// mxaccessgw#192: every field comes from configuration. /// The heartbeat check interval binds from HeartbeatCheckIntervalSeconds (not the @@ -391,6 +448,35 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime } } + /// Fake launcher whose worker stays alive but never connects to its pipe. + private sealed class NeverConnectLauncher : IWorkerProcessLauncher + { + /// Gets the fake worker process. + public FakeWorkerProcess Process { get; } = new(processId: 6802); + + /// + public Task LaunchAsync( + WorkerProcessLaunchRequest request, + CancellationToken cancellationToken = default) => Task.FromResult(CreateHandle(Process)); + } + + /// Fake launcher whose worker exits with code 3 shortly after start, never connecting. + private sealed class ExitBeforeConnectLauncher : IWorkerProcessLauncher + { + /// Gets the fake worker process. + public FakeWorkerProcess Process { get; } = new(processId: 5791); + + /// + public Task 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( diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs index 41634073..d54e9155 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs @@ -216,6 +216,35 @@ public sealed class WorkerProcessLauncherTests Assert.Equal(1, metrics.GetSnapshot().WorkerKills); } + /// + /// WRK-006: a Kill 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. + /// + /// A task that represents the asynchronous operation. + [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( + async () => await launcher.LaunchAsync(CreateRequest())); + + Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode); + Assert.True(process.DisposeCalled); + } + /// Verifies that a startup probe timeout kills and disposes the worker process. /// A task that represents the asynchronous operation. [Fact] diff --git a/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs b/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs index 10a5e9cb..6e149217 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs @@ -57,11 +57,19 @@ public sealed class FakeWorkerProcess(int processId) : IWorkerProcess /// public void Kill(bool entireProcessTree) { + if (KillException is not null) + { + throw KillException; + } + KillCount++; KillEntireProcessTree = entireProcessTree; MarkExited(-1); } + /// Gets or sets an exception throws instead of killing, as Process.Kill can for a process that is mid-termination. + public Exception? KillException { get; set; } + /// Marks this fake as disposed so tests can assert was called. public void Dispose() => IsDisposed = true;