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)
ci / windows-x86 (push) Failing after 11m18s
ci / java (push) Failing after 11m43s
ci / portable (push) Failing after 12m6s

This commit is contained in:
Joseph Doherty
2026-12-03 10:07:41 -05:00
parent a474d3219b
commit 8e720bc727
11 changed files with 430 additions and 24 deletions
@@ -50,4 +50,13 @@ public static class WorkerLaunchEnvironment
/// exceed it.
/// </summary>
public const string HeartbeatGraceMilliseconds = "MXGATEWAY_WORKER_HEARTBEAT_GRACE_MS";
/// <summary>
/// Deadline, in milliseconds, for the worker's startup handshake (the <c>GatewayHello</c> read
/// and MXAccess initialization). Set from <c>MxGateway:Worker:StartupTimeoutSeconds</c>, 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.
/// </summary>
public const string StartupTimeoutMilliseconds = "MXGATEWAY_WORKER_STARTUP_TIMEOUT_MS";
}
@@ -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;
@@ -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]);
}
/// <summary>Verifies that a failed startup probe kills and disposes the worker process.</summary>
@@ -1273,6 +1273,122 @@ public sealed class WorkerPipeSessionTests
await SendShutdownAndWaitAsync(pipePair, runTask, cancellation.Token);
}
/// <summary>
/// WIP-007: a graceful shutdown whose STA cleanup outlasts <c>HeartbeatGrace</c> must not be
/// reported as <c>StaHung</c>. The watchdog stands down once the shutdown has begun, and the
/// shutdown still ends with an OK <c>WorkerShutdownAck</c>.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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;
}
/// <summary>
/// WIP-009: a peer that connects and never sends <c>GatewayHello</c> does not hold the worker
/// forever; the handshake fails with a <see cref="TimeoutException"/> at its deadline.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<TimeoutException>(async () => await handshake);
Assert.False(initialized);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<bool> 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<TimeoutException>(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);
}
/// <summary>The startup deadline is conveyed by the launcher's environment.</summary>
[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);
}
/// <summary>
/// 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.
/// <summary>A readable stream whose reads never complete, as a connected but silent peer's pipe.</summary>
private sealed class NeverReadingStream : Stream
{
private readonly TaskCompletionSource<int> _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<int> 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;
@@ -574,6 +574,48 @@ public sealed class MxAccessStaSessionTests
"Expected StaCallInProgress to clear once the alarm poll returned.");
}
/// <summary>
/// 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
/// <see cref="TimeoutException"/> at roughly its grace period instead of waiting on the STA.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<MxAccessShutdownResult> 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<TimeoutException>(async () => await shutdown);
Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(3), $"shutdown took {stopwatch.Elapsed}");
}
finally
{
handler.BlockPoll = false;
handler.ReleasePoll();
}
}
/// <summary>
/// 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
@@ -64,6 +64,13 @@ internal sealed class FakeRuntimeSession : IWorkerRuntimeSession
/// <summary>Gets or sets whether ShutdownGracefullyAsync throws a TimeoutException.</summary>
public bool ThrowTimeoutOnShutdown { get; set; }
/// <summary>
/// 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.
/// </summary>
public TimeSpan ShutdownDuration { get; set; }
/// <summary>
/// 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<MxAccessShutdownFailure>()));
}
private async Task<MxAccessShutdownResult> 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<MxAccessShutdownFailure>());
}
/// <summary>Releases a blocked dispatch.</summary>
public void ReleaseDispatch()
{
@@ -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<T> WithinStartupDeadlineAsync<T>(
Task<T> 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)
{
@@ -20,12 +20,20 @@ public sealed class WorkerPipeSessionOptions
/// </summary>
public static readonly TimeSpan DefaultHeartbeatStuckCeiling = TimeSpan.FromSeconds(75);
/// <summary>
/// Default startup-handshake deadline (120 seconds), used when the launcher did not convey
/// one (<see cref="WorkerLaunchEnvironment.StartupTimeoutMilliseconds"/>). Generous so it
/// never undercuts a gateway's own startup timeout.
/// </summary>
public static readonly TimeSpan DefaultStartupHandshakeTimeout = TimeSpan.FromSeconds(120);
/// <summary>Initializes a new instance of the WorkerPipeSessionOptions class with default values.</summary>
public WorkerPipeSessionOptions()
{
HeartbeatInterval = DefaultHeartbeatInterval;
HeartbeatGrace = DefaultHeartbeatGrace;
HeartbeatStuckCeiling = DefaultHeartbeatStuckCeiling;
StartupHandshakeTimeout = DefaultStartupHandshakeTimeout;
}
/// <summary>
@@ -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
/// </summary>
public TimeSpan HeartbeatStuckCeiling { get; set; }
/// <summary>
/// Gets or sets the deadline for the startup handshake: reading the <c>GatewayHello</c> 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.
/// </summary>
public TimeSpan StartupHandshakeTimeout { get; set; }
/// <summary>Validates the session options.</summary>
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(
@@ -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<MxAccessShutdownResult> 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);
}
/// <inheritdoc />
public void Dispose()
{