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()
{