From 3d4d5f2b04367d67fbcfbca72c930c37bf3fd8dc Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:39:19 -0500 Subject: [PATCH 1/9] fix(sessions): renew the lease on last-subscriber detach; purge item registrations on Unregister (SES-004, SES-007, #253) --- docs/Sessions.md | 4 +- .../Sessions/GatewaySession.cs | 45 +++++++++- .../Gateway/Sessions/GatewaySessionTests.cs | 87 +++++++++++++++++++ 3 files changed, 132 insertions(+), 4 deletions(-) diff --git a/docs/Sessions.md b/docs/Sessions.md index acea2952..25e84fb6 100644 --- a/docs/Sessions.md +++ b/docs/Sessions.md @@ -230,7 +230,7 @@ The repair transitions the monitor's reconcile broadcasts on the alarm feed (Rai The same one-distributor-per-session rule is enforced at the other end of the lifecycle. Session disposal disposes the distributor and latches the fact, so an attach that passed its readiness gate and then lost the CPU until the session was torn down throws `SessionNotReady` rather than constructing a replacement distributor. A replacement can never be pumped — the pump-start flag is a one-way latch — so its subscriber would block on an empty channel that is never completed until the client's own deadline expired, with no error, log or metric to explain it. Every attach entry point (`AttachEventSubscriber`, `AttachEventSubscriberWithReplay`, `AttachInternalEventSubscriber`) fails this way, and each rolls back the subscriber-count slot it took, so a caller that loses the race to teardown sees the same failure it would have seen a moment later from the readiness gate. -Sessions open with `MxGateway:Sessions:DefaultLeaseSeconds` (default 1800) added to the open timestamp. Unary client activity refreshes the lease by the same duration (`TouchClientActivity` is the only path that moves the lease). `IsLeaseExpired` cooperates with `SessionManager.CloseExpiredLeasesAsync`, which iterates a registry snapshot and closes any session whose lease has expired with `LeaseExpiredReason`. `SessionLeaseMonitorHostedService` runs that sweep every `MxGateway:Sessions:LeaseSweepIntervalSeconds` seconds (default 30). +Sessions open with `MxGateway:Sessions:DefaultLeaseSeconds` (default 1800) added to the open timestamp. Unary client activity refreshes the lease by the same duration (`TouchClientActivity`), and so does the detach of the last external event subscriber: streaming is client activity, and the lease does not age while a subscriber is attached (`IsLeaseExpired` is held false), but its deadline is only moved on unary calls. Without the renewal at detach, a client that streamed for longer than `DefaultLeaseSeconds` with no unary call would drop its stream with a lease already in the past, and the next sweep would close it as `lease-expired` (which takes precedence) before its detach-grace window. `IsLeaseExpired` cooperates with `SessionManager.CloseExpiredLeasesAsync`, which iterates a registry snapshot and closes any session whose lease has expired with `LeaseExpiredReason`. `SessionLeaseMonitorHostedService` runs that sweep every `MxGateway:Sessions:LeaseSweepIntervalSeconds` seconds (default 30). #### Lazy dashboard mirror @@ -258,7 +258,7 @@ The asymmetry with `CloseExpiredLeasesAsync` — whose `ParallelOptions` *is* to `MxGateway:Sessions:DetachGraceSeconds` (default 30) is a bounded retention window kept after a session's *last external (gRPC) event-stream subscriber* drops, so a client can reconnect to the same session instead of having it torn down on the first stream disconnect. While the window is open the session stays `Ready` and fully usable — worker commands continue to work and a reconnecting subscriber re-attaches normally. Because retention is keyed on the *external* subscriber count (`_activeEventSubscriberCount`), and the gateway-owned internal dashboard mirror registers directly on the distributor with `isInternal: true` and is therefore *not* counted, a session whose only remaining subscriber is the dashboard mirror still enters detach-grace. -Mechanically: when the last external subscriber detaches and `DetachGraceSeconds > 0`, `DetachEventSubscriber` stamps `DetachedAtUtc` from the session's `TimeProvider` under `_syncRoot` (the detach→grace-start transition). `AttachEventSubscriber` clears `DetachedAtUtc` under the same lock when a subscriber re-attaches (the reattach→grace-cancel transition), so the two races and the sweeper's read all serialize on `_syncRoot`. `SessionManager.CloseExpiredLeasesAsync` checks `IsDetachGraceExpired(now)` alongside `IsLeaseExpired(now)`: a session detached for at least `DetachGraceSeconds` with no active external subscriber is closed by the same lease sweep, with the distinct `DetachGraceExpiredReason` (`"detach-grace-expired"`) so operators can tell a short reconnect-window expiry from a long idle-lease expiry. Setting `DetachGraceSeconds` to `0` disables retention and reverts to the original behavior: a detached session is retained only until its normal lease expires. +Mechanically: when the last external subscriber detaches and `DetachGraceSeconds > 0`, `DetachEventSubscriber` stamps `DetachedAtUtc` from the session's `TimeProvider` under `_syncRoot` (the detach→grace-start transition). `AttachEventSubscriber` clears `DetachedAtUtc` under the same lock when a subscriber re-attaches (the reattach→grace-cancel transition), so the two races and the sweeper's read all serialize on `_syncRoot`. `SessionManager.CloseExpiredLeasesAsync` checks `IsDetachGraceExpired(now)` alongside `IsLeaseExpired(now)`: a session detached for at least `DetachGraceSeconds` with no active external subscriber is closed by the same lease sweep, with the distinct `DetachGraceExpiredReason` (`"detach-grace-expired"`) so operators can tell a short reconnect-window expiry from a long idle-lease expiry. Setting `DetachGraceSeconds` to `0` disables retention and reverts to the original behavior: a detached session is retained only until its normal lease expires, counted from the detach. `DetachGraceSeconds` controls retention and expiry only; the reconnect/replay path that re-attaches a dropped client to a retained session is described in [Reconnect and replay](#reconnect-and-replay). diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs index 9f8da1d5..9f61c2e0 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs @@ -1697,6 +1697,13 @@ public sealed class GatewaySession : IAsyncDisposable case MxCommandKind.UnsubscribeBulk: RemoveItems(command.UnsubscribeBulk.ServerHandle, command.UnsubscribeBulk.ItemHandles); break; + case MxCommandKind.Unregister: + // Unregister invalidates every item under the server handle in MXAccess, so + // keeping their registrations would grow _items on each register/unregister + // cycle and leave stale tag addresses for the constraint checks to read if + // MXAccess hands the same handle values out again. + RemoveServerItems(command.Unregister.ServerHandle); + break; } } } @@ -2630,6 +2637,28 @@ public sealed class GatewaySession : IAsyncDisposable } } + private void RemoveServerItems(int serverHandle) + { + List<(int ServerHandle, int ItemHandle)>? stale = null; + foreach ((int ServerHandle, int ItemHandle) key in _items.Keys) + { + if (key.ServerHandle == serverHandle) + { + (stale ??= []).Add(key); + } + } + + if (stale is null) + { + return; + } + + foreach ((int ServerHandle, int ItemHandle) key in stale) + { + _items.Remove(key); + } + } + private void DetachEventSubscriber() { lock (_syncRoot) @@ -2659,11 +2688,23 @@ public sealed class GatewaySession : IAsyncDisposable // before any subscriber registered; that never-subscribed session must not enter the // grace window. if (_everHadEventSubscriber - && _detachGrace > TimeSpan.Zero && _activeEventSubscriberCount == 0 && _state is not (SessionState.Closing or SessionState.Closed or SessionState.Faulted)) { - _detachedAtUtc = _eventStreaming.TimeProvider.GetUtcNow(); + DateTimeOffset now = _eventStreaming.TimeProvider.GetUtcNow(); + + // Streaming is client activity, and the detach is its last moment. The lease only + // moves on unary commands, so a client that streamed for longer than the lease with + // no unary call would otherwise detach with a lease already in the past — and the + // next sweep would close it as lease-expired (which takes precedence) before the + // detach-grace window it is entitled to. Renewing here keeps the reconnect window. + _lastClientActivityAt = now; + _leaseExpiresAt = now + LeaseDuration; + + if (_detachGrace > TimeSpan.Zero) + { + _detachedAtUtc = now; + } } } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewaySessionTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewaySessionTests.cs index 587636f2..78393a70 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewaySessionTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/GatewaySessionTests.cs @@ -595,6 +595,93 @@ public sealed class GatewaySessionTests second.Dispose(); } + /// + /// SES-004: a client that only streams (no unary call) for longer than the lease must still + /// get its full detach-grace window when the stream drops. The detach renews the lease, so + /// the session is neither lease-expired nor grace-expired until the grace elapses, and is + /// then closed for detach-grace rather than for the lease. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DetachGrace_StreamOutlivesLease_DetachStillGetsFullGraceWindow() + { + FakeTimeProvider clock = new(DateTimeOffset.UtcNow); + FakeWorkerClient workerClient = new(); + await using GatewaySession session = CreateReadySessionWithDetachGrace( + workerClient, + clock, + detachGrace: TimeSpan.FromSeconds(30)); + + IEventSubscriberLease lease = session.AttachEventSubscriber(maxSubscribers: 1); + + // Stream for longer than the 30-minute lease with no unary command. + clock.Advance(TimeSpan.FromMinutes(31)); + lease.Dispose(); + + clock.Advance(TimeSpan.FromSeconds(5)); + Assert.False(session.IsLeaseExpired(clock.GetUtcNow())); + Assert.False(session.IsDetachGraceExpired(clock.GetUtcNow())); + Assert.False(session.TryBeginCloseIfExpired(clock.GetUtcNow(), out _)); + Assert.Equal(SessionState.Ready, session.State); + + clock.Advance(TimeSpan.FromSeconds(25)); + Assert.False(session.IsLeaseExpired(clock.GetUtcNow())); + Assert.True(session.IsDetachGraceExpired(clock.GetUtcNow())); + } + + /// + /// SES-007: a successful Unregister drops every item registration under that server + /// handle (MXAccess invalidates them all), and leaves other server handles alone. + /// + [Fact] + public void TrackCommandReply_SuccessfulUnregister_PurgesThatServerHandlesItems() + { + GatewaySession session = CreateSession(); + TrackAddItem(session, serverHandle: 1, itemHandle: 10, "A.PV"); + TrackAddItem(session, serverHandle: 1, itemHandle: 11, "B.PV"); + TrackAddItem(session, serverHandle: 1, itemHandle: 12, "C.PV"); + TrackAddItem(session, serverHandle: 2, itemHandle: 10, "D.PV"); + + session.TrackCommandReply( + new MxCommand { Kind = MxCommandKind.Unregister, Unregister = new UnregisterCommand { ServerHandle = 1 } }, + new MxCommandReply { ProtocolStatus = MxAccessGrpcMapper.Ok() }); + + Assert.False(session.TryGetItemRegistration(1, 10, out _)); + Assert.False(session.TryGetItemRegistration(1, 11, out _)); + Assert.False(session.TryGetItemRegistration(1, 12, out _)); + Assert.True(session.TryGetItemRegistration(2, 10, out SessionItemRegistration other)); + Assert.Equal("D.PV", other.TagAddress); + } + + /// A failed Unregister leaves the registrations in place. + [Fact] + public void TrackCommandReply_FailedUnregister_KeepsRegistrations() + { + GatewaySession session = CreateSession(); + TrackAddItem(session, serverHandle: 1, itemHandle: 10, "A.PV"); + + session.TrackCommandReply( + new MxCommand { Kind = MxCommandKind.Unregister, Unregister = new UnregisterCommand { ServerHandle = 1 } }, + new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure } }); + + Assert.True(session.TryGetItemRegistration(1, 10, out _)); + } + + private static void TrackAddItem(GatewaySession session, int serverHandle, int itemHandle, string tagAddress) + { + session.TrackCommandReply( + new MxCommand + { + Kind = MxCommandKind.AddItem, + AddItem = new AddItemCommand { ServerHandle = serverHandle, ItemDefinition = tagAddress }, + }, + new MxCommandReply + { + ProtocolStatus = MxAccessGrpcMapper.Ok(), + AddItem = new AddItemReply { ItemHandle = itemHandle }, + }); + } + /// /// With detach-grace disabled (0), dropping the last subscriber must /// match today's behavior: the session stays with no From 0673b0c76c3b1d3cddd5aa18b94d6994e009885f Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:46:17 -0500 Subject: [PATCH 2/9] fix(sessions): start the host session drain at ApplicationStopping, before Kestrel's drain (SES-001, #247) --- docs/Sessions.md | 8 +- .../Sessions/SessionManager.cs | 51 +++- .../Sessions/SessionShutdownHostedService.cs | 3 + .../Sessions/SessionShutdownOrderingTests.cs | 248 ++++++++++++++++++ 4 files changed, 306 insertions(+), 4 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionShutdownOrderingTests.cs diff --git a/docs/Sessions.md b/docs/Sessions.md index 25e84fb6..75214ef1 100644 --- a/docs/Sessions.md +++ b/docs/Sessions.md @@ -109,7 +109,7 @@ The named pipe is created with `maxNumberOfServerInstances: 1` so a second worke ### SessionShutdownHostedService -`SessionShutdownHostedService` is an `IHostedService` whose only job is to call `ISessionManager.ShutdownAsync` from `StopAsync`. It catches `OperationCanceledException` triggered by the host shutdown timeout and logs a warning so that an over-running shutdown does not surface as an unhandled exception. +`SessionShutdownHostedService` is an `IHostedService` whose only job is to call `ISessionManager.ShutdownAsync` from `StopAsync`. The drain itself has normally already run by then: it starts at `ApplicationStopping` (see [Shutdown Coordination](#shutdown-coordination)), and `ShutdownAsync` awaits that same drain. It catches `OperationCanceledException` triggered by the host shutdown timeout and logs a warning so that an over-running shutdown does not surface as an unhandled exception. ### SessionOpenRequest @@ -354,7 +354,9 @@ Only if both the graceful shutdown and the kill fall-back fail are the original ## Shutdown Coordination -`SessionShutdownHostedService.StopAsync` calls `SessionManager.ShutdownAsync`, which closes every registered session with `GatewayShutdownReason`. Sessions are drained with the same bounded fan-out the lease sweep uses (`MaxParallelSessionCloses`), because a one-at-a-time drain of a full registry at a worst-case worker shutdown timeout each outruns any host stop-timeout and leaves the tail to the orphan killer. Each iteration catches its own exceptions — *every* exception, including from the fallback — calls `KillWorkerAsync` on an uncancellable token, and removes the session, so that neither one stuck worker nor one failing teardown can block or abort the rest of the host's drain: +The drain starts at the host's `IHostApplicationLifetime.ApplicationStopping` signal, not at `SessionShutdownHostedService.StopAsync`. `WebApplication` registers Kestrel's hosted service last, so it stops first, and Kestrel's stop waits for in-flight requests. An open `StreamEvents` call is an in-flight request that ends only when its session closes. When the drain ran from `StopAsync`, every stop with an active stream waited out the whole host shutdown timeout (30 s by default); Kestrel then aborted the streams, and the drain ran on an already-cancelled token, so every worker fell to the kill fallback with no MXAccess cleanup. Starting at `ApplicationStopping`, the drain closes the sessions while Kestrel is still draining: each close completes the subscriber channels, the streams end with `OK`, and Kestrel's drain finishes at once. The manager starts the drain exactly once (`BeginShutdown`), and `ShutdownAsync` — called by `SessionShutdownHostedService.StopAsync`, or directly by a host without a lifetime — awaits that same task. The stop token passed to `ShutdownAsync` cancels the graceful closes still in flight, which turns them into the kill fallback; it never abandons the drain. + +The drain closes every registered session with `GatewayShutdownReason`. Sessions are drained with the same bounded fan-out the lease sweep uses (`MaxParallelSessionCloses`), because a one-at-a-time drain of a full registry at a worst-case worker shutdown timeout each outruns any host stop-timeout and leaves the tail to the orphan killer. Each iteration catches its own exceptions — *every* exception, including from the fallback — calls `KillWorkerAsync` on an uncancellable token, and removes the session, so that neither one stuck worker nor one failing teardown can block or abort the rest of the host's drain: ```csharp MarkStopping(); @@ -422,7 +424,7 @@ public static IServiceCollection AddGatewaySessions(this IServiceCollection serv } ``` -The registry must be a singleton because its `ConcurrentDictionary` is the source of truth for session state across the gRPC service, the lease sweeper, the dashboard, and the shutdown hosted service. Registering `SessionShutdownHostedService` last ensures it is constructed after `ISessionManager` and therefore drains sessions during host stop. +The registry must be a singleton because its `ConcurrentDictionary` is the source of truth for session state across the gRPC service, the lease sweeper, the dashboard, and the shutdown hosted service. Registering `SessionShutdownHostedService` last ensures it is constructed after `ISessionManager` and therefore awaits the session drain during host stop. Constructing `SessionManager` is also what subscribes the drain to `ApplicationStopping`. ## Related Documentation diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs index ffbc7a54..a3f6e526 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs @@ -54,6 +54,18 @@ public sealed class SessionManager : ISessionManager // begun draining does not come back. private int _stopping; + // The one host drain (SES-001). Started at ApplicationStopping, not at the shutdown hosted + // service's StopAsync: WebApplication registers Kestrel's hosted service last, so it stops + // FIRST, and Kestrel's stop waits for in-flight requests — an open StreamEvents is one, and it + // only ends when its session closes. Draining from StopAsync therefore let every stop with an + // active stream wait out the whole host shutdown timeout, after which Kestrel aborted the + // streams and the drain ran on an already-cancelled token, killing every worker. Started here, + // the drain closes the sessions (completing the streams with OK) while Kestrel is still + // draining, and StopAsync just awaits the same task. + private readonly object _shutdownSyncRoot = new(); + private readonly CancellationTokenSource _shutdownCts = new(); + private Task? _shutdownTask; + /// /// Initializes a new instance of . /// @@ -110,7 +122,7 @@ public sealed class SessionManager : ISessionManager // The registration is never disposed: the manager is a host singleton that lives exactly // as long as the lifetime it observes. - applicationLifetime?.ApplicationStopping.Register(MarkStopping); + applicationLifetime?.ApplicationStopping.Register(() => _ = BeginShutdown()); } /// @@ -495,7 +507,44 @@ public sealed class SessionManager : ISessionManager } /// + /// + /// The drain itself starts once, at the host's ApplicationStopping signal when a + /// lifetime was supplied, otherwise at the first call here. This call awaits that drain; + /// firing (the host's stop deadline) cancels the + /// graceful closes still in flight, which degrades them to the kill fallback. + /// public async Task ShutdownAsync(CancellationToken cancellationToken) + { + Task drain = BeginShutdown(); + using CancellationTokenRegistration registration = cancellationToken.Register( + static state => CancelQuietly((CancellationTokenSource)state!), + _shutdownCts); + await drain.ConfigureAwait(false); + } + + private static void CancelQuietly(CancellationTokenSource source) + { + try + { + source.Cancel(); + } + catch (ObjectDisposedException) + { + } + } + + // Starts the drain exactly once and returns it. Closes the open gate synchronously first, so + // an open that races ApplicationStopping is refused (or drained) exactly as before. + private Task BeginShutdown() + { + MarkStopping(); + lock (_shutdownSyncRoot) + { + return _shutdownTask ??= Task.Run(() => ShutdownCoreAsync(_shutdownCts.Token)); + } + } + + private async Task ShutdownCoreAsync(CancellationToken cancellationToken) { // Sessions are drained in parallel: at a worst-case worker shutdown timeout each, a // one-at-a-time drain of a full registry outruns any host stop-timeout and leaves the diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionShutdownHostedService.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionShutdownHostedService.cs index d02fe36c..0ae996a9 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionShutdownHostedService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionShutdownHostedService.cs @@ -18,6 +18,9 @@ public sealed class SessionShutdownHostedService( /// Shuts down all gateway sessions as the host stops. /// + /// The drain normally started earlier, at ApplicationStopping (SES-001): Kestrel's + /// hosted service stops before this one and waits for open event streams, which end only + /// when their sessions close. This call awaits that same drain. /// The catch below is now effectively unreachable: /// no longer aborts on the host's shutdown timeout, it degrades to a kill sweep and logs a /// per-session warning for each session that failed its graceful close. The clause is kept as diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionShutdownOrderingTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionShutdownOrderingTests.cs new file mode 100644 index 00000000..47b23d2a --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionShutdownOrderingTests.cs @@ -0,0 +1,248 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Channels; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.MxGateway.Contracts.Proto; +using ZB.MOM.WW.MxGateway.Server.Configuration; +using ZB.MOM.WW.MxGateway.Server.Metrics; +using ZB.MOM.WW.MxGateway.Server.Sessions; +using ZB.MOM.WW.MxGateway.Server.Workers; + +namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Sessions; + +/// +/// SES-001: the host drain must close sessions while Kestrel is still draining, not after it. +/// WebApplication stops Kestrel's hosted service first, and Kestrel waits for in-flight +/// requests; an open event stream is one, and it ends only when its session closes. +/// +public sealed class SessionShutdownOrderingTests +{ + private static readonly TimeSpan HostShutdownTimeout = TimeSpan.FromSeconds(20); + + /// + /// ApplicationStopping starts the drain by itself: the session is closed gracefully + /// before anyone calls , and the later call (made by + /// the hosted service, possibly on an already-cancelled token) awaits that same drain + /// instead of killing the worker. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ApplicationStopping_StartsDrain_AndShutdownAsyncAwaitsItWithoutKilling() + { + StreamingWorkerClient worker = new(); + ApplicationLifetimeStub lifetime = new(); + using GatewayMetrics metrics = new(); + SessionManager manager = CreateManager(worker, metrics, lifetime); + GatewaySession session = await manager.OpenSessionAsync(new SessionOpenRequest(RequestedBackend: null, ClientSessionName: "ordering", ClientCorrelationId: "ordering-1", CommandTimeout: null), "client-1", ownerKeyId: null, CancellationToken.None); + + lifetime.SignalStopping(); + await worker.ShutdownCalled.WaitAsync(TimeSpan.FromSeconds(5)); + + using CancellationTokenSource alreadyCancelled = new(); + await alreadyCancelled.CancelAsync(); + await manager.ShutdownAsync(alreadyCancelled.Token).WaitAsync(TimeSpan.FromSeconds(5)); + + Assert.Equal(SessionState.Closed, session.State); + Assert.Equal(1, worker.ShutdownCount); + Assert.Equal(0, worker.KillCount); + Assert.Equal(0, metrics.GetSnapshot().OpenSessions); + } + + /// + /// Kestrel-backed: with an event subscriber streaming over a real HTTP request, stopping the + /// host finishes well inside the host shutdown timeout, the request ends normally (its + /// subscriber channel completed, not a transport abort), and the worker is shut down + /// gracefully rather than killed. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task HostStop_WithOpenEventStream_ClosesSessionGracefullyAndEndsStreamCleanly() + { + StreamingWorkerClient worker = new(); + TaskCompletionSource attached = new(TaskCreationOptions.RunContinuationsAsynchronously); + TaskCompletionSource streamOutcome = new(TaskCreationOptions.RunContinuationsAsynchronously); + using GatewayMetrics metrics = new(); + + WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.UseKestrel().UseUrls("http://127.0.0.1:0"); + builder.Services.Configure(options => options.ShutdownTimeout = HostShutdownTimeout); + builder.Services.AddSingleton(provider => CreateManager( + worker, + metrics, + provider.GetRequiredService())); + builder.Services.AddHostedService(); + + await using WebApplication app = builder.Build(); + app.MapGet("/stream/{sessionId}", async (string sessionId, HttpContext context, ISessionManager sessions) => + { + Assert.True(sessions.TryGetSession(sessionId, out GatewaySession? session)); + using IEventSubscriberLease lease = session!.AttachEventSubscriber(maxSubscribers: 1); + await context.Response.WriteAsync("attached\n", context.RequestAborted); + await context.Response.Body.FlushAsync(context.RequestAborted); + attached.TrySetResult(); + try + { + await foreach (MxEvent _ in lease.Reader.ReadAllAsync(context.RequestAborted)) + { + } + + streamOutcome.TrySetResult("completed"); + } + catch (OperationCanceledException) + { + streamOutcome.TrySetResult("aborted"); + throw; + } + }); + + await app.StartAsync(); + string address = app.Services.GetRequiredService().Features.Get()!.Addresses.First(); + ISessionManager manager = app.Services.GetRequiredService(); + GatewaySession session = await manager.OpenSessionAsync(new SessionOpenRequest(RequestedBackend: null, ClientSessionName: "ordering", ClientCorrelationId: "ordering-1", CommandTimeout: null), "client-1", ownerKeyId: null, CancellationToken.None); + + using HttpClient client = new() { BaseAddress = new Uri(address), Timeout = TimeSpan.FromSeconds(10) }; + using HttpResponseMessage response = await client.GetAsync( + $"/stream/{session.SessionId}", + HttpCompletionOption.ResponseHeadersRead); + await attached.Task.WaitAsync(TimeSpan.FromSeconds(5)); + + Stopwatch stopwatch = Stopwatch.StartNew(); + await app.StopAsync(); + stopwatch.Stop(); + + Assert.True( + stopwatch.Elapsed < TimeSpan.FromSeconds(10), + $"host stop took {stopwatch.Elapsed}; the drain did not end the open stream before Kestrel's drain"); + Assert.Equal("completed", await streamOutcome.Task.WaitAsync(TimeSpan.FromSeconds(5))); + Assert.Equal(SessionState.Closed, session.State); + Assert.Equal(1, worker.ShutdownCount); + Assert.Equal(0, worker.KillCount); + } + + private static SessionManager CreateManager( + IWorkerClient worker, + GatewayMetrics metrics, + IHostApplicationLifetime lifetime) + { + GatewayOptions options = new() + { + Sessions = new ZB.MOM.WW.MxGateway.Server.Configuration.SessionOptions { DefaultCommandTimeoutSeconds = 30, MaxSessions = 4 }, + Worker = new WorkerOptions { StartupTimeoutSeconds = 30, ShutdownTimeoutSeconds = 10 }, + }; + + return new SessionManager( + new SessionRegistry(), + new SingleWorkerClientFactory(worker), + Options.Create(options), + metrics, + applicationLifetime: lifetime); + } + + private sealed class SingleWorkerClientFactory(IWorkerClient worker) : ISessionWorkerClientFactory + { + /// + public Task CreateAsync(GatewaySession session, CancellationToken cancellationToken) + => Task.FromResult(worker); + } + + /// + /// Worker client whose event stream stays open until it is shut down or killed, like a real + /// worker's: so a subscriber only ends when the session is torn down. + /// + private sealed class StreamingWorkerClient : IWorkerClient + { + private readonly Channel _events = Channel.CreateUnbounded(); + private readonly TaskCompletionSource _shutdownCalled = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _shutdownCount; + private int _killCount; + private volatile WorkerClientState _state = WorkerClientState.Ready; + + /// + public string SessionId => "session-ordering"; + + /// + public int? ProcessId => 4242; + + /// + public WorkerClientState State => _state; + + /// + public DateTimeOffset LastHeartbeatAt => DateTimeOffset.UtcNow; + + /// Gets a task that completes when a graceful shutdown was requested. + public Task ShutdownCalled => _shutdownCalled.Task; + + /// Gets the number of graceful shutdowns. + public int ShutdownCount => Volatile.Read(ref _shutdownCount); + + /// Gets the number of kills. + public int KillCount => Volatile.Read(ref _killCount); + + /// + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + /// + public Task InvokeAsync(WorkerCommand command, TimeSpan timeout, CancellationToken cancellationToken) + => Task.FromResult(new WorkerCommandReply()); + + /// + public async IAsyncEnumerable ReadEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (WorkerEvent workerEvent in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + { + yield return workerEvent; + } + } + + /// + public Task ShutdownAsync(TimeSpan timeout, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + Interlocked.Increment(ref _shutdownCount); + _state = WorkerClientState.Closed; + _events.Writer.TryComplete(); + _shutdownCalled.TrySetResult(); + return Task.CompletedTask; + } + + /// + public void Kill(string reason) + { + Interlocked.Increment(ref _killCount); + _state = WorkerClientState.Faulted; + _events.Writer.TryComplete(); + } + + /// + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private sealed class ApplicationLifetimeStub : IHostApplicationLifetime + { + private readonly CancellationTokenSource _stopping = new(); + + /// + public CancellationToken ApplicationStarted => CancellationToken.None; + + /// + public CancellationToken ApplicationStopping => _stopping.Token; + + /// + public CancellationToken ApplicationStopped => CancellationToken.None; + + /// Fires . + public void SignalStopping() => _stopping.Cancel(); + + /// + public void StopApplication() => SignalStopping(); + } +} From 159524edd9e955a79edf507b809ca183ee0d2594 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:47:46 -0500 Subject: [PATCH 3/9] fix(dashboard): close the dropped live-read session; subscribe-and-track off the caller's token (DSH-002 #248, DSH-007, #253) --- docs/GatewayDashboardDesign.md | 12 +++ .../Dashboard/DashboardLiveDataService.cs | 63 +++++++++++----- .../DashboardLiveDataServiceTests.cs | 73 +++++++++++++++++++ 3 files changed, 131 insertions(+), 17 deletions(-) diff --git a/docs/GatewayDashboardDesign.md b/docs/GatewayDashboardDesign.md index 40e36bd4..ec757a1f 100644 --- a/docs/GatewayDashboardDesign.md +++ b/docs/GatewayDashboardDesign.md @@ -637,6 +637,18 @@ its lease expires. One session means one worker process backs every dashboard circuit; all access is serialised so the worker sees one in-flight command at a time. Tag reads go through `GatewaySession.SubscribeBulkAsync` / `ReadBulkAsync`. +When a read fails for any reason other than cancellation, the service closes that +session before dropping it, and the next read opens a new one. A command timeout +or a non-Ok bulk reply leaves the session `Ready` with a live worker and its +advised tags; dropping only the reference left it in the registry until its lease +expired, and a Browse page that kept failing opened a new session every poll +until `MaxSessions` refused real clients. A Register failure on a freshly opened +session closes it the same way. The subscribe-and-track step and the eviction +unadvise run on `CancellationToken.None` (bounded by the session's command +timeout) and observe the caller's token only afterwards, so a page that cancels +its read mid-subscribe cannot leave tags advised on the worker that the advise +set does not track. + The advise set that backs those reads is capped at 256 tags (one browse page plus headroom) and evicted least-recently-read-first. Without the cap every tag any viewer ever inspected stayed advised on the single dashboard worker until the diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardLiveDataService.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardLiveDataService.cs index a1aa7168..88c0b63d 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardLiveDataService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardLiveDataService.cs @@ -147,12 +147,18 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync string[] toSubscribe = TouchAndCollectNewTags(tagAddresses, viewer, out HashSet justRead); if (toSubscribe.Length > 0) { - await EvictForAsync(session, serverHandle, toSubscribe.Length, justRead, viewer, now, cancellationToken) + await EvictForAsync(session, serverHandle, toSubscribe.Length, justRead, viewer, now) .ConfigureAwait(false); + // The subscribe and its tracking run as one step that the caller's token cannot + // split (DSH-007): a cancellation that lands after the worker advised the tags but + // before TrackSubscribed would leave advises nothing tracks — never unadvised, not + // counted against MaxSubscribedTags, and re-advised on the next read. The session's + // command timeout still bounds the call; the caller's token is observed after. IReadOnlyList subscribeResults = await session - .SubscribeBulkAsync(serverHandle, toSubscribe, cancellationToken) + .SubscribeBulkAsync(serverHandle, toSubscribe, CancellationToken.None) .ConfigureAwait(false); TrackSubscribed(toSubscribe, subscribeResults, viewer); + cancellationToken.ThrowIfCancellationRequested(); } IReadOnlyList results = await session @@ -178,7 +184,17 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync } catch (Exception exception) when (exception is not OperationCanceledException) { + // Close the session being dropped, not just forget it (DSH-002). A command timeout or a + // non-Ok bulk reply leaves the session Ready with a live x86 worker and its advised + // tags; once unreferenced, nothing sweeps it until its lease expires, and the next poll + // opens another — a repeatedly failing Browse page could fill MaxSessions. + GatewaySession? failedSession = _session; InvalidateSession(); + if (failedSession is not null) + { + await CloseQuietlyAsync(failedSession.SessionId).ConfigureAwait(false); + } + _logger.LogWarning(exception, "Dashboard live read failed; the dashboard session will be re-opened."); return new DashboardLiveReadResult([], exception.Message, null, null); } @@ -280,17 +296,16 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync // back at the cap). A read that subscribes nothing new evicts nothing, but it also // cannot grow the set. // - // Cancellation mid-eviction follows this file's policy: OperationCanceledException - // is deliberately not caught here or in ReadAsync, so it propagates with the tags - // already dropped from tracking — the same end state as a failed unadvise. + // The unadvise runs on CancellationToken.None, so a caller cancelling mid-read cannot + // strand evicted tags advised-but-untracked; only a failed unadvise can, and that is + // logged. private async Task EvictForAsync( GatewaySession session, int serverHandle, int incomingCount, HashSet justRead, string reader, - DateTimeOffset now, - CancellationToken cancellationToken) + DateTimeOffset now) { int overflow = _subscribed.Count + incomingCount - MaxSubscribedTags; if (overflow <= 0) @@ -351,7 +366,10 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync try { - await session.UnsubscribeBulkAsync(serverHandle, evictedHandles, cancellationToken) + // Not the caller's token: the evicted tags are already dropped from tracking, so an + // unadvise abandoned on cancellation would leave them advised with nothing to remove + // them (DSH-007). The session's command timeout bounds the call. + await session.UnsubscribeBulkAsync(serverHandle, evictedHandles, CancellationToken.None) .ConfigureAwait(false); } catch (Exception exception) when (exception is not OperationCanceledException) @@ -506,17 +524,28 @@ public sealed class DashboardLiveDataService : IDashboardLiveDataService, IAsync cancellationToken) .ConfigureAwait(false); - WorkerCommandReply reply = await session.InvokeAsync( - new WorkerCommand - { - Command = new MxCommand + // Until _session holds it, nothing else references the new session: any way out of the + // Register step (a fault, a timeout, the caller cancelling) must close it. + WorkerCommandReply reply; + try + { + reply = await session.InvokeAsync( + new WorkerCommand { - Kind = MxCommandKind.Register, - Register = new RegisterCommand { ClientName = ClientName }, + Command = new MxCommand + { + Kind = MxCommandKind.Register, + Register = new RegisterCommand { ClientName = ClientName }, + }, }, - }, - cancellationToken) - .ConfigureAwait(false); + cancellationToken) + .ConfigureAwait(false); + } + catch + { + await CloseQuietlyAsync(session.SessionId).ConfigureAwait(false); + throw; + } int? serverHandle = reply.Reply?.Register?.ServerHandle; if (serverHandle is null) diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardLiveDataServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardLiveDataServiceTests.cs index af52910e..6c2bbf0c 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardLiveDataServiceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardLiveDataServiceTests.cs @@ -342,6 +342,57 @@ public sealed class DashboardLiveDataServiceTests Assert.Equal(DashboardTagValue.RedactedValueText, succeeded.ValueText); } + /// + /// DSH-002: a read that fails without faulting the session (here a worker-side + /// bulk-read failure) closes the dashboard session it drops, so the next read's + /// fresh session never coexists with an orphaned one. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReadAsync_WhenReadFails_ClosesTheDroppedSession() + { + RecordingWorkerClient worker = new() { FailReadBulk = true }; + await using FakeSessionManager sessionManager = new(worker); + await using DashboardLiveDataService service = CreateService(sessionManager); + + DashboardLiveReadResult first = await service.ReadAsync(["Tank_001.PV"], CancellationToken.None); + Assert.NotNull(first.Error); + Assert.Equal(["dashboard-session-1"], sessionManager.ClosedSessionIds); + + worker.FailReadBulk = false; + DashboardLiveReadResult second = await service.ReadAsync(["Tank_001.PV"], CancellationToken.None); + + Assert.Null(second.Error); + Assert.Equal(2, sessionManager.OpenCount); + Assert.Equal("dashboard-session-2", second.SessionId); + Assert.Equal(["dashboard-session-1"], sessionManager.ClosedSessionIds); + } + + /// + /// DSH-007: a caller that cancels after the worker advised the tags still gets them + /// tracked, so the next read does not advise them a second time. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ReadAsync_CancelledMidSubscribe_StillTracksTheAdvisedTags() + { + RecordingWorkerClient worker = new(); + await using FakeSessionManager sessionManager = new(worker); + await using DashboardLiveDataService service = CreateService(sessionManager); + using CancellationTokenSource pageToken = new(); + worker.OnSubscribe = pageToken.Cancel; + + await Assert.ThrowsAnyAsync( + () => service.ReadAsync(["Tank_001.PV", "Tank_002.PV"], pageToken.Token)); + + worker.OnSubscribe = null; + DashboardLiveReadResult next = await service.ReadAsync(["Tank_001.PV", "Tank_002.PV"], CancellationToken.None); + + Assert.Null(next.Error); + Assert.Equal(["Tank_001.PV", "Tank_002.PV"], worker.SubscribedTags); + Assert.Equal(1, sessionManager.OpenCount); + } + private static DashboardLiveDataService CreateService( ISessionManager sessionManager, bool showTagValues = false, @@ -414,9 +465,13 @@ public sealed class DashboardLiveDataServiceTests return session is not null; } + /// Gets the ids of the sessions the dashboard service closed, in order. + public List ClosedSessionIds { get; } = []; + /// public Task CloseSessionAsync(string sessionId, CancellationToken cancellationToken) { + ClosedSessionIds.Add(sessionId); return Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false)); } @@ -494,6 +549,16 @@ public sealed class DashboardLiveDataServiceTests /// public MxValue? ReadValue { get; set; } + /// Gets or sets a value indicating whether every bulk read throws, as a worker-side failure would. + public bool FailReadBulk { get; set; } + + /// + /// Gets or sets a hook run after a subscribe was applied worker-side and before the + /// reply returns; the fake then honours the command's cancellation token, as a real + /// reply wait would. + /// + public Action? OnSubscribe { get; set; } + /// Gets the tag addresses whose bulk read comes back unsuccessful. public HashSet FailReadFor { get; } = new(StringComparer.OrdinalIgnoreCase); @@ -527,6 +592,12 @@ public sealed class DashboardLiveDataServiceTests break; case MxCommandKind.SubscribeBulk: reply.SubscribeBulk = Subscribe(mxCommand.SubscribeBulk.TagAddresses); + if (OnSubscribe is not null) + { + OnSubscribe(); + cancellationToken.ThrowIfCancellationRequested(); + } + break; case MxCommandKind.UnsubscribeBulk: UnsubscribeCommandCount++; @@ -538,6 +609,8 @@ public sealed class DashboardLiveDataServiceTests UnsubscribedHandles.AddRange(mxCommand.UnsubscribeBulk.ItemHandles); reply.UnsubscribeBulk = new BulkSubscribeReply(); break; + case MxCommandKind.ReadBulk when FailReadBulk: + throw new InvalidOperationException("Simulated worker bulk-read failure."); case MxCommandKind.ReadBulk: reply.ReadBulk = Read(mxCommand.ReadBulk.TagAddresses); break; From 2c22ae6bd48d3351c121e932be321f54aa6af702 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:52:19 -0500 Subject: [PATCH 4/9] fix(workers): bound the heartbeat skip by heartbeat age on the monotonic clock; deadline covers the enqueue; a reply that wins the timeout race is returned (WRK-001, WRK-003, WRK-004, WRK-005, #253) --- docs/GatewayConfiguration.md | 2 +- docs/GatewayProcessDesign.md | 15 ++ .../Workers/WorkerClient.cs | 112 +++++++++- .../Workers/WorkerClientOptions.cs | 12 +- .../Gateway/Workers/WorkerClientTests.cs | 191 ++++++++++++++++++ .../TestSupport/TickObservingTimeProvider.cs | 34 +++- 6 files changed, 345 insertions(+), 21 deletions(-) diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 076705f4..2211b5d6 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -153,7 +153,7 @@ launch CWD (SEC-01, SEC-33). | `MxGateway:Worker:HeartbeatCheckIntervalSeconds` | `5` | How often the gateway checks the age of the worker's last heartbeat against `HeartbeatGraceSeconds`. This is the gateway-side check cadence only; the worker's send interval is `WorkerHeartbeatSendIntervalSeconds`. Must be greater than zero. | | `MxGateway:Worker:HeartbeatIntervalSeconds` | *(unset)* | **Deprecated** alias of `HeartbeatCheckIntervalSeconds` (mxaccessgw#192). The old name implied the worker's send interval, but the value only ever set the gateway's check cadence, which is what it still sets. Setting both keys fails validation. | | `MxGateway:Worker:HeartbeatGraceSeconds` | `15` | Maximum age of the last worker heartbeat before the gateway faults the worker. This must be greater than or equal to `HeartbeatCheckIntervalSeconds`, and strictly greater than `WorkerHeartbeatSendIntervalSeconds` — a grace at or below the worker's send interval declares a healthy worker dead between two heartbeats (mxaccessgw#218). | -| `MxGateway:Worker:HeartbeatStuckCeilingSeconds` | `75` | Ceiling on the gateway's in-flight-command heartbeat skip. While a command is pending the gateway tolerates a stale heartbeat, because the worker STA is busy inside a COM call; once the oldest pending command is older than this, the watchdog faults the worker anyway so a truly stuck COM call cannot hide a dead worker. Must be greater than or equal to `HeartbeatGraceSeconds`. The worker's own watchdog has its separate ceiling, `WorkerHeartbeatStuckCeilingSeconds`. | +| `MxGateway:Worker:HeartbeatStuckCeilingSeconds` | `75` | Ceiling on the gateway's in-flight-command heartbeat skip. While a command is pending the gateway tolerates a stale heartbeat, because the worker STA is busy inside a COM call; once the oldest pending command is older than this, or the last heartbeat is, the watchdog faults the worker anyway so a truly stuck COM call cannot hide a dead worker. The heartbeat-age bound is what stops a client that keeps retrying timed-out commands from holding the skip open: a command that times out leaves the pending set, so with the default 30 s command timeout no pending command ever reaches 75 s. Heartbeat age is measured on the monotonic clock, so a wall-clock step does not fault workers. Must be greater than or equal to `HeartbeatGraceSeconds`. The worker's own watchdog has its separate ceiling, `WorkerHeartbeatStuckCeilingSeconds`. | | `MxGateway:Worker:WorkerHeartbeatSendIntervalSeconds` | `5` | Interval at which the worker sends heartbeats to the gateway. Must be between `1` and `86400`, and below `HeartbeatGraceSeconds`. Conveyed to the worker via `MXGATEWAY_WORKER_HEARTBEAT_SEND_INTERVAL_MS`; a missing or invalid value leaves the worker on 5 s. | | `MxGateway:Worker:WorkerHeartbeatGraceSeconds` | `15` | The worker's own STA-watchdog grace: how long STA activity may go stale before the worker faults `StaHung` (no command in flight). Must be between `1` and `86400` and below `WorkerHeartbeatStuckCeilingSeconds`; validation uses this configured value, not a copied constant (mxaccessgw#224). Conveyed via `MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS`; a missing or invalid value, or a grace the ceiling does not exceed, leaves the worker on 15 s. | | `MxGateway:Worker:WorkerHeartbeatStuckCeilingSeconds` | `75` | Ceiling on the worker's own STA watchdog: once STA activity has been stale this long, the worker faults `StaHung` even while a command is in flight. Must be greater than `WorkerHeartbeatGraceSeconds` and at most `86400`. Raise it together with `HeartbeatStuckCeilingSeconds` for deployments that run very long bulk operations. Conveyed via `MXGATEWAY_WORKER_HEARTBEAT_STUCK_CEILING_MS`; a missing or invalid value leaves the worker on 75 s. | diff --git a/docs/GatewayProcessDesign.md b/docs/GatewayProcessDesign.md index e9c5aefa..02feb937 100644 --- a/docs/GatewayProcessDesign.md +++ b/docs/GatewayProcessDesign.md @@ -647,6 +647,21 @@ Pending command handling: Timeouts should not assume the COM call stopped. A timed-out command may still finish inside the worker. +The command timeout is one deadline for the whole call, the outbound enqueue +included. The outbound channel is bounded, and a write loop parked in a pipe +write the worker is not draining leaves it full; an enqueue bound only to the +caller's token then waited indefinitely for a caller with no deadline. The +common case (room in the channel) is a non-allocating `TryWrite`; only a full +channel waits, under the deadline, and the reply wait gets what is left of it. +An enqueue that runs out of time fails the command as `CommandTimeout` with no +`WorkerCancel`, because the worker never saw it. + +When the deadline fires, the timeout arm owns the outcome only if it removes the +pending entry. If the read loop removed it first (the reply landed right at the +deadline), the caller gets that reply, which is what the metrics already counted, +instead of a `CommandTimeout` that would make it retry a write the worker +performed. + On timeout **and on caller cancellation** the client also forwards a `WorkerCancel` carrying the abandoned correlation id, best-effort: the gateway has stopped waiting, but the worker has not stopped working, and the worker owns diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs index 0f05317c..1257bd45 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClient.cs @@ -56,6 +56,12 @@ public sealed class WorkerClient : IWorkerClient // task before reading State is woken by the next transition instead of polling (mxaccessgw#189). private TaskCompletionSource _stateChanged = new(TaskCreationOptions.RunContinuationsAsynchronously); private DateTimeOffset _lastHeartbeatAt; + + // Monotonic twin of _lastHeartbeatAt (TimeProvider.GetTimestamp), the one the watchdog + // measures staleness on (WRK-005). A wall-clock step — a time-sync correction after a VM + // restore — must neither fault every Ready worker at once nor delay detecting a dead one. + // _lastHeartbeatAt stays for display. Both are written together under _syncRoot. + private long _lastHeartbeatTimestamp; private int? _processId; private string? _recordInfoPinStatus; private int _eventQueueDepth; @@ -140,6 +146,7 @@ public sealed class WorkerClient : IWorkerClient _eventQueueDepthRegistration = _metrics?.RegisterWorkerEventQueueDepthSource( () => Volatile.Read(ref _eventQueueDepth)); _lastHeartbeatAt = _timeProvider.GetUtcNow(); + _lastHeartbeatTimestamp = _timeProvider.GetTimestamp(); } /// @@ -287,7 +294,24 @@ public sealed class WorkerClient : IWorkerClient + $"{MaxSequenceEncodingBytes}-byte sequence-stamp allowance."); } - await EnqueueAsync(commandEnvelope, cancellationToken).ConfigureAwait(false); + // The command deadline covers the enqueue too (WRK-003). The bounded outbound channel + // fills when the write loop is parked in a pipe write the worker is not draining; an + // enqueue bound only to the caller's token then waited indefinitely for a caller with no + // deadline. The common case — room in the channel — takes TryWrite and allocates + // nothing; only a full channel pays for a linked, deadline-bound token. + cancellationToken.ThrowIfCancellationRequested(); + TimeSpan replyTimeout = timeout; + if (!_outboundEnvelopes.Writer.TryWrite(commandEnvelope)) + { + replyTimeout = await EnqueueCommandWithinDeadlineAsync( + commandEnvelope, + correlationId, + pendingCommand, + method, + timeout, + cancellationToken) + .ConfigureAwait(false); + } // one pooled timer instead of a linked CTS + Task.Delay + WhenAny per command. // Task.WaitAsync arms a TimerQueueTimer on the shared timer queue and cancels it when the @@ -303,7 +327,7 @@ public sealed class WorkerClient : IWorkerClient // and messages are unchanged. try { - return await pendingCommand.Task.WaitAsync(timeout, cancellationToken).ConfigureAwait(false); + return await pendingCommand.Task.WaitAsync(replyTimeout, cancellationToken).ConfigureAwait(false); } catch (TimeoutException) when (!cancellationToken.IsCancellationRequested) { @@ -321,14 +345,21 @@ public sealed class WorkerClient : IWorkerClient // reply that won the race — the pending entry is already gone and the caller is about // to see it — never has a cancel chase it. Best-effort by design; the send cannot // throw, so it can never replace the timeout the caller is owed. - if (removed) + if (!removed) { - TrySendCancelForAbandonedCommand( - correlationId, - method, - $"gateway command timeout after {timeout}"); + // The reply (or a fault) won the race between the timer firing and the removal + // above (WRK-004): the read loop already removed the entry, recorded the + // outcome and completed the task. Return that outcome instead of a timeout — + // a Write the worker performed and the metrics counted as succeeded must not + // reach the client as DeadlineExceeded and be retried. + return await pendingCommand.Task.ConfigureAwait(false); } + TrySendCancelForAbandonedCommand( + correlationId, + method, + $"gateway command timeout after {timeout}"); + throw new WorkerClientException( WorkerClientErrorCode.CommandTimeout, timeoutMessage); @@ -625,14 +656,28 @@ public sealed class WorkerClient : IWorkerClient continue; } - DateTimeOffset lastHeartbeatAt = LastHeartbeatAt; - DateTimeOffset now = _timeProvider.GetUtcNow(); - if (now - lastHeartbeatAt <= _options.HeartbeatGrace) + DateTimeOffset lastHeartbeatAt; + long lastHeartbeatTimestamp; + lock (_syncRoot) + { + lastHeartbeatAt = _lastHeartbeatAt; + lastHeartbeatTimestamp = _lastHeartbeatTimestamp; + } + + TimeSpan heartbeatAge = _timeProvider.GetElapsedTime(lastHeartbeatTimestamp); + if (heartbeatAge <= _options.HeartbeatGrace) { continue; } - if (TryGetOldestPendingCommandAge(out TimeSpan oldestCommandAge) + // The in-flight-command skip is bounded by the heartbeat's own age as well as by the + // oldest command's (WRK-001). A command that hits its timeout leaves + // _pendingCommands, so with a command timeout below the ceiling no pending entry + // ever reaches it: a client that keeps issuing (and timing out) commands against a + // worker that has gone silent would otherwise hold the skip open forever, while an + // idle session over the same worker faults after HeartbeatGrace. + if (heartbeatAge <= _options.HeartbeatStuckCeiling + && TryGetOldestPendingCommandAge(out TimeSpan oldestCommandAge) && oldestCommandAge <= _options.HeartbeatStuckCeiling) { continue; @@ -1091,6 +1136,7 @@ public sealed class WorkerClient : IWorkerClient ? _processId ?? _connection.ProcessHandle?.ProcessId : ready.WorkerProcessId; _lastHeartbeatAt = _timeProvider.GetUtcNow(); + _lastHeartbeatTimestamp = _timeProvider.GetTimestamp(); SetStateUnderLock(WorkerClientState.Ready); _workerStartRecorded = true; } @@ -1146,6 +1192,7 @@ public sealed class WorkerClient : IWorkerClient lock (_syncRoot) { _lastHeartbeatAt = _timeProvider.GetUtcNow(); + _lastHeartbeatTimestamp = _timeProvider.GetTimestamp(); if (heartbeat.WorkerProcessId != 0) { _processId = heartbeat.WorkerProcessId; @@ -1381,6 +1428,49 @@ public sealed class WorkerClient : IWorkerClient } } + /// + /// Slow path of the command enqueue, taken only when the outbound channel is full: waits for + /// room under the caller's token AND the command deadline, and returns what is left of the + /// deadline for the reply wait. + /// + /// Command envelope to enqueue. + /// Command correlation id. + /// The command's pending entry. + /// Command method name for metrics and messages. + /// The whole command deadline. + /// The caller's token. + /// The part of left for the reply wait. + private async Task EnqueueCommandWithinDeadlineAsync( + WorkerEnvelope commandEnvelope, + string correlationId, + PendingCommand pendingCommand, + string method, + TimeSpan timeout, + CancellationToken cancellationToken) + { + using CancellationTokenSource deadlineCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadlineCts.CancelAfter(timeout); + try + { + await EnqueueAsync(commandEnvelope, deadlineCts.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // The deadline fired with the envelope never queued, so there is nothing for the + // worker to drop and no WorkerCancel to send. + string timeoutMessage = $"Worker command {method} timed out after {timeout} waiting for the outbound queue."; + RemovePendingCommandAsFailed( + correlationId, + pendingCommand, + WorkerClientErrorCode.CommandTimeout, + timeoutMessage); + throw new WorkerClientException(WorkerClientErrorCode.CommandTimeout, timeoutMessage); + } + + TimeSpan remaining = timeout - _timeProvider.GetElapsedTime(pendingCommand.StartTimestamp); + return remaining > TimeSpan.Zero ? remaining : TimeSpan.FromTicks(1); + } + /// Creates gateway hello envelope. /// The hello envelope. private WorkerEnvelope CreateGatewayHelloEnvelope() diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClientOptions.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClientOptions.cs index 6113cb96..e1f536d0 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClientOptions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerClientOptions.cs @@ -57,11 +57,13 @@ public sealed class WorkerClientOptions /// /// Ceiling on the in-flight-command heartbeat-skip. When /// a command has been pending on the gateway↔worker pipe for longer - /// than this, the gateway-side HeartbeatLoopAsync fires the - /// HeartbeatExpired fault even if commands are still pending; - /// a truly stuck COM call shouldn't keep the watchdog suppressed - /// indefinitely. Mirrors HeartbeatStuckCeiling on - /// the worker side. + /// than this, or the last heartbeat is older than this, the gateway-side + /// HeartbeatLoopAsync fires the HeartbeatExpired fault even + /// if commands are still pending; a truly stuck COM call shouldn't keep + /// the watchdog suppressed indefinitely. The heartbeat-age bound matters + /// because a command that times out leaves the pending set, so with a + /// command timeout below this ceiling no pending entry ever reaches it. + /// Mirrors HeartbeatStuckCeiling on the worker side. /// public TimeSpan HeartbeatStuckCeiling { get; init; } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs index 789cb5c3..08b9a864 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs @@ -1152,6 +1152,197 @@ public sealed class WorkerClientTests Assert.Equal(WorkerClientState.Faulted, client.State); } + /// + /// WRK-001: a client that keeps issuing commands against a silent worker, each abandoned + /// before it reaches the stuck ceiling (here by caller cancellation; a command timeout + /// removes the entry the same way), must not hold the in-flight-command skip open forever. + /// Once the heartbeat itself is older than the ceiling the watchdog faults. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task HeartbeatMonitor_WhenYoungCommandsKeepArrivingPastStuckCeiling_FaultsClient() + { + TickObservingTimeProvider clock = new() { WatchedDueTime = TimeSpan.FromSeconds(1) }; + clock.SetUtcNow(DateTimeOffset.Parse("2026-05-20T15:00:00Z", System.Globalization.CultureInfo.InvariantCulture)); + await using PipePair pipePair = await PipePair.CreateAsync(); + await using WorkerClient client = CreateClient( + pipePair, + new WorkerClientOptions + { + HeartbeatGrace = TimeSpan.FromSeconds(15), + HeartbeatCheckInterval = TimeSpan.FromSeconds(1), + EventChannelCapacity = 8, + HeartbeatStuckCeiling = TimeSpan.FromSeconds(30), + }, + timeProvider: clock); + await CompleteHandshakeAsync(client, pipePair); + + CancellationTokenSource? previousCaller = null; + Task? previousInvoke = null; + for (int round = 0; round < 6 && client.State == WorkerClientState.Ready; round++) + { + CancellationTokenSource caller = new(); + Task invoke = client.InvokeAsync( + CreateCommand(MxCommandKind.Ping), + TestTimeout, + caller.Token); + await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout); + + // Abandon the older command so the oldest pending one is never more than 10 s old. + if (previousCaller is not null) + { + await previousCaller.CancelAsync(); + await Assert.ThrowsAnyAsync(async () => await previousInvoke!.WaitAsync(TestTimeout)); + previousCaller.Dispose(); + await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout); + } + + previousCaller = caller; + previousInvoke = invoke; + for (int i = 0; i < 10 && client.State == WorkerClientState.Ready; i++) + { + await clock.AdvanceAndAwaitTickAsync(TimeSpan.FromSeconds(1), TestTimeout); + } + } + + await WaitUntilAsync(() => client.State == WorkerClientState.Faulted, TestTimeout); + Assert.Equal(WorkerClientState.Faulted, client.State); + previousCaller?.Dispose(); + } + + /// + /// WRK-005: heartbeat staleness is measured on the monotonic clock, so a forward step of the + /// wall clock larger than the grace does not fault a worker whose heartbeat is current. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task HeartbeatMonitor_WhenWallClockStepsForward_DoesNotFault() + { + TickObservingTimeProvider clock = new() { WatchedDueTime = TimeSpan.FromSeconds(1) }; + clock.SetUtcNow(DateTimeOffset.Parse("2026-05-20T16:00:00Z", System.Globalization.CultureInfo.InvariantCulture)); + await using PipePair pipePair = await PipePair.CreateAsync(); + await using WorkerClient client = CreateClient( + pipePair, + new WorkerClientOptions + { + HeartbeatGrace = TimeSpan.FromSeconds(15), + HeartbeatCheckInterval = TimeSpan.FromSeconds(1), + EventChannelCapacity = 8, + }, + timeProvider: clock); + await CompleteHandshakeAsync(client, pipePair); + + // The wall clock steps 60 s forward; the monotonic clock moves only 1 s. + clock.MonotonicLag = TimeSpan.FromSeconds(59); + await clock.AdvanceAndAwaitTickAsync(TimeSpan.FromSeconds(60), TestTimeout); + for (int i = 0; i < 3; i++) + { + await clock.AdvanceAndAwaitTickAsync(TimeSpan.FromSeconds(1), TestTimeout); + } + + Assert.Equal(WorkerClientState.Ready, client.State); + } + + /// + /// WRK-003: the command deadline covers the outbound enqueue. With the write loop parked in a + /// pipe write and the outbound channel full, a caller with no token of its own still gets + /// after its timeout instead of waiting + /// indefinitely. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task InvokeAsync_WhenOutboundQueueIsFull_TimesOutWithinTheCommandTimeout() + { + await using PipePair pipePair = await PipePair.CreateAsync(); + await using StallableWriteStream gatewayStream = new(pipePair.GatewayStream); + WorkerClientOptions options = new() + { + MaxPendingCommands = 1, + HeartbeatGrace = TimeSpan.FromSeconds(30), + HeartbeatCheckInterval = TimeSpan.FromSeconds(30), + }; + await using WorkerClient client = CreateClient(pipePair, options, gatewayStream: gatewayStream); + await CompleteHandshakeAsync(client, pipePair); + gatewayStream.StallWrites(); + + // Same fill as the shutdown test: three abandoned commands leave the write loop parked on + // the first and the five-envelope channel full behind it. + for (int round = 0; round < 3; round++) + { + using CancellationTokenSource callerCts = new(); + Task invokeTask = client.InvokeAsync( + CreateCommand(MxCommandKind.Advise), + TestTimeout, + callerCts.Token); + if (round == 0) + { + await gatewayStream.FirstStalledWrite.WaitAsync(TestTimeout); + } + + await callerCts.CancelAsync(); + await Assert.ThrowsAnyAsync( + async () => await invokeTask.WaitAsync(TestTimeout)); + } + + TimeSpan commandTimeout = TimeSpan.FromMilliseconds(300); + WorkerClientException exception = await Assert.ThrowsAsync( + async () => await client.InvokeAsync(CreateCommand(MxCommandKind.Ping), commandTimeout, CancellationToken.None) + .WaitAsync(TestTimeout)); + + Assert.Equal(WorkerClientErrorCode.CommandTimeout, exception.ErrorCode); + Assert.Equal(WorkerClientState.Ready, client.State); + + // The slot was released: the next command is admitted (and times out the same way) + // rather than refused with PendingCommandLimitExceeded. + WorkerClientException second = await Assert.ThrowsAsync( + async () => await client.InvokeAsync(CreateCommand(MxCommandKind.Ping), commandTimeout, CancellationToken.None) + .WaitAsync(TestTimeout)); + Assert.Equal(WorkerClientErrorCode.CommandTimeout, second.ErrorCode); + } + + /// + /// WRK-004: when a reply lands right at the deadline, the caller's outcome agrees with the + /// metrics — every command counted as succeeded returned its reply, never a timeout. Runs + /// the race many times; before the fix a reply that won the removal still surfaced as + /// . + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task InvokeAsync_WhenReplyRacesTheDeadline_OutcomeMatchesTheSucceededMetric() + { + using GatewayMetrics metrics = new(); + await using PipePair pipePair = await PipePair.CreateAsync(); + await using WorkerClient client = CreateClient(pipePair, metrics: metrics); + await CompleteHandshakeAsync(client, pipePair); + + int returnedReplies = 0; + TimeSpan commandTimeout = TimeSpan.FromMilliseconds(15); + for (int i = 0; i < 60; i++) + { + Task invoke = client.InvokeAsync( + CreateCommand(MxCommandKind.Ping), + commandTimeout, + CancellationToken.None); + WorkerEnvelope command = await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout); + await Task.Delay(commandTimeout - TimeSpan.FromMilliseconds(i % 4)); + await pipePair.WriteAsync(CreateCommandReplyEnvelope(command.CorrelationId, MxCommandKind.Ping)); + + try + { + await invoke.WaitAsync(TestTimeout); + returnedReplies++; + } + catch (WorkerClientException exception) when (exception.ErrorCode == WorkerClientErrorCode.CommandTimeout) + { + // The timeout won: the abandonment forwards a WorkerCancel; drain it. + WorkerEnvelope cancel = await pipePair.WorkerReader.ReadAsync().AsTask().WaitAsync(TestTimeout); + Assert.Equal(WorkerEnvelope.BodyOneofCase.WorkerCancel, cancel.BodyCase); + } + } + + Assert.Equal(metrics.GetSnapshot().CommandsSucceeded, returnedReplies); + } + /// /// A transient burst that exceeds /// must be diff --git a/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/TickObservingTimeProvider.cs b/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/TickObservingTimeProvider.cs index 0ac09bd9..91816f9b 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/TickObservingTimeProvider.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/TickObservingTimeProvider.cs @@ -13,9 +13,27 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider private long _watchedTimersCreated; private long _watchedTimersConsumed; + private long _timestampReads; + /// Gets the number of times has been read. public long UtcNowReads => Interlocked.Read(ref _utcNowReads); + /// + /// Gets the number of times has been read. A loop that measures + /// elapsed time on the monotonic clock () + /// evaluates its condition through this read rather than through . + /// + public long TimestampReads => Interlocked.Read(ref _timestampReads); + + /// + /// Gets or sets how far the monotonic timestamp () lags the wall + /// clock. Raising it right before an of the same size + /// models a host wall-clock step: and the timers jump, the + /// monotonic clock does not. The timers run on the wall clock here, so the step is modelled + /// on the timestamp side. + /// + public TimeSpan MonotonicLag { get; set; } + /// public override DateTimeOffset GetUtcNow() { @@ -23,6 +41,13 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider return base.GetUtcNow(); } + /// + public override long GetTimestamp() + { + Interlocked.Increment(ref _timestampReads); + return base.GetTimestamp() - (long)(MonotonicLag.TotalSeconds * TimestampFrequency); + } + /// /// Gets or sets the due time of the timer the loop under test re-arms each iteration /// (for Task.Delay(interval, timeProvider, ct) this is the interval). When set, @@ -66,8 +91,9 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider } /// - /// Advances the clock and waits until a consumer has read again, - /// which proves the awakened loop evaluated its condition against the advanced time. + /// Advances the clock and waits until a consumer has read or + /// again, which proves the awakened loop evaluated its condition + /// against the advanced time. /// /// Amount to advance. /// Real-time bound on the wait. @@ -86,9 +112,9 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider Interlocked.Increment(ref _watchedTimersConsumed); } - long before = UtcNowReads; + long before = UtcNowReads + TimestampReads; Advance(delta); - while (UtcNowReads == before) + while (UtcNowReads + TimestampReads == before) { await Task.Yield(); cts.Token.ThrowIfCancellationRequested(); From 196465ef9c6b01ee2dd12420daa087b3aa0af051 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:56:05 -0500 Subject: [PATCH 5/9] 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; From 9c3a4c0eae656930a0a469fdee0e2989173b79a3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:57:41 -0500 Subject: [PATCH 6/9] fix(sessions): drop per-session event metrics after the session dispose (WRK-008, #253) --- docs/Metrics.md | 2 +- docs/Sessions.md | 2 +- .../Sessions/SessionManager.cs | 15 ++++++++-- .../Gateway/Sessions/SessionManagerTests.cs | 29 +++++++++++++++++++ 4 files changed, 44 insertions(+), 4 deletions(-) diff --git a/docs/Metrics.md b/docs/Metrics.md index ad9490a4..dd7caa61 100644 --- a/docs/Metrics.md +++ b/docs/Metrics.md @@ -106,7 +106,7 @@ The scalar fields mirror the counters and gauges. The three dictionaries provide - `CommandFailuresByMethod` keys by gRPC method name. - `EventsByFamily` keys by event family (the `Family` enum on a worker event). -- `EventsBySession` keys by `sessionId`; entries are removed via `RemoveSessionEvents` when a session closes so the map does not grow without bound. +- `EventsBySession` keys by `sessionId`; entries are removed via `RemoveSessionEvents` when a session closes so the map does not grow without bound. The removal runs after the session (and with it the worker client, whose dispose waits for its read loop) is disposed: on the kill path the read loop is cancelled but not awaited, and a frame it had already read would otherwise re-create the entry after the removal. `EventsReceived` is read with `Interlocked.Read(ref _eventsReceived)` because `EventReceived` increments it via `Interlocked.Increment` outside the lock to keep the event-ingestion path non-blocking. `CommandsStarted`, `CommandsSucceeded`, `CommandsFailed`, and `CommandFailuresByMethod` are read the same way: the command counters run two-to-three times per gRPC call, so they are recorded with `Interlocked` and a `ConcurrentDictionary` rather than under `_syncRoot` (PERF-02). The two queue depths are pulled from their registered sources before the lock is taken, since those delegates reach into subscriber channels and worker clients. diff --git a/docs/Sessions.md b/docs/Sessions.md index 75214ef1..c27f6e18 100644 --- a/docs/Sessions.md +++ b/docs/Sessions.md @@ -196,7 +196,7 @@ catch (Exception exception) } ``` -`RollBackOpenAsync` faults the session and, when it had been registered, routes it through `RemoveSessionAsync` — the single removal path every teardown uses, which deregisters, drops the session's per-session event metrics, releases the slot and disposes, in that order. The order matters because releasing the semaphore before disposal would let the next open race the worker process tear-down on the same machine. A session that was never registered (id collision) releases the slot and disposes directly. The open-session gauge is not touched by the rollback: `SessionOpened` is recorded inside the attach gate described next, after which nothing in the open sequence can fail. +`RollBackOpenAsync` faults the session and, when it had been registered, routes it through `RemoveSessionAsync` — the single removal path every teardown uses, which deregisters, releases the slot, disposes, and then drops the session's per-session event metrics (after the dispose, so a worker read loop still finishing a frame cannot re-create the entry). The order matters because releasing the semaphore before disposal would let the next open race the worker process tear-down on the same machine. A session that was never registered (id collision) releases the slot and disposes directly. The open-session gauge is not touched by the rollback: `SessionOpened` is recorded inside the attach gate described next, after which nothing in the open sequence can fail. #### Close or kill during worker startup diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs index a3f6e526..549b32a8 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionManager.cs @@ -746,9 +746,20 @@ public sealed class SessionManager : ISessionManager return; } - _metrics.RemoveSessionEvents(session.SessionId); ReleaseSessionSlot(); - await removedSession.DisposeAsync().ConfigureAwait(false); + try + { + await removedSession.DisposeAsync().ConfigureAwait(false); + } + finally + { + // After the dispose, not before (WRK-008): on the kill path the worker client's read + // loop is cancelled but not awaited, so it can still be inside DispatchEnvelope for a + // frame it already read, and its EventReceived would re-create the per-session entry + // that nothing removes again. Disposing the session disposes its worker client, which + // waits (bounded) for that loop to stop. + _metrics.RemoveSessionEvents(session.SessionId); + } } private void ReleaseSessionSlot() diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs index e2596bfe..70a2759c 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs @@ -1939,6 +1939,28 @@ public sealed class SessionManagerTests Assert.Equal(0, metrics.GetSnapshot().OpenSessions); } + /// + /// WRK-008: a worker read loop that records one more event while the killed session's + /// worker client is being disposed must not leave a per-session metrics entry behind; the + /// entry is dropped after the dispose. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task KillWorkerAsync_EventRecordedDuringWorkerDispose_LeavesNoPerSessionEntry() + { + using GatewayMetrics metrics = new(); + string? sessionId = null; + FakeWorkerClient workerClient = new() { OnDispose = () => metrics.EventReceived(sessionId!, "OnDataChange") }; + SessionManager manager = CreateManager(new FakeSessionWorkerClientFactory(workerClient), metrics: metrics); + GatewaySession session = await manager.OpenSessionAsync(CreateOpenRequest(), "client-1", ownerKeyId: null, CancellationToken.None); + sessionId = session.SessionId; + + await manager.KillWorkerAsync(session.SessionId, "test-kill", CancellationToken.None); + + Assert.Equal(1, workerClient.DisposeCount); + Assert.False(metrics.GetSnapshot().EventsBySession.ContainsKey(session.SessionId)); + } + /// Creates a session manager for testing. /// Worker client factory. /// Session registry; defaults to a new registry. @@ -2467,9 +2489,16 @@ public sealed class SessionManagerTests public ValueTask DisposeAsync() { DisposeCount++; + OnDispose?.Invoke(); return ValueTask.CompletedTask; } + /// + /// Gets a hook run inside , standing in for a worker read loop + /// that is still finishing a frame while the client is disposed. + /// + public Action? OnDispose { get; init; } + /// Waits for shutdown to start on the fake worker client. /// A task that represents the asynchronous operation. public Task WaitForShutdownStartAsync() From 87b8f8da0970d014e5bfadefa36bd11ea0eccb03 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:00:16 -0500 Subject: [PATCH 7/9] fix(workers): orphan cleanup skips workers whose owning gateway is still running (WRK-009, #253) --- gateway.md | 14 +- .../Workers/IRunningProcessInspector.cs | 21 ++- .../Workers/OrphanWorkerTerminator.cs | 101 +++++++++++-- .../Workers/SystemRunningProcessInspector.cs | 140 +++++++++++++++++- .../OrphanWorkerCleanupHostedServiceTests.cs | 6 + .../Workers/OrphanWorkerTerminatorTests.cs | 122 +++++++++++++-- 6 files changed, 381 insertions(+), 23 deletions(-) diff --git a/gateway.md b/gateway.md index 6b0b4412..0ce6dd3a 100644 --- a/gateway.md +++ b/gateway.md @@ -1050,9 +1050,17 @@ Policy: - stuck workers are killed by process id, - gateway restart does not reattach old workers; `OrphanWorkerCleanupHostedService` runs `OrphanWorkerTerminator` once on startup — before the server accepts - sessions — to kill leftover `ZB.MOM.WW.MxGateway.Worker.exe` processes (matched by the - configured worker executable path, or by image name when the x64 gateway cannot - introspect the x86 worker's module) left behind by a previous unclean run. + sessions — to kill leftover `ZB.MOM.WW.MxGateway.Worker.exe` processes left behind by + a previous unclean run. A candidate must match the configured worker executable path + (when its path is readable), and its command line's `--pipe-name` + (`mxgw-{gatewayPid}-{sessionUid}`) must name a gateway process that is no longer running + (or whose id was recycled: it started after the worker). A worker of a gateway that is + still running — a second gateway from the same build output, a test host — is left + alone. When neither the path nor the command line can be read, the process is left + alone and logged, since an image-name match alone could be another build's worker; when + the path matches but the command line cannot be read, the path decides, as before. The + command line is read with `NtQueryInformationProcess(ProcessCommandLineInformation)`, + which works from the x64 gateway on the x86 worker. Because each client owns one worker, a crash or leak affects only that session. diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/IRunningProcessInspector.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/IRunningProcessInspector.cs index fda5caa0..e85f70e1 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/IRunningProcessInspector.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/IRunningProcessInspector.cs @@ -18,6 +18,16 @@ public interface IRunningProcessInspector /// Forcibly terminates the process with the given identifier. /// Identifier of the process to terminate. void Kill(int processId); + + /// + /// Reports whether a process with the given identifier is running, and when it started. + /// Orphan cleanup uses it to tell a worker whose owning gateway is still alive from a real + /// orphan, and the start time to reject a recycled process id. + /// + /// Identifier of the process to look up. + /// The process start time, or when it cannot be read. + /// when the process is running; otherwise . + bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt); } /// Identifying information for a running process candidate. @@ -26,4 +36,13 @@ public interface IRunningProcessInspector /// Fully-qualified path to the process main module, or /// when it could not be read (e.g. access denied). /// -public sealed record RunningProcessInfo(int ProcessId, string? ExecutablePath); +/// +/// The process command line, or when it could not be read (or the +/// platform offers no way to read it). +/// +/// The process start time, or when it could not be read. +public sealed record RunningProcessInfo( + int ProcessId, + string? ExecutablePath, + string? CommandLine = null, + DateTimeOffset? StartedAt = null); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs index 7ac29c2d..3fbeb0c0 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs @@ -60,7 +60,7 @@ public sealed class OrphanWorkerTerminator continue; } - if (!IsOrphanWorker(candidate, configuredPath)) + if (!IsOrphanWorker(candidate, configuredPath, currentProcessId)) { continue; } @@ -94,21 +94,104 @@ public sealed class OrphanWorkerTerminator return terminated; } - private static bool IsOrphanWorker(RunningProcessInfo candidate, string? configuredPath) + private bool IsOrphanWorker(RunningProcessInfo candidate, string? configuredPath, int currentProcessId) { // When the executable path is readable, require an exact match against // the configured worker path so unrelated processes that merely share // the image name are never killed. - if (candidate.ExecutablePath is { } path) + if (candidate.ExecutablePath is { } path + && (configuredPath is null + || !string.Equals(path, configuredPath, StringComparison.OrdinalIgnoreCase))) { - return configuredPath is not null - && string.Equals(path, configuredPath, StringComparison.OrdinalIgnoreCase); + return false; } - // A null path means the x64 gateway could not introspect the module — - // the expected case for the x86 worker. Image-name match is the only - // signal available; treat it as an orphan. - return true; + // Ownership (WRK-009): the worker's --pipe-name carries the PID of the gateway that + // launched it (mxgw-{gatewayPid}-{sessionUid}). A worker whose gateway is still running + // belongs to that gateway — a second gateway started from the same build output, a test + // host — and killing it would fault that gateway's live sessions. + if (TryParseOwnerGatewayProcessId(candidate.CommandLine, out int ownerProcessId)) + { + if (ownerProcessId == currentProcessId) + { + return false; + } + + if (_inspector.TryGetRunningProcess(ownerProcessId, out DateTimeOffset? ownerStartedAt) + && !IsRecycledProcessId(ownerStartedAt, candidate.StartedAt)) + { + _logger.LogInformation( + "Leaving worker process {ProcessId} alone: its gateway process {OwnerProcessId} is still running.", + candidate.ProcessId, + ownerProcessId); + return false; + } + + return true; + } + + if (candidate.ExecutablePath is not null) + { + // The configured path matches but the command line could not be read or carries no + // owner: the path is the only signal, as before. + return true; + } + + // Neither the path nor the command line could be read, so nothing ties the process to + // this gateway's worker build. Image name alone is not enough: a same-named worker from a + // different build (a CI checkout) would be killed. + _logger.LogWarning( + "Leaving worker-named process {ProcessId} alone: neither its executable path nor its command line could be read to confirm it is an orphan of this gateway's worker build.", + candidate.ProcessId); + return false; + } + + // An owner process that started after the worker cannot have launched it: the gateway that + // did is gone and its id was reused. Unknown start times give the live process the benefit + // of the doubt. + private static bool IsRecycledProcessId(DateTimeOffset? ownerStartedAt, DateTimeOffset? workerStartedAt) + => ownerStartedAt is { } owner + && workerStartedAt is { } worker + && owner > worker; + + /// + /// Extracts the owning gateway PID from a worker command line's --pipe-name value + /// (mxgw-{gatewayPid}-{sessionUid}, or the older mxaccess-gateway-{gatewayPid}-…). + /// + /// The worker command line, or . + /// The parsed gateway PID. + /// when an owner PID was found. + internal static bool TryParseOwnerGatewayProcessId(string? commandLine, out int ownerProcessId) + { + ownerProcessId = 0; + if (string.IsNullOrEmpty(commandLine)) + { + return false; + } + + const string PipeNameSwitch = "--pipe-name"; + int switchIndex = commandLine.IndexOf(PipeNameSwitch, StringComparison.Ordinal); + if (switchIndex < 0) + { + return false; + } + + ReadOnlySpan rest = commandLine.AsSpan(switchIndex + PipeNameSwitch.Length).TrimStart().TrimStart('"'); + foreach (string prefix in (string[])["mxgw-", "mxaccess-gateway-"]) + { + if (!rest.StartsWith(prefix, StringComparison.Ordinal)) + { + continue; + } + + ReadOnlySpan afterPrefix = rest[prefix.Length..]; + int dash = afterPrefix.IndexOf('-'); + return dash > 0 + && int.TryParse(afterPrefix[..dash], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out ownerProcessId) + && ownerProcessId > 0; + } + + return false; } private string? ResolveConfiguredExecutablePath() diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemRunningProcessInspector.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemRunningProcessInspector.cs index 5eabef13..c4a9769b 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemRunningProcessInspector.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemRunningProcessInspector.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Runtime.InteropServices; namespace ZB.MOM.WW.MxGateway.Server.Workers; @@ -7,6 +8,14 @@ namespace ZB.MOM.WW.MxGateway.Server.Workers; /// public sealed class SystemRunningProcessInspector : IRunningProcessInspector { + // PROCESS_QUERY_LIMITED_INFORMATION: the least access that reads the image path, the command + // line and the start time, and the one granted across WOW64 (x64 gateway, x86 worker). + private const uint ProcessQueryLimitedInformation = 0x1000; + + // PROCESSINFOCLASS.ProcessCommandLineInformation (Windows 8.1+). Returns a UNICODE_STRING + // followed by its buffer, and works across bitness, unlike reading the target's PEB. + private const int ProcessCommandLineInformation = 60; + /// public IReadOnlyList GetProcessesByName(string processName) { @@ -16,7 +25,11 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector { foreach (Process process in processes) { - results.Add(new RunningProcessInfo(process.Id, TryGetExecutablePath(process))); + results.Add(new RunningProcessInfo( + process.Id, + TryGetExecutablePath(process), + TryGetCommandLine(process.Id), + TryGetStartTime(process))); } } finally @@ -37,6 +50,102 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector process.Kill(entireProcessTree: true); } + /// + public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt) + { + startedAt = null; + Process process; + try + { + process = Process.GetProcessById(processId); + } + catch (ArgumentException) + { + // Not running. + return false; + } + catch (InvalidOperationException) + { + return false; + } + + using (process) + { + try + { + if (process.HasExited) + { + return false; + } + } + catch (Exception exception) when (exception is InvalidOperationException + or System.ComponentModel.Win32Exception + or NotSupportedException) + { + // Cannot open it to ask, but GetProcessById found it: treat it as running. + } + + startedAt = TryGetStartTime(process); + return true; + } + } + + /// + /// Reads another process's command line. Windows only; elsewhere or + /// when it cannot be read (access denied, the process exited). + /// + /// The process to read. + /// The command line, or . + internal static string? TryGetCommandLine(int processId) + { + if (!OperatingSystem.IsWindows()) + { + return null; + } + + IntPtr handle = OpenProcess(ProcessQueryLimitedInformation, inheritHandle: false, processId); + if (handle == IntPtr.Zero) + { + return null; + } + + try + { + // The sizing call fails with STATUS_INFO_LENGTH_MISMATCH and reports the size needed. + _ = NtQueryInformationProcess(handle, ProcessCommandLineInformation, IntPtr.Zero, 0, out int length); + if (length <= 0 || length > 1024 * 1024) + { + return null; + } + + IntPtr buffer = Marshal.AllocHGlobal(length); + try + { + int status = NtQueryInformationProcess(handle, ProcessCommandLineInformation, buffer, length, out _); + if (status != 0) + { + return null; + } + + // UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } — the + // pointer is naturally aligned, so it sits at offset IntPtr.Size. + int byteLength = (ushort)Marshal.ReadInt16(buffer); + IntPtr text = Marshal.ReadIntPtr(buffer, IntPtr.Size); + return byteLength == 0 || text == IntPtr.Zero + ? string.Empty + : Marshal.PtrToStringUni(text, byteLength / 2); + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + finally + { + _ = CloseHandle(handle); + } + } + private static string? TryGetExecutablePath(Process process) { try @@ -52,4 +161,33 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector return null; } } + + private static DateTimeOffset? TryGetStartTime(Process process) + { + try + { + return new DateTimeOffset(process.StartTime.ToUniversalTime(), TimeSpan.Zero); + } + catch (Exception exception) when (exception is InvalidOperationException + or System.ComponentModel.Win32Exception + or NotSupportedException) + { + return null; + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr OpenProcess(uint desiredAccess, bool inheritHandle, int processId); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CloseHandle(IntPtr handle); + + [DllImport("ntdll.dll")] + private static extern int NtQueryInformationProcess( + IntPtr processHandle, + int processInformationClass, + IntPtr processInformation, + int processInformationLength, + out int returnLength); } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerCleanupHostedServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerCleanupHostedServiceTests.cs index f41ba089..13cf0b55 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerCleanupHostedServiceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerCleanupHostedServiceTests.cs @@ -98,5 +98,11 @@ public sealed class OrphanWorkerCleanupHostedServiceTests } public void Kill(int processId) => Killed.Add(processId); + + public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt) + { + startedAt = null; + return false; + } } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerTerminatorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerTerminatorTests.cs index df0eafc1..cb85873e 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerTerminatorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerTerminatorTests.cs @@ -8,8 +8,9 @@ namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Workers; /// /// Per gateway.md the gateway must terminate /// orphaned worker processes on startup. These tests pin that the terminator -/// kills leftover workers (matched by executable path, or by image name when -/// the path is unreadable) without touching unrelated processes or itself. +/// kills leftover workers (matched by executable path, or confirmed by a command line +/// whose pipe name names a gateway that is gone) without touching unrelated processes, +/// another live gateway's workers, or itself. /// public sealed class OrphanWorkerTerminatorTests { @@ -44,13 +45,13 @@ public sealed class OrphanWorkerTerminatorTests Assert.Equal([101, 102], inspector.KilledProcessIds.Order()); } - /// Verifies that orphan workers are killed when executable path is unreadable but image name matches. + /// + /// WRK-009: with neither the path nor the command line readable, an image-name match alone is + /// not enough to kill — it could be a same-named worker from another build. + /// [Fact] - public void TerminateOrphans_KillsImageNameMatchWhenExecutablePathUnreadable() + public void TerminateOrphans_LeavesImageNameMatchAloneWhenPathAndCommandLineUnreadable() { - // The x64 gateway cannot introspect the x86 worker's main module, so the - // path comes back null. Image-name match is the only signal — and it is - // exactly the orphan worker case, so the process must still be killed. FakeProcessInspector inspector = new( [ new RunningProcessInfo(201, ExecutablePath: null), @@ -59,10 +60,106 @@ public sealed class OrphanWorkerTerminatorTests int killed = terminator.TerminateOrphans(); - Assert.Equal(1, killed); - Assert.Equal([201], inspector.KilledProcessIds); + Assert.Equal(0, killed); + Assert.Empty(inspector.KilledProcessIds); } + /// + /// With the path unreadable, a command line whose pipe name names a gateway that is no longer + /// running confirms the orphan, and it is killed. + /// + [Fact] + public void TerminateOrphans_KillsWorkerWhoseOwningGatewayIsGone() + { + FakeProcessInspector inspector = new( + [ + new RunningProcessInfo(202, ExecutablePath: null, WorkerCommandLine(ownerPid: 9001)), + ]); + OrphanWorkerTerminator terminator = CreateTerminator(inspector); + + int killed = terminator.TerminateOrphans(); + + Assert.Equal(1, killed); + Assert.Equal([202], inspector.KilledProcessIds); + } + + /// + /// WRK-009: a worker whose owning gateway (from its pipe name) is still running belongs to + /// that gateway and is not killed, even when its path matches. + /// + [Fact] + public void TerminateOrphans_LeavesWorkerOfALiveGatewayAlone() + { + DateTimeOffset workerStarted = DateTimeOffset.UtcNow; + FakeProcessInspector inspector = new( + [ + new RunningProcessInfo(203, WorkerExecutablePath, WorkerCommandLine(ownerPid: 9002), workerStarted), + ]); + inspector.RunningProcesses[9002] = workerStarted.AddMinutes(-5); + OrphanWorkerTerminator terminator = CreateTerminator(inspector); + + int killed = terminator.TerminateOrphans(); + + Assert.Equal(0, killed); + Assert.Empty(inspector.KilledProcessIds); + } + + /// + /// An "owner" process that started after the worker is a recycled process id, not the + /// gateway that launched it, so the worker is still an orphan. + /// + [Fact] + public void TerminateOrphans_KillsWorkerWhoseOwnerPidWasRecycled() + { + DateTimeOffset workerStarted = DateTimeOffset.UtcNow.AddHours(-1); + FakeProcessInspector inspector = new( + [ + new RunningProcessInfo(204, WorkerExecutablePath, WorkerCommandLine(ownerPid: 9003), workerStarted), + ]); + inspector.RunningProcesses[9003] = workerStarted.AddMinutes(10); + OrphanWorkerTerminator terminator = CreateTerminator(inspector); + + int killed = terminator.TerminateOrphans(); + + Assert.Equal(1, killed); + Assert.Equal([204], inspector.KilledProcessIds); + } + + /// The owner PID parses from both the current and the older pipe-name formats, quoted or not. + /// Worker command line. + /// Expected owner PID, or 0 when none should parse. + [Theory] + [InlineData("Worker.exe --session-id session-x --pipe-name mxgw-1234-abcdef --protocol-version 1", 1234)] + [InlineData("\"C:\\w\\Worker.exe\" --pipe-name \"mxgw-77-abc\"", 77)] + [InlineData("Worker.exe --pipe-name mxaccess-gateway-555-session-1", 555)] + [InlineData("Worker.exe --pipe-name other-555-session-1", 0)] + [InlineData("Worker.exe --session-id x", 0)] + [InlineData("", 0)] + public void TryParseOwnerGatewayProcessId_ParsesPipeName(string commandLine, int expected) + { + bool parsed = OrphanWorkerTerminator.TryParseOwnerGatewayProcessId(commandLine, out int ownerProcessId); + + Assert.Equal(expected != 0, parsed); + Assert.Equal(expected, ownerProcessId); + } + + /// + /// On Windows the system inspector reads a live process's command line (the cross-bitness + /// NtQueryInformationProcess path orphan cleanup depends on). + /// + [ZB.MOM.WW.MxGateway.Tests.Gateway.Sessions.WindowsFact] + public void SystemInspector_ReadsCurrentProcessCommandLine() + { + string? commandLine = SystemRunningProcessInspector.TryGetCommandLine(Environment.ProcessId); + + Assert.False(string.IsNullOrEmpty(commandLine)); + Assert.True(new SystemRunningProcessInspector().TryGetRunningProcess(Environment.ProcessId, out DateTimeOffset? startedAt)); + Assert.NotNull(startedAt); + } + + private static string WorkerCommandLine(int ownerPid) + => $"\"{WorkerExecutablePath}\" --session-id session-1 --pipe-name mxgw-{ownerPid}-0123456789abcdef --protocol-version 1"; + /// Verifies that unrelated processes with the same image name are not killed. [Fact] public void TerminateOrphans_DoesNotKillUnrelatedProcessSharingImageName() @@ -147,6 +244,9 @@ public sealed class OrphanWorkerTerminatorTests /// public IReadOnlyList GetProcessesByName(string processName) => processes; + /// Gets the processes reported as running, by id, with their start times. + public Dictionary RunningProcesses { get; } = []; + /// public void Kill(int processId) { @@ -157,5 +257,9 @@ public sealed class OrphanWorkerTerminatorTests KilledProcessIds.Add(processId); } + + /// + public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt) + => RunningProcesses.TryGetValue(processId, out startedAt); } } From a474d3219b1fb51742002c3105be9ac697ba352e Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:03:53 -0500 Subject: [PATCH 8/9] fix(grpc): configure Kestrel HTTP/2 keepalive (60 s ping, 10 s timeout) under MxGateway:Protocol (SES-005, #253) --- docs/GatewayConfiguration.md | 10 +- .../Configuration/GatewayOptionsValidator.cs | 13 ++ .../Configuration/ProtocolOptions.cs | 19 ++- .../GatewayApplication.cs | 3 + .../GatewayKestrelKeepAliveConfiguration.cs | 63 +++++++++ .../appsettings.json | 4 +- .../GatewayOptionsValidatorTests.cs | 29 +++++ .../Grpc/GatewayKestrelKeepAliveTests.cs | 122 ++++++++++++++++++ 8 files changed, 259 insertions(+), 4 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Server/Grpc/GatewayKestrelKeepAliveConfiguration.cs create mode 100644 src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/GatewayKestrelKeepAliveTests.cs diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 2211b5d6..d79bd9e0 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -75,7 +75,9 @@ paths, timeouts, queue sizes, enum values, or protocol values are invalid. }, "Protocol": { "WorkerProtocolVersion": 1, - "MaxGrpcMessageBytes": 16777216 + "MaxGrpcMessageBytes": 16777216, + "Http2KeepAlivePingDelaySeconds": 60, + "Http2KeepAlivePingTimeoutSeconds": 10 }, "Galaxy": { "ConnectionString": "Server=localhost;Database=ZB;Integrated Security=True;TrustServerCertificate=True;Encrypt=False;", @@ -440,8 +442,12 @@ is **not yet available**. |--------|---------|-------------| | `MxGateway:Protocol:WorkerProtocolVersion` | `1` | Worker IPC protocol version expected by the gateway and worker. This must match `GatewayContractInfo.WorkerProtocolVersion`. | | `MxGateway:Protocol:MaxGrpcMessageBytes` | `16777216` | Public gRPC max send and receive message size in bytes. The same default is used by official clients. The validator allows values from `1024` through `268435456`, and requires `MxGateway:Worker:MaxMessageBytes` to exceed this by at least the 64 KiB worker-frame envelope reserve and by no more than twice that reserve, so a `DrainEvents` reply budgeted at the pipe maximum still fits this send cap (see the Worker options). | +| `MxGateway:Protocol:Http2KeepAlivePingDelaySeconds` | `60` | Seconds an HTTP/2 connection may go without receiving a frame before the gateway sends a keepalive PING (Kestrel `Limits.Http2.KeepAlivePingDelay`). `0` turns server pings off. Must be between `0` and `86400`. Without server pings, a client that vanished without closing its connection (power loss, a firewall or NAT idle drop) keeps its `StreamEvents` call open on a quiet session indefinitely: the session's subscriber slot stays taken, so the client's own resume is refused with `ResourceExhausted` (`EventSubscriberAlreadyActive`), and the session and its x86 worker are never swept. With pings, the dead peer is detected within the delay plus the timeout and the subscriber detaches. | +| `MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds` | `10` | Seconds the gateway waits for any frame after a keepalive PING before it closes the connection (Kestrel `Limits.Http2.KeepAlivePingTimeout`). Must be between `1` and `3600`. | -The protocol option is exposed for diagnostics and explicit deployment +Client keepalive pings need no server setting. Kestrel has no minimum client-ping interval (unlike grpc-core and grpc-go servers, it never answers frequent pings with `GOAWAY`/`ENHANCE_YOUR_CALM`), it answers pings with or without an active call, and a received ping resets the connection's idle keep-alive timeout. The official clients ping every 30 s with a 10 s timeout, also while no call is active, which keeps an idle connection open and detects a dead gateway from the client side. + +The worker protocol version option is exposed for diagnostics and explicit deployment configuration, not for compatibility negotiation. A mismatch fails validation at startup. diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs index 2acd8fcc..67bd806e 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs @@ -714,6 +714,19 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase 86400) + { + builder.Add( + "MxGateway:Protocol:Http2KeepAlivePingDelaySeconds must be between 0 (disabled) and 86400."); + } + + if (options.Http2KeepAlivePingTimeoutSeconds is < 1 or > 3600) + { + builder.Add("MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds must be between 1 and 3600."); + } } // The worker-frame (pipe) maximum must stay above the public gRPC cap by the envelope-overhead diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/ProtocolOptions.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/ProtocolOptions.cs index 5a983f5c..8f6e9558 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/ProtocolOptions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/ProtocolOptions.cs @@ -3,7 +3,7 @@ using ZB.MOM.WW.MxGateway.Contracts; namespace ZB.MOM.WW.MxGateway.Server.Configuration; /// -/// Configuration options for the worker protocol version. +/// Configuration options for the worker protocol version and the public gRPC (HTTP/2) transport. /// public sealed class ProtocolOptions { @@ -14,4 +14,21 @@ public sealed class ProtocolOptions /// Gets or sets the maximum gRPC message size in bytes. public int MaxGrpcMessageBytes { get; init; } = 16 * 1024 * 1024; + + /// + /// Gets or sets how long an HTTP/2 connection may be idle (no frames received) before the + /// gateway sends a keepalive PING, in seconds. 0 disables server pings. Maps to + /// Kestrel's Limits.Http2.KeepAlivePingDelay. Without it a client that vanished + /// without a FIN or RST (power loss, a firewall or NAT idle drop) holds its + /// StreamEvents call, its session and its worker until a write times out, which on a + /// quiet session may be never. + /// + public int Http2KeepAlivePingDelaySeconds { get; init; } = 60; + + /// + /// Gets or sets how long the gateway waits for any frame after sending a keepalive PING + /// before it closes the connection, in seconds. Maps to Kestrel's + /// Limits.Http2.KeepAlivePingTimeout. + /// + public int Http2KeepAlivePingTimeoutSeconds { get; init; } = 10; } diff --git a/src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs b/src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs index 312ef0f8..ffa60325 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/GatewayApplication.cs @@ -110,6 +110,9 @@ public static class GatewayApplication builder.AddZbSerilog(o => o.ServiceName = "mxgateway"); builder.Services.AddGatewayConfiguration(builder.Configuration); + builder.Services.AddSingleton< + Microsoft.Extensions.Options.IConfigureOptions, + GatewayKestrelKeepAliveConfiguration>(); builder.Services.AddZbSecrets(builder.Configuration, "Secrets"); builder.Services.AddSqliteAuthStore(builder.Configuration); builder.Services.AddGatewayGrpcAuthorization(); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Grpc/GatewayKestrelKeepAliveConfiguration.cs b/src/ZB.MOM.WW.MxGateway.Server/Grpc/GatewayKestrelKeepAliveConfiguration.cs new file mode 100644 index 00000000..84c5f7b8 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Grpc/GatewayKestrelKeepAliveConfiguration.cs @@ -0,0 +1,63 @@ +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.MxGateway.Server.Configuration; + +namespace ZB.MOM.WW.MxGateway.Server.Grpc; + +/// +/// Applies the gateway's HTTP/2 keepalive policy (MxGateway:Protocol:Http2KeepAlive*) to +/// Kestrel (SES-005). +/// +/// +/// +/// Kestrel's HTTP/2 keepalive ping is off unless configured. A client that disappears +/// without closing its connection (host power loss, a firewall or NAT idle drop, a pulled +/// cable) is otherwise noticed only when a write times out at the TCP layer, and a quiet +/// session writes nothing: its StreamEvents call stays open, the session's single +/// subscriber slot stays taken — so the real client's resume is refused with +/// EventSubscriberAlreadyActive — and the session and its x86 worker are never +/// swept. With the ping on, a dead peer is detected within the delay plus the timeout, +/// the call's token fires, and the subscriber detaches. +/// +/// +/// Kestrel has no minimum-client-ping-interval policy (no equivalent of grpc-core's +/// GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS): it answers every client +/// PING and never sends GOAWAY/ENHANCE_YOUR_CALM for ping rate, with or without +/// an active call. A received PING also resets the connection's idle keep-alive timeout, +/// so client keepalive pings (the official clients send one every 30 s, also with no call +/// active) keep an otherwise idle connection open. There is therefore nothing to configure +/// on the server side for client pings. +/// +/// +/// The section is bound straight from configuration rather than through +/// IOptions<GatewayOptions>: Kestrel resolves its options while the server is +/// constructed, and reading the validated gateway options there would surface any +/// configuration error from inside Kestrel's construction instead of as the +/// OptionsValidationException startup validation reports. +/// +/// +/// The application configuration holding MxGateway:Protocol. +public sealed class GatewayKestrelKeepAliveConfiguration(IConfiguration configuration) + : IConfigureOptions +{ + /// The configuration section the keepalive options bind from. + public const string SectionName = "MxGateway:Protocol"; + + /// + public void Configure(KestrelServerOptions options) + { + ArgumentNullException.ThrowIfNull(options); + ProtocolOptions protocol = configuration.GetSection(SectionName).Get() ?? new ProtocolOptions(); + + // Out-of-range values are rejected by GatewayOptionsValidator at startup; the guards here + // only keep Kestrel's own setters from throwing before that validation reports. + options.Limits.Http2.KeepAlivePingDelay = protocol.Http2KeepAlivePingDelaySeconds > 0 + ? TimeSpan.FromSeconds(protocol.Http2KeepAlivePingDelaySeconds) + : TimeSpan.MaxValue; + if (protocol.Http2KeepAlivePingTimeoutSeconds > 0) + { + options.Limits.Http2.KeepAlivePingTimeout = TimeSpan.FromSeconds(protocol.Http2KeepAlivePingTimeoutSeconds); + } + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/appsettings.json b/src/ZB.MOM.WW.MxGateway.Server/appsettings.json index 93489ca4..d440e6e2 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/appsettings.json +++ b/src/ZB.MOM.WW.MxGateway.Server/appsettings.json @@ -90,7 +90,9 @@ }, "Protocol": { "WorkerProtocolVersion": 1, - "MaxGrpcMessageBytes": 16777216 + "MaxGrpcMessageBytes": 16777216, + "Http2KeepAlivePingDelaySeconds": 60, + "Http2KeepAlivePingTimeoutSeconds": 10 }, "Galaxy": { "ConnectionString": "Server=localhost;Database=ZB;Integrated Security=True;TrustServerCertificate=True;Encrypt=False;", diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs index cfeebb46..44fc7d80 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsValidatorTests.cs @@ -1330,6 +1330,35 @@ public sealed class GatewayOptionsValidatorTests Assert.True(result.Succeeded); } + /// SES-005: the HTTP/2 keepalive knobs are range-checked; a delay of 0 (off) is valid. + /// Configured ping delay. + /// Configured ping timeout. + /// Whether validation should pass. + [Theory] + [InlineData(60, 10, true)] + [InlineData(0, 10, true)] + [InlineData(86400, 3600, true)] + [InlineData(-1, 10, false)] + [InlineData(86401, 10, false)] + [InlineData(60, 0, false)] + [InlineData(60, 3601, false)] + public void Validate_Http2KeepAlive_IsRangeChecked(int delaySeconds, int timeoutSeconds, bool valid) + { + GatewayOptions options = WithWorkerAndProtocol( + new WorkerOptions(), + new ProtocolOptions + { + Http2KeepAlivePingDelaySeconds = delaySeconds, + Http2KeepAlivePingTimeoutSeconds = timeoutSeconds, + }); + + ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options); + + bool keepAliveFailure = result.Failed + && result.Failures!.Any(f => f.Contains("Http2KeepAlive", StringComparison.Ordinal)); + Assert.Equal(!valid, keepAliveFailure); + } + /// /// Verifies that a worker-frame maximum equal to the gRPC cap (zero headroom) fails validation: /// a maximally-sized accepted gRPC payload would not fit one worker frame once wrapped in a diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/GatewayKestrelKeepAliveTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/GatewayKestrelKeepAliveTests.cs new file mode 100644 index 00000000..c28c71c6 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/GatewayKestrelKeepAliveTests.cs @@ -0,0 +1,122 @@ +using System.Net; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.MxGateway.Server.Grpc; +using ZB.MOM.WW.MxGateway.Tests.TestSupport; + +namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Grpc; + +/// +/// SES-005: the gateway configures Kestrel's HTTP/2 keepalive from MxGateway:Protocol, and +/// Kestrel tolerates the official clients' keepalive pings (every 30 s, also with no call active). +/// +public sealed class GatewayKestrelKeepAliveTests +{ + /// The defaults are the D7 policy: server ping after 60 s idle, 10 s timeout. + [Fact] + public void Configure_WithDefaults_AppliesSixtySecondDelayAndTenSecondTimeout() + { + KestrelServerOptions kestrel = new(); + + new GatewayKestrelKeepAliveConfiguration(Config()).Configure(kestrel); + + Assert.Equal(TimeSpan.FromSeconds(60), kestrel.Limits.Http2.KeepAlivePingDelay); + Assert.Equal(TimeSpan.FromSeconds(10), kestrel.Limits.Http2.KeepAlivePingTimeout); + } + + /// Configured values are applied; a delay of 0 turns server pings off. + [Fact] + public void Configure_WithZeroDelay_DisablesServerPings() + { + KestrelServerOptions kestrel = new(); + new GatewayKestrelKeepAliveConfiguration(Config( + ("MxGateway:Protocol:Http2KeepAlivePingDelaySeconds", "0"), + ("MxGateway:Protocol:Http2KeepAlivePingTimeoutSeconds", "25"))) + .Configure(kestrel); + + Assert.Equal(TimeSpan.MaxValue, kestrel.Limits.Http2.KeepAlivePingDelay); + Assert.Equal(TimeSpan.FromSeconds(25), kestrel.Limits.Http2.KeepAlivePingTimeout); + } + + /// The real gateway host wires the configuration into its Kestrel options. + /// A task that represents the asynchronous operation. + [Fact] + public async Task GatewayHost_ConfiguresKestrelKeepAlive() + { + await using WebApplication app = TestGatewayHost.Build("--MxGateway:Protocol:Http2KeepAlivePingDelaySeconds=45"); + + KestrelServerOptions kestrel = app.Services.GetRequiredService>().Value; + + Assert.Equal(TimeSpan.FromSeconds(45), kestrel.Limits.Http2.KeepAlivePingDelay); + Assert.Equal(TimeSpan.FromSeconds(10), kestrel.Limits.Http2.KeepAlivePingTimeout); + } + + /// + /// Kestrel accepts client keepalive pings on a connection with no active call without a + /// GOAWAY, and the pings keep the idle connection open past Kestrel's idle keep-alive + /// timeout: the second request reuses the first request's connection. A client that does + /// not ping is the control — its idle connection is closed and the second request lands on a + /// new one, so the test can tell the two apart. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ClientPingsWithNoActiveCall_AreAcceptedAndKeepTheIdleConnectionOpen() + { + WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.UseKestrel(options => + { + options.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(2); + options.Listen(IPAddress.Loopback, 0, listen => listen.Protocols = HttpProtocols.Http2); + }); + await using WebApplication app = builder.Build(); + app.MapGet("/connection", (HttpContext context) => context.Connection.Id); + await app.StartAsync(); + string address = app.Services.GetRequiredService().Features.Get()!.Addresses.First(); + + Task<(string First, string Second)> pinging = TwoRequestsAcrossIdleGapAsync(address, ping: true); + Task<(string First, string Second)> silent = TwoRequestsAcrossIdleGapAsync(address, ping: false); + (string pingFirst, string pingSecond) = await pinging; + (string silentFirst, string silentSecond) = await silent; + + Assert.Equal(pingFirst, pingSecond); + Assert.NotEqual(silentFirst, silentSecond); + await app.StopAsync(); + } + + private static IConfiguration Config(params (string Key, string Value)[] values) + => new ConfigurationBuilder() + .AddInMemoryCollection(values.Select(pair => new KeyValuePair(pair.Key, pair.Value))) + .Build(); + + private static async Task<(string First, string Second)> TwoRequestsAcrossIdleGapAsync(string address, bool ping) + { + using SocketsHttpHandler handler = new() + { + KeepAlivePingDelay = ping ? TimeSpan.FromSeconds(1) : Timeout.InfiniteTimeSpan, + KeepAlivePingTimeout = TimeSpan.FromSeconds(5), + KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, + PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5), + }; + using HttpClient client = new(handler) + { + BaseAddress = new Uri(address), + DefaultRequestVersion = HttpVersion.Version20, + DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact, + Timeout = TimeSpan.FromSeconds(10), + }; + + string first = await client.GetStringAsync("/connection"); + await Task.Delay(TimeSpan.FromSeconds(4.5)); + string second = await client.GetStringAsync("/connection"); + return (first, second); + } +} From 8e720bc72732f85b8c93bf27f782b8c1c318c6f3 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:07:41 -0500 Subject: [PATCH 9/9] fix(worker): bound shutdown alarm steps by the grace; watchdog stands down while shutting down; startup handshake deadline (MXA-003, WIP-007, WIP-009, #253) --- docs/GatewayConfiguration.md | 2 +- docs/MxAccessWorkerInstanceDesign.md | 30 ++++ .../WorkerLaunchEnvironment.cs | 9 + .../Workers/WorkerProcessLauncher.cs | 3 + .../Workers/WorkerProcessLauncherTests.cs | 5 + .../Ipc/WorkerPipeSessionTests.cs | 155 ++++++++++++++++++ .../MxAccess/MxAccessStaSessionTests.cs | 42 +++++ .../TestSupport/FakeRuntimeSession.cs | 24 +++ .../Ipc/WorkerPipeSession.cs | 60 ++++++- .../Ipc/WorkerPipeSessionOptions.cs | 30 ++++ .../MxAccess/MxAccessStaSession.cs | 94 ++++++++--- 11 files changed, 430 insertions(+), 24 deletions(-) diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index d79bd9e0..3f8b0eb4 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -147,7 +147,7 @@ launch CWD (SEC-01, SEC-33). | `MxGateway:Worker:ExecutablePath` | `src\ZB.MOM.WW.MxGateway.Worker\bin\x86\Release\ZB.MOM.WW.MxGateway.Worker.exe` | Path to the x86 worker executable launched for each gateway session. The path must be valid and point to a `.exe` file. | | `MxGateway:Worker:WorkingDirectory` | `null` | Optional working directory for the worker process. When set, it must be a valid filesystem path. | | `MxGateway:Worker:RequiredArchitecture` | `X86` | Required Portable Executable architecture for the worker. Supported values are `X86` and `X64`; MXAccess parity uses `X86`. | -| `MxGateway:Worker:StartupTimeoutSeconds` | `30` | Total startup budget for process launch, startup probe, pipe connect, handshake, and worker readiness. | +| `MxGateway:Worker:StartupTimeoutSeconds` | `30` | Total startup budget for process launch, startup probe, pipe connect, handshake, and worker readiness. Also conveyed to the worker (`MXGATEWAY_WORKER_STARTUP_TIMEOUT_MS`) as the deadline for its own startup handshake, so a worker whose gateway died mid-launch exits instead of hanging in MXAccess initialization. | | `MxGateway:Worker:PipeConnectAttemptTimeoutMilliseconds` | `2000` | Per-attempt timeout used by the worker named-pipe connect retry path. The overall pipe connection still stays under the startup budget. | | `MxGateway:Worker:WriteCompletionWaitMilliseconds` | `1500` | Bounded wait the worker holds a unary write reply (`Write`/`Write2`/`WriteSecured`/`WriteSecured2`; bulk writes excluded) for the matching MXAccess `OnWriteComplete` callback, so the reply's `statuses` carry the real commit outcome. `0` disables the wait (pure fire-and-forget replies). Must be `>= 0`. The gateway conveys the value to the worker via the `MXGATEWAY_WORKER_WRITE_COMPLETION_WAIT_MS` environment variable. Consumers that time their own writes must budget above this wait: OtOpcUa's GalaxyDriver wraps gateway writes in a 2 s Tier A resilience timeout, so a deployment raising this option past ~2000 must raise that driver `ResilienceConfig` write timeout in step or slow-but-successful commits surface as consumer-side failures. | | `MxGateway:Worker:EventQueueCapacity` | `10000` | Capacity, in events, of the worker's outbound MXAccess event queue. Must be between `1000` and `1000000`. This is burst headroom, not a throttle: the queue has no drop policy, so filling it records a `QueueOverflow` worker fault and faults the session. Raise it for sessions whose subscription set can outrun the drain loop (large advise sets, slow event consumers); the backing queue pre-allocates its slots, so the ceiling keeps a mistyped value from committing the 32-bit worker to an outsized allocation. The gateway conveys the value to the worker via the `MXGATEWAY_EVENT_QUEUE_CAPACITY` environment variable; a missing or unusable value leaves the worker on the 10000 default rather than failing the session. | diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md index d91394fa..8e100d80 100644 --- a/docs/MxAccessWorkerInstanceDesign.md +++ b/docs/MxAccessWorkerInstanceDesign.md @@ -127,6 +127,20 @@ Startup sequence: If validation fails before MXAccess creation, exit quickly with a non-zero exit code. If MXAccess creation fails, send `WorkerFault` when possible and exit. +Steps 5–10 run under one deadline, `WorkerPipeSessionOptions.StartupHandshakeTimeout`, +which the launcher conveys as `MXGATEWAY_WORKER_STARTUP_TIMEOUT_MS` from +`MxGateway:Worker:StartupTimeoutSeconds` (default 120 s when absent). The worker +notices gateway death only through a pipe read returning end-of-stream or a +failed write, and the handshake has two windows with neither: a peer that +connects and never sends `GatewayHello` (net48 pipe reads ignore the +cancellation token), and MXAccess initialization, during which no read is +outstanding. A COM activation that hangs after the gateway died would otherwise +keep the x86 worker alive indefinitely. At the deadline the handshake throws +`TimeoutException` and the worker exits with `PipeConnectionFailed`; the stuck +step is abandoned, which is safe because the STA is a background thread. The +gateway applies the same budget to the whole launch and starts its clock first, +so a live gateway always gives up and kills the worker before this deadline. + The bootstrap layer returns structured exit codes before it creates pipes, starts the STA, or touches MXAccess: @@ -1155,6 +1169,22 @@ are rejected and queued commands that have not started receive `ProtocolStatusCode.WorkerUnavailable`. The command already executing on the STA is allowed to finish until the shutdown grace period expires. +The grace period covers the whole method, including the two alarm-side steps +that run before the data cleanup: joining the alarm poll loop and disposing the +alarm handler on the STA. Both wait on the STA, and neither can be cancelled +once its work item has started, so with the STA stuck in a COM call they used +to wait forever, the timeout below was never reached, and no shutdown-timeout +fault or `WorkerShutdownAck` was sent. Each step now gets what is left of the +grace, and running out raises the same `TimeoutException` as a slow data +cleanup. + +The STA watchdog stands down once the session is `ShuttingDown` or `Stopped`. +The data cleanup runs as one STA work item, which leaves `LastStaActivityUtc` +frozen with no command correlation id on the heartbeat. With a grace longer than +`HeartbeatGrace`, the watchdog would otherwise overwrite `ShuttingDown` with +`Faulted` and report `StaHung` for a session that is closing cleanly. The +shutdown's own timeout bounds it instead. + After command dispatch is closed, cleanup runs on the STA in MXAccess handle order: diff --git a/src/ZB.MOM.WW.MxGateway.Contracts/WorkerLaunchEnvironment.cs b/src/ZB.MOM.WW.MxGateway.Contracts/WorkerLaunchEnvironment.cs index 04037401..49008b54 100644 --- a/src/ZB.MOM.WW.MxGateway.Contracts/WorkerLaunchEnvironment.cs +++ b/src/ZB.MOM.WW.MxGateway.Contracts/WorkerLaunchEnvironment.cs @@ -50,4 +50,13 @@ public static class WorkerLaunchEnvironment /// exceed it. /// public const string HeartbeatGraceMilliseconds = "MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS"; + + /// + /// Deadline, in milliseconds, for the worker's startup handshake (the GatewayHello read + /// and MXAccess initialization). Set from MxGateway:Worker:StartupTimeoutSeconds, the + /// same bound the gateway applies to the whole launch, so a live gateway always gives up + /// (and kills the worker) first; the worker's own deadline only matters when the gateway is + /// gone. + /// + public const string StartupTimeoutMilliseconds = "MXGATEWAY_WORKER_STARTUP_TIMEOUT_MS"; } diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs index 7ec8ef29..e9445b45 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs @@ -224,6 +224,9 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher startInfo.Environment[WorkerLaunchEnvironment.HeartbeatStuckCeilingMilliseconds] = (_workerOptions.WorkerHeartbeatStuckCeilingSeconds * 1000L).ToString(System.Globalization.CultureInfo.InvariantCulture); + startInfo.Environment[WorkerLaunchEnvironment.StartupTimeoutMilliseconds] = + (_workerOptions.StartupTimeoutSeconds * 1000L).ToString(System.Globalization.CultureInfo.InvariantCulture); + commandLine = new WorkerProcessCommandLine(executablePath, arguments); return startInfo; 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 d54e9155..55926b84 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs @@ -186,6 +186,11 @@ public sealed class WorkerProcessLauncherTests Assert.Equal( "30000", processFactory.LastStartInfo.Environment[WorkerLaunchEnvironment.HeartbeatGraceMilliseconds]); + + // WIP-009: the worker bounds its own startup handshake with the gateway's startup budget. + Assert.Equal( + "30000", + processFactory.LastStartInfo.Environment[WorkerLaunchEnvironment.StartupTimeoutMilliseconds]); } /// Verifies that a failed startup probe kills and disposes the worker process. diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Ipc/WorkerPipeSessionTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Ipc/WorkerPipeSessionTests.cs index 675e4aff..24cd7272 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Ipc/WorkerPipeSessionTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Ipc/WorkerPipeSessionTests.cs @@ -1273,6 +1273,122 @@ public sealed class WorkerPipeSessionTests await SendShutdownAndWaitAsync(pipePair, runTask, cancellation.Token); } + /// + /// WIP-007: a graceful shutdown whose STA cleanup outlasts HeartbeatGrace must not be + /// reported as StaHung. The watchdog stands down once the shutdown has begun, and the + /// shutdown still ends with an OK WorkerShutdownAck. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RunAsync_WhenShutdownCleanupOutlastsHeartbeatGrace_DoesNotWriteWatchdogFault() + { + using CancellationTokenSource cancellation = new(TimeSpan.FromSeconds(10)); + using PipePair pipePair = await PipePair.CreateAsync(cancellation.Token); + FakeRuntimeSession runtime = new() { ShutdownDuration = TimeSpan.FromMilliseconds(500) }; + WorkerPipeSession session = CreatePipeSession( + pipePair.WorkerStream, + runtime, + new WorkerPipeSessionOptions + { + HeartbeatInterval = TimeSpan.FromMilliseconds(20), + HeartbeatGrace = TimeSpan.FromMilliseconds(100), + }); + Task runTask = session.RunAsync(cancellation.Token); + await CompleteGatewayHandshakeAsync(pipePair, cancellation.Token); + + await pipePair.GatewayWriter.WriteAsync(CreateShutdownEnvelope(), cancellation.Token); + + WorkerEnvelope envelope; + do + { + envelope = await pipePair.GatewayReader.ReadAsync(cancellation.Token); + Assert.NotEqual(WorkerEnvelope.BodyOneofCase.WorkerFault, envelope.BodyCase); + } + while (envelope.BodyCase != WorkerEnvelope.BodyOneofCase.WorkerShutdownAck); + + Assert.Equal(ProtocolStatusCode.Ok, envelope.WorkerShutdownAck.Status.Code); + Task completedTask = await Task.WhenAny(runTask, Task.Delay(TimeSpan.FromSeconds(5), cancellation.Token)); + Assert.Same(runTask, completedTask); + await runTask; + } + + /// + /// WIP-009: a peer that connects and never sends GatewayHello does not hold the worker + /// forever; the handshake fails with a at its deadline. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task CompleteStartupHandshakeAsync_WhenGatewayNeverSendsHello_TimesOut() + { + WorkerFrameProtocolOptions options = CreateOptions(); + using NeverReadingStream inbound = new(); + using MemoryStream outbound = new(); + WorkerPipeSession session = new( + new WorkerFrameReader(inbound, options), + new WorkerFrameWriter(outbound, options), + options, + () => 1234, + new WorkerPipeSessionOptions { StartupHandshakeTimeout = TimeSpan.FromMilliseconds(200) }, + () => new FakeRuntimeSession()); + bool initialized = false; + + Task handshake = session.CompleteStartupHandshakeAsync( + _ => + { + initialized = true; + return Task.CompletedTask; + }); + Task completed = await Task.WhenAny(handshake, Task.Delay(TimeSpan.FromSeconds(5))); + + Assert.Same(handshake, completed); + await Assert.ThrowsAsync(async () => await handshake); + Assert.False(initialized); + } + + /// + /// WIP-009: MXAccess initialization that hangs (as a COM activation can, with the gateway + /// gone and no pipe read outstanding to notice) is bounded by the same startup deadline. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task CompleteStartupHandshakeAsync_WhenInitializationHangs_TimesOut() + { + WorkerFrameProtocolOptions options = CreateOptions(); + using MemoryStream inbound = new(); + await new WorkerFrameWriter(inbound, options).WriteAsync(CreateGatewayHelloEnvelope()); + inbound.Position = 0; + using MemoryStream outbound = new(); + WorkerPipeSession session = new( + new WorkerFrameReader(inbound, options), + new WorkerFrameWriter(outbound, options), + options, + () => 1234, + new WorkerPipeSessionOptions { StartupHandshakeTimeout = TimeSpan.FromMilliseconds(200) }, + () => new FakeRuntimeSession()); + TaskCompletionSource never = new(); + + Task handshake = session.CompleteStartupHandshakeAsync(_ => never.Task); + Task completed = await Task.WhenAny(handshake, Task.Delay(TimeSpan.FromSeconds(5))); + + Assert.Same(handshake, completed); + await Assert.ThrowsAsync(async () => await handshake); + WorkerEnvelope[] written = ReadWrittenFrames(outbound, options); + Assert.Equal(WorkerEnvelope.BodyOneofCase.WorkerHello, written[0].BodyCase); + Assert.DoesNotContain(written, envelope => envelope.BodyCase == WorkerEnvelope.BodyOneofCase.WorkerReady); + } + + /// The startup deadline is conveyed by the launcher's environment. + [Fact] + public void FromEnvironment_ReadsStartupHandshakeTimeout() + { + WorkerPipeSessionOptions conveyed = WorkerPipeSessionOptions.FromEnvironment( + name => name == WorkerLaunchEnvironment.StartupTimeoutMilliseconds ? "45000" : null); + WorkerPipeSessionOptions missing = WorkerPipeSessionOptions.FromEnvironment(_ => null); + + Assert.Equal(TimeSpan.FromSeconds(45), conveyed.StartupHandshakeTimeout); + Assert.Equal(WorkerPipeSessionOptions.DefaultStartupHandshakeTimeout, missing.StartupHandshakeTimeout); + } + /// /// While a command is in flight (snapshot's current command /// correlation id is non-empty), stale STA activity must NOT trigger @@ -2794,6 +2910,45 @@ public sealed class WorkerPipeSessionTests // that batch before the flush runs. Neither "I read the frames" nor any fixed sleep is evidence // that a flush has been counted; WaitForAllWritesFlushedAsync is the explicit edge a test must // take before sampling the counters. + /// A readable stream whose reads never complete, as a connected but silent peer's pipe. + private sealed class NeverReadingStream : Stream + { + private readonly TaskCompletionSource _never = new(); + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() + { + } + + public override int Read(byte[] buffer, int offset, int count) + { + _never.Task.Wait(); + return 0; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + => _never.Task; + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + private sealed class FlushCountingPassthroughStream : Stream { private readonly Stream inner; diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs index 12947984..3b79cb3b 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessStaSessionTests.cs @@ -574,6 +574,48 @@ public sealed class MxAccessStaSessionTests "Expected StaCallInProgress to clear once the alarm poll returned."); } + /// + /// MXA-003: the graceful-shutdown grace covers the alarm poll join and the alarm handler + /// dispose. With the STA stuck inside a poll, ShutdownGracefullyAsync reports a + /// at roughly its grace period instead of waiting on the STA. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ShutdownGracefullyAsync_WhenStaIsStuckInAlarmPoll_TimesOutWithinGrace() + { + FakeAlarmCommandHandler handler = new() { BlockPoll = true }; + FakeMxAccessComObjectFactory factory = new(); + FakeMxAccessEventSink eventSink = new(); + using StaRuntime runtime = CreateRuntime(); + using MxAccessStaSession session = new( + runtime, + factory, + eventSink, + new MxAccessEventQueue(), + (_eq, _affinity, _comFactory) => handler); + await session.StartAsync("session-1", workerProcessId: 1); + Assert.True( + handler.WaitForPollEntered(TimeSpan.FromSeconds(5)), + "Expected the alarm poll to start within 5 seconds."); + + System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); + Task shutdown = session.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(200)); + Task completed = await Task.WhenAny(shutdown, Task.Delay(TimeSpan.FromSeconds(5))); + stopwatch.Stop(); + + try + { + Assert.Same(shutdown, completed); + await Assert.ThrowsAsync(async () => await shutdown); + Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(3), $"shutdown took {stopwatch.Elapsed}"); + } + finally + { + handler.BlockPoll = false; + handler.ReleasePoll(); + } + } + /// /// A transient PollOnce failure must not fault the whole session: with a /// failure threshold of 3, a poll pattern that never fails three times in diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/FakeRuntimeSession.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/FakeRuntimeSession.cs index 5d5fa18f..1f7dc64c 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/FakeRuntimeSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/FakeRuntimeSession.cs @@ -64,6 +64,13 @@ internal sealed class FakeRuntimeSession : IWorkerRuntimeSession /// Gets or sets whether ShutdownGracefullyAsync throws a TimeoutException. public bool ThrowTimeoutOnShutdown { get; set; } + /// + /// Gets or sets how long a graceful shutdown takes. While it runs, the heartbeat snapshot + /// reports STA activity frozen at the moment the shutdown began, the way one long STA + /// cleanup work item leaves it in production. + /// + public TimeSpan ShutdownDuration { get; set; } + /// /// Optional diagnostic message stuffed into every dispatched command reply. A long value /// pushes the STA command reply past a small negotiated frame maximum, which is how a test @@ -519,9 +526,26 @@ internal sealed class FakeRuntimeSession : IWorkerRuntimeSession new TimeoutException("Simulated graceful shutdown timeout.")); } + if (ShutdownDuration > TimeSpan.Zero) + { + return SlowShutdownAsync(); + } + return Task.FromResult(new MxAccessShutdownResult(Array.Empty())); } + private async Task SlowShutdownAsync() + { + SetSnapshot(new WorkerRuntimeHeartbeatSnapshot( + DateTimeOffset.UtcNow - TimeSpan.FromSeconds(10), + pendingCommandCount: 0, + outboundEventQueueDepth: 0, + lastEventSequence: 0, + currentCommandCorrelationId: string.Empty)); + await Task.Delay(ShutdownDuration).ConfigureAwait(false); + return new MxAccessShutdownResult(Array.Empty()); + } + /// Releases a blocked dispatch. public void ReleaseDispatch() { diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs b/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs index c2561d5f..b1f64976 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs @@ -346,15 +346,32 @@ public sealed class WorkerPipeSession throw new ArgumentNullException(nameof(initializeMxAccessAsync)); } + // One deadline over the hello read and MXAccess initialization (WIP-009). Neither observes + // gateway death on its own: net48 pipe reads ignore the token, so a peer that connects and + // never sends parks the read forever, and no read is outstanding while initialization + // runs, so a COM activation that hangs after the gateway died keeps this worker alive. The + // abandoned step is left running; the caller exits the process (the STA is a background + // thread), which is the only way to end either. + Stopwatch handshakeClock = Stopwatch.StartNew(); try { - WorkerEnvelope envelope = await _reader.ReadAsync(cancellationToken).ConfigureAwait(false); + WorkerEnvelope envelope = await WithinStartupDeadlineAsync( + _reader.ReadAsync(cancellationToken), + handshakeClock, + "GatewayHello", + cancellationToken) + .ConfigureAwait(false); _state = WorkerState.Handshaking; ValidateGatewayHello(envelope); await WriteWorkerHelloAsync(cancellationToken).ConfigureAwait(false); _state = WorkerState.InitializingSta; - WorkerReady ready = await initializeMxAccessAsync(cancellationToken).ConfigureAwait(false); + WorkerReady ready = await WithinStartupDeadlineAsync( + initializeMxAccessAsync(cancellationToken), + handshakeClock, + "MXAccess initialization", + cancellationToken) + .ConfigureAwait(false); if (MxStatusProxyRecordInfoPin.Status is { } pinStatus) { _logger?.Information( @@ -386,6 +403,35 @@ public sealed class WorkerPipeSession } } + private async Task WithinStartupDeadlineAsync( + Task step, + Stopwatch handshakeClock, + string stepName, + CancellationToken cancellationToken) + { + if (!step.IsCompleted) + { + TimeSpan remaining = _sessionOptions.StartupHandshakeTimeout - handshakeClock.Elapsed; + Task completed = remaining > TimeSpan.Zero + ? await Task.WhenAny(step, Task.Delay(remaining, cancellationToken)).ConfigureAwait(false) + : Task.CompletedTask; + if (completed != step) + { + cancellationToken.ThrowIfCancellationRequested(); + _ = step.ContinueWith( + static abandoned => _ = abandoned.Exception, + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + throw new TimeoutException( + $"Worker startup handshake did not complete within {_sessionOptions.StartupHandshakeTimeout} " + + $"(waiting for {stepName}); the gateway is gone or stopped responding."); + } + } + + return await step.ConfigureAwait(false); + } + private void ValidateGatewayHello(WorkerEnvelope envelope) { if (envelope.BodyCase != WorkerEnvelope.BodyOneofCase.GatewayHello) @@ -1521,6 +1567,16 @@ public sealed class WorkerPipeSession WorkerRuntimeHeartbeatSnapshot snapshot, CancellationToken cancellationToken) { + // A graceful shutdown runs its cleanup as one STA work item, which leaves LastActivityUtc + // frozen with no command correlation advertised. With a grace longer than HeartbeatGrace + // the watchdog would overwrite ShuttingDown with Faulted and report StaHung for a session + // that is closing cleanly (WIP-007). The shutdown has its own bound (its timeout raises the + // shutdown-timeout fault), so the watchdog stands down once it has begun. + if (_state is WorkerState.ShuttingDown or WorkerState.Stopped) + { + return; + } + TimeSpan staleFor = DateTimeOffset.UtcNow - snapshot.LastStaActivityUtc; if (staleFor <= _sessionOptions.HeartbeatGrace) { diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSessionOptions.cs b/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSessionOptions.cs index a12e6ab8..c1392ec5 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSessionOptions.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSessionOptions.cs @@ -20,12 +20,20 @@ public sealed class WorkerPipeSessionOptions /// public static readonly TimeSpan DefaultHeartbeatStuckCeiling = TimeSpan.FromSeconds(75); + /// + /// Default startup-handshake deadline (120 seconds), used when the launcher did not convey + /// one (). Generous so it + /// never undercuts a gateway's own startup timeout. + /// + public static readonly TimeSpan DefaultStartupHandshakeTimeout = TimeSpan.FromSeconds(120); + /// Initializes a new instance of the WorkerPipeSessionOptions class with default values. public WorkerPipeSessionOptions() { HeartbeatInterval = DefaultHeartbeatInterval; HeartbeatGrace = DefaultHeartbeatGrace; HeartbeatStuckCeiling = DefaultHeartbeatStuckCeiling; + StartupHandshakeTimeout = DefaultStartupHandshakeTimeout; } /// @@ -54,6 +62,11 @@ public sealed class WorkerPipeSessionOptions options.HeartbeatInterval = interval; } + if (TryReadPositiveMilliseconds(lookup, WorkerLaunchEnvironment.StartupTimeoutMilliseconds, out TimeSpan startupTimeout)) + { + options.StartupHandshakeTimeout = startupTimeout; + } + TimeSpan grace = options.HeartbeatGrace; bool haveGrace = TryReadPositiveMilliseconds(lookup, WorkerLaunchEnvironment.HeartbeatGraceMilliseconds, out TimeSpan configuredGrace); if (haveGrace) @@ -123,6 +136,16 @@ public sealed class WorkerPipeSessionOptions /// public TimeSpan HeartbeatStuckCeiling { get; set; } + /// + /// Gets or sets the deadline for the startup handshake: reading the GatewayHello and + /// initializing MXAccess. Gateway death is otherwise noticed only through a pipe read + /// returning end-of-stream or a failed write, and the handshake has two windows with + /// neither: a peer that connects and never sends (net48 pipe reads ignore the token), and + /// MXAccess initialization, during which no read is outstanding. A hung COM activation with + /// the gateway gone would otherwise keep the x86 worker alive indefinitely. + /// + public TimeSpan StartupHandshakeTimeout { get; set; } + /// Validates the session options. public void Validate() { @@ -140,6 +163,13 @@ public sealed class WorkerPipeSessionOptions "Worker heartbeat grace must be greater than zero."); } + if (StartupHandshakeTimeout <= TimeSpan.Zero) + { + throw new ArgumentOutOfRangeException( + nameof(StartupHandshakeTimeout), + "Worker startup handshake timeout must be greater than zero."); + } + if (HeartbeatStuckCeiling <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException( diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs index 6e9a098e..ae184433 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessStaSession.cs @@ -773,6 +773,15 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession commandDispatcher?.RequestShutdown(); + // The grace period covers the whole shutdown, the alarm poll join and the alarm handler + // dispose included (MXA-003). Both of those wait on the STA: the poll loop's in-flight + // PollOnce and the dispose work item cannot be cancelled once started, so with the STA stuck + // in a COM call (a hung Write, GetXmlCurrentAlarms2 or ReadBulk) an unbounded await here + // never reached the timeout below — no TimeoutException, no shutdown-timeout fault, no + // ShutdownAck — and the worker sat until the gateway killed it. A hung STA is exactly the + // case the grace period exists for. + Stopwatch stopwatch = Stopwatch.StartNew(); + // Cancel the STA poll loop before disposing the alarm handler. // The loop references the alarm handler and must be stopped first // so that no further PollOnce calls race with disposal. @@ -785,15 +794,9 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession pollCtsToDispose.Cancel(); if (pollTaskToAwait is not null) { - try - { - await pollTaskToAwait.ConfigureAwait(false); - } - catch - { - // Swallow — poll loop cancellation must not block data shutdown. - } + await AwaitWithinGraceAsync(pollTaskToAwait, timeout, stopwatch, cancellationToken).ConfigureAwait(false); } + pollCtsToDispose.Dispose(); } @@ -806,19 +809,14 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession alarmCommandHandler = null; if (alarmHandlerToDispose is not null) { - try - { - await staRuntime.InvokeAsync( - () => alarmHandlerToDispose.Dispose(), - cancellationToken).ConfigureAwait(false); - } - catch - { - // Swallow — alarm cleanup must not block data shutdown. - } + await AwaitWithinGraceAsync( + staRuntime.InvokeAsync(() => alarmHandlerToDispose.Dispose(), cancellationToken), + timeout, + stopwatch, + cancellationToken) + .ConfigureAwait(false); } - Stopwatch stopwatch = Stopwatch.StartNew(); MxAccessShutdownResult result; if (session is null) { @@ -826,14 +824,20 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession } else { + TimeSpan cleanupBudget = timeout - stopwatch.Elapsed; + if (cleanupBudget <= TimeSpan.Zero) + { + throw new TimeoutException($"MXAccess graceful shutdown exceeded {timeout}."); + } + using CancellationTokenSource shutdownCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - shutdownCancellation.CancelAfter(timeout); + shutdownCancellation.CancelAfter(cleanupBudget); Task cleanupTask = staRuntime.InvokeAsync( () => session.ShutdownGracefully(), shutdownCancellation.Token); - Task delayTask = Task.Delay(timeout, cancellationToken); + Task delayTask = Task.Delay(cleanupBudget, cancellationToken); Task completedTask = await Task.WhenAny(cleanupTask, delayTask).ConfigureAwait(false); if (completedTask != cleanupTask) { @@ -862,6 +866,54 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession return result; } + // Awaits one alarm-side shutdown step within what is left of the grace period. A step that + // fails is swallowed (alarm cleanup must not block data shutdown); a step that does not finish + // in time means the STA is stuck, so the shutdown reports the same TimeoutException the data + // cleanup would. The step is left running: the STA work item cannot be abandoned, and if the + // STA recovers it simply completes. + private static async Task AwaitWithinGraceAsync( + Task step, + TimeSpan timeout, + Stopwatch stopwatch, + CancellationToken cancellationToken) + { + TimeSpan remaining = timeout - stopwatch.Elapsed; + if (!step.IsCompleted) + { + if (remaining <= TimeSpan.Zero) + { + ObserveFault(step); + throw new TimeoutException($"MXAccess graceful shutdown exceeded {timeout}."); + } + + Task completed = await Task.WhenAny(step, Task.Delay(remaining, cancellationToken)).ConfigureAwait(false); + if (completed != step) + { + ObserveFault(step); + cancellationToken.ThrowIfCancellationRequested(); + throw new TimeoutException($"MXAccess graceful shutdown exceeded {timeout}."); + } + } + + try + { + await step.ConfigureAwait(false); + } + catch + { + // Swallow — alarm cleanup must not block data shutdown. + } + } + + private static void ObserveFault(Task step) + { + _ = step.ContinueWith( + static completed => _ = completed.Exception, + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + } + /// public void Dispose() {