fix(gateway): split the heartbeat check interval from the send interval; expose the two fixed worker-client timeouts (mxaccessgw#192)

R21-O14: MxGateway:Worker:HeartbeatIntervalSeconds was documented as the
worker heartbeat send interval, but it never reached the worker (which sends
on its own fixed 5 s) and only set the gateway's HeartbeatCheckInterval. It is
renamed HeartbeatCheckIntervalSeconds (default 5, unchanged). The old key stays
as a deprecated alias with the same meaning so existing appsettings keep
working; setting both is a validation error. The grace-vs-interval check now
compares against the resolved check interval.

R21-O15: WorkerClientOptions.EventChannelFullModeTimeout and
HeartbeatStuckCeiling were always their compile-time defaults. They are now
MxGateway:Worker:EventChannelFullModeTimeoutMilliseconds (default 5000, > 0)
and HeartbeatStuckCeilingSeconds (default 75, >= HeartbeatGraceSeconds). The
factory's mapping moved into SessionWorkerClientFactory.CreateWorkerClientOptions
so every field is set from configuration and is testable. The effective-config
record shows the resolved check interval and both new values.

Docs: GatewayConfiguration.md, GatewayProcessDesign.md sample,
MxAccessWorkerInstanceDesign.md heartbeat section; appsettings.json uses the
new keys.

Tests: CreateWorkerClientOptions mapping + defaults (fail under a mutated
mapping), alias honoured, both-keys conflict, and bounds for the new options.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 12:35:42 -05:00
parent 101bda7073
commit 7b21f304e9
15 changed files with 211 additions and 28 deletions
@@ -1883,7 +1883,7 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
ExecutablePath = workerExecutablePath,
StartupTimeoutSeconds = 30,
ShutdownTimeoutSeconds = 15,
HeartbeatIntervalSeconds = 5,
HeartbeatCheckIntervalSeconds = 5,
HeartbeatGraceSeconds = 15,
MaxMessageBytes = WorkerFrameProtocolOptions.DefaultMaxMessageBytes,
RequiredArchitecture = WorkerArchitecture.X86,
@@ -6,6 +6,8 @@ public sealed record EffectiveWorkerConfiguration(
string RequiredArchitecture,
int StartupTimeoutSeconds,
int ShutdownTimeoutSeconds,
int HeartbeatIntervalSeconds,
int HeartbeatCheckIntervalSeconds,
int HeartbeatGraceSeconds,
int HeartbeatStuckCeilingSeconds,
int EventChannelFullModeTimeoutMilliseconds,
int MaxMessageBytes);
@@ -38,8 +38,10 @@ public sealed class GatewayConfigurationProvider(IOptions<GatewayOptions> option
RequiredArchitecture: value.Worker.RequiredArchitecture.ToString(),
StartupTimeoutSeconds: value.Worker.StartupTimeoutSeconds,
ShutdownTimeoutSeconds: value.Worker.ShutdownTimeoutSeconds,
HeartbeatIntervalSeconds: value.Worker.HeartbeatIntervalSeconds,
HeartbeatCheckIntervalSeconds: value.Worker.ResolveHeartbeatCheckIntervalSeconds(),
HeartbeatGraceSeconds: value.Worker.HeartbeatGraceSeconds,
HeartbeatStuckCeilingSeconds: value.Worker.HeartbeatStuckCeilingSeconds,
EventChannelFullModeTimeoutMilliseconds: value.Worker.EventChannelFullModeTimeoutMilliseconds,
MaxMessageBytes: value.Worker.MaxMessageBytes),
Sessions: new EffectiveSessionConfiguration(
DefaultCommandTimeoutSeconds: value.Sessions.DefaultCommandTimeoutSeconds,
@@ -258,19 +258,37 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
options.ShutdownTimeoutSeconds,
"MxGateway:Worker:ShutdownTimeoutSeconds must be greater than zero.",
builder);
if (options.HeartbeatCheckIntervalSeconds is not null && options.HeartbeatIntervalSeconds is not null)
{
builder.Add(
"MxGateway:Worker:HeartbeatIntervalSeconds is a deprecated alias of HeartbeatCheckIntervalSeconds; set only HeartbeatCheckIntervalSeconds.");
}
int heartbeatCheckIntervalSeconds = options.ResolveHeartbeatCheckIntervalSeconds();
AddIfNotPositive(
options.HeartbeatIntervalSeconds,
"MxGateway:Worker:HeartbeatIntervalSeconds must be greater than zero.",
heartbeatCheckIntervalSeconds,
"MxGateway:Worker:HeartbeatCheckIntervalSeconds must be greater than zero.",
builder);
AddIfNotPositive(
options.HeartbeatGraceSeconds,
"MxGateway:Worker:HeartbeatGraceSeconds must be greater than zero.",
builder);
if (options.HeartbeatGraceSeconds < options.HeartbeatIntervalSeconds)
if (options.HeartbeatGraceSeconds < heartbeatCheckIntervalSeconds)
{
builder.Add(
"MxGateway:Worker:HeartbeatGraceSeconds must be greater than or equal to HeartbeatIntervalSeconds.");
"MxGateway:Worker:HeartbeatGraceSeconds must be greater than or equal to HeartbeatCheckIntervalSeconds.");
}
AddIfNotPositive(
options.EventChannelFullModeTimeoutMilliseconds,
"MxGateway:Worker:EventChannelFullModeTimeoutMilliseconds must be greater than zero.",
builder);
if (options.HeartbeatStuckCeilingSeconds < options.HeartbeatGraceSeconds)
{
builder.Add(
"MxGateway:Worker:HeartbeatStuckCeilingSeconds must be greater than or equal to HeartbeatGraceSeconds.");
}
if (options.EventQueueCapacity is < MinimumWorkerEventQueueCapacity or > MaximumWorkerEventQueueCapacity)
@@ -42,12 +42,59 @@ public sealed class WorkerOptions
/// <summary>The maximum time in seconds for graceful shutdown.</summary>
public int ShutdownTimeoutSeconds { get; init; } = 10;
/// <summary>The interval in seconds for worker heartbeats.</summary>
public int HeartbeatIntervalSeconds { get; init; } = 5;
/// <summary>Default for <see cref="HeartbeatCheckIntervalSeconds"/>.</summary>
public const int DefaultHeartbeatCheckIntervalSeconds = 5;
/// <summary>
/// How often, in seconds, the gateway checks the age of the worker's last heartbeat
/// against <see cref="HeartbeatGraceSeconds"/>. This is the gateway-side <em>check</em>
/// cadence only: the worker sends heartbeats on its own fixed 5-second interval, which
/// this option does not reach. <see langword="null"/> falls back to the deprecated
/// <see cref="HeartbeatIntervalSeconds"/> key, then to
/// <see cref="DefaultHeartbeatCheckIntervalSeconds"/>; read the resolved value through
/// <see cref="ResolveHeartbeatCheckIntervalSeconds"/>.
/// </summary>
public int? HeartbeatCheckIntervalSeconds { get; init; }
/// <summary>
/// Deprecated alias of <see cref="HeartbeatCheckIntervalSeconds"/> (mxaccessgw#192). The
/// name implied the worker's heartbeat <em>send</em> interval, but the value only ever
/// drove the gateway's check cadence. Still honoured so existing configuration keeps
/// its meaning; setting both keys is a validation error.
/// </summary>
public int? HeartbeatIntervalSeconds { get; init; }
/// <summary>The grace period in seconds after a heartbeat before considering the worker unresponsive.</summary>
public int HeartbeatGraceSeconds { get; init; } = 15;
/// <summary>
/// How long, in milliseconds, the gateway waits for its bounded per-session event
/// channel to accept a worker event before faulting the session with a
/// <c>QueueOverflow</c>. A consumer that stalls for longer than this is treated as stuck.
/// Default 5000; must be greater than zero.
/// </summary>
public int EventChannelFullModeTimeoutMilliseconds { get; init; } =
(int)Workers.WorkerClientOptions.DefaultEventChannelFullModeTimeout.TotalMilliseconds;
/// <summary>
/// Ceiling, in seconds, on the gateway's in-flight-command heartbeat skip: while a command
/// is pending the gateway tolerates a stale heartbeat (the worker STA is busy in a COM
/// call), but once the oldest pending command is older than this the heartbeat watchdog
/// faults the worker anyway. Default 75; must be at least <see cref="HeartbeatGraceSeconds"/>.
/// The worker's own watchdog keeps its separate, fixed 75-second ceiling.
/// </summary>
public int HeartbeatStuckCeilingSeconds { get; init; } =
(int)Workers.WorkerClientOptions.DefaultHeartbeatStuckCeiling.TotalSeconds;
/// <summary>
/// Resolves the effective heartbeat check interval: <see cref="HeartbeatCheckIntervalSeconds"/>,
/// else the deprecated <see cref="HeartbeatIntervalSeconds"/>, else
/// <see cref="DefaultHeartbeatCheckIntervalSeconds"/>.
/// </summary>
/// <returns>The heartbeat check interval in seconds.</returns>
public int ResolveHeartbeatCheckIntervalSeconds() =>
HeartbeatCheckIntervalSeconds ?? HeartbeatIntervalSeconds ?? DefaultHeartbeatCheckIntervalSeconds;
/// <summary>
/// The maximum worker-frame (pipe) message size in bytes. Must stay at least
/// <see cref="Workers.WorkerFrameProtocolOptions.EnvelopeOverheadReserveBytes"/> above
@@ -92,13 +92,7 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
pipe,
frameOptions,
processHandle);
WorkerClientOptions clientOptions = new()
{
HeartbeatGrace = TimeSpan.FromSeconds(_options.Worker.HeartbeatGraceSeconds),
HeartbeatCheckInterval = TimeSpan.FromSeconds(_options.Worker.HeartbeatIntervalSeconds),
EventChannelCapacity = _options.Events.QueueCapacity,
MaxPendingCommands = _options.Sessions.MaxPendingCommandsPerSession,
};
WorkerClientOptions clientOptions = CreateWorkerClientOptions(_options);
workerClient = new WorkerClient(
connection,
@@ -208,4 +202,26 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
{
await pipe.WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Maps the bound <c>MxGateway:*</c> options onto the per-session <see cref="WorkerClientOptions"/>.
/// Every <see cref="WorkerClientOptions"/> field is set from configuration here, so none is left
/// silently on its compile-time default.
/// </summary>
/// <param name="options">The bound gateway options.</param>
/// <returns>The worker client options for a new session.</returns>
internal static WorkerClientOptions CreateWorkerClientOptions(GatewayOptions options)
{
ArgumentNullException.ThrowIfNull(options);
return new WorkerClientOptions
{
HeartbeatGrace = TimeSpan.FromSeconds(options.Worker.HeartbeatGraceSeconds),
HeartbeatCheckInterval = TimeSpan.FromSeconds(options.Worker.ResolveHeartbeatCheckIntervalSeconds()),
HeartbeatStuckCeiling = TimeSpan.FromSeconds(options.Worker.HeartbeatStuckCeilingSeconds),
EventChannelCapacity = options.Events.QueueCapacity,
EventChannelFullModeTimeout = TimeSpan.FromMilliseconds(options.Worker.EventChannelFullModeTimeoutMilliseconds),
MaxPendingCommands = options.Sessions.MaxPendingCommandsPerSession,
};
}
}
@@ -49,8 +49,10 @@
"RequiredArchitecture": "X86",
"StartupTimeoutSeconds": 30,
"ShutdownTimeoutSeconds": 10,
"HeartbeatIntervalSeconds": 5,
"HeartbeatCheckIntervalSeconds": 5,
"HeartbeatGraceSeconds": 15,
"HeartbeatStuckCeilingSeconds": 75,
"EventChannelFullModeTimeoutMilliseconds": 5000,
"MaxMessageBytes": 16842752
},
"Sessions": {
@@ -41,7 +41,9 @@ public sealed class GatewayOptionsTests
Assert.Equal(2000, options.Worker.PipeConnectAttemptTimeoutMilliseconds);
Assert.Equal(1500, options.Worker.WriteCompletionWaitMilliseconds);
Assert.Equal(10, options.Worker.ShutdownTimeoutSeconds);
Assert.Equal(5, options.Worker.HeartbeatIntervalSeconds);
Assert.Equal(5, options.Worker.ResolveHeartbeatCheckIntervalSeconds());
Assert.Equal(75, options.Worker.HeartbeatStuckCeilingSeconds);
Assert.Equal(5000, options.Worker.EventChannelFullModeTimeoutMilliseconds);
Assert.Equal(15, options.Worker.HeartbeatGraceSeconds);
// 16 MiB public gRPC cap plus the 64 KiB worker-frame envelope reserve for headroom.
Assert.Equal((16 * 1024 * 1024) + (64 * 1024), options.Worker.MaxMessageBytes);
@@ -110,6 +112,11 @@ public sealed class GatewayOptionsTests
[InlineData("MxGateway:Worker:ExecutablePath", "worker.dll", "MxGateway:Worker:ExecutablePath must point to a .exe file.")]
[InlineData("MxGateway:Worker:PipeConnectAttemptTimeoutMilliseconds", "0", "MxGateway:Worker:PipeConnectAttemptTimeoutMilliseconds must be greater than zero.")]
[InlineData("MxGateway:Worker:WriteCompletionWaitMilliseconds", "-1", "MxGateway:Worker:WriteCompletionWaitMilliseconds must be greater than or equal to zero.")]
[InlineData("MxGateway:Worker:HeartbeatCheckIntervalSeconds", "0", "MxGateway:Worker:HeartbeatCheckIntervalSeconds must be greater than zero.")]
[InlineData("MxGateway:Worker:HeartbeatIntervalSeconds", "0", "MxGateway:Worker:HeartbeatCheckIntervalSeconds must be greater than zero.")]
[InlineData("MxGateway:Worker:HeartbeatCheckIntervalSeconds", "16", "MxGateway:Worker:HeartbeatGraceSeconds must be greater than or equal to HeartbeatCheckIntervalSeconds.")]
[InlineData("MxGateway:Worker:EventChannelFullModeTimeoutMilliseconds", "0", "MxGateway:Worker:EventChannelFullModeTimeoutMilliseconds must be greater than zero.")]
[InlineData("MxGateway:Worker:HeartbeatStuckCeilingSeconds", "14", "MxGateway:Worker:HeartbeatStuckCeilingSeconds must be greater than or equal to HeartbeatGraceSeconds.")]
[InlineData("MxGateway:Sessions:DefaultLeaseSeconds", "0", "MxGateway:Sessions:DefaultLeaseSeconds must be greater than zero.")]
[InlineData("MxGateway:Sessions:LeaseSweepIntervalSeconds", "0", "MxGateway:Sessions:LeaseSweepIntervalSeconds must be greater than zero.")]
[InlineData("MxGateway:Sessions:DetachGraceSeconds", "-1", "MxGateway:Sessions:DetachGraceSeconds must be zero or greater (0 disables detach-grace retention).")]
@@ -126,6 +133,42 @@ public sealed class GatewayOptionsTests
Assert.Contains(exception.Failures, failure => failure.Contains(expectedFailure, StringComparison.Ordinal));
}
/// <summary>
/// mxaccessgw#192: the deprecated <c>HeartbeatIntervalSeconds</c> key still sets the
/// heartbeat check interval, so existing configuration keeps its meaning after the rename.
/// </summary>
[Fact]
public void HeartbeatIntervalSeconds_DeprecatedAlias_SetsCheckInterval()
{
GatewayOptions options = BindOptions(new Dictionary<string, string?>
{
["MxGateway:Ldap:ServiceAccountPassword"] = "test-bind-password",
["MxGateway:Worker:HeartbeatIntervalSeconds"] = "7",
});
Assert.Equal(7, options.Worker.ResolveHeartbeatCheckIntervalSeconds());
}
/// <summary>
/// mxaccessgw#192: setting both the new key and its deprecated alias is ambiguous and
/// fails validation rather than silently preferring one.
/// </summary>
[Fact]
public void HeartbeatCheckInterval_BothKeysSet_FailsValidation()
{
OptionsValidationException exception = Assert.Throws<OptionsValidationException>(() =>
_ = BindOptions(new Dictionary<string, string?>
{
["MxGateway:Ldap:ServiceAccountPassword"] = "test-bind-password",
["MxGateway:Worker:HeartbeatCheckIntervalSeconds"] = "5",
["MxGateway:Worker:HeartbeatIntervalSeconds"] = "5",
}));
Assert.Contains(
exception.Failures,
failure => failure.Contains("HeartbeatIntervalSeconds is a deprecated alias", StringComparison.Ordinal));
}
/// <summary>Verifies that pepper secret names are redacted in the effective configuration.</summary>
[Fact]
public void EffectiveConfiguration_RedactsPepperSecretName()
@@ -317,7 +317,7 @@ public sealed class GatewayEndToEndFakeWorkerSmokeTests
{
StartupTimeoutSeconds = 5,
ShutdownTimeoutSeconds = 5,
HeartbeatIntervalSeconds = 30,
HeartbeatCheckIntervalSeconds = 30,
HeartbeatGraceSeconds = 30,
MaxMessageBytes = WorkerFrameProtocolOptions.DefaultMaxMessageBytes,
},
@@ -528,7 +528,7 @@ public sealed class GatewayEndToEndMultiSubscriberTests(ITestOutputHelper output
{
StartupTimeoutSeconds = 5,
ShutdownTimeoutSeconds = 5,
HeartbeatIntervalSeconds = 30,
HeartbeatCheckIntervalSeconds = 30,
HeartbeatGraceSeconds = 30,
MaxMessageBytes = WorkerFrameProtocolOptions.DefaultMaxMessageBytes,
},
@@ -644,7 +644,7 @@ public sealed class GatewayEndToEndReconnectReplayTests(ITestOutputHelper output
{
StartupTimeoutSeconds = 5,
ShutdownTimeoutSeconds = 5,
HeartbeatIntervalSeconds = 30,
HeartbeatCheckIntervalSeconds = 30,
HeartbeatGraceSeconds = 30,
MaxMessageBytes = WorkerFrameProtocolOptions.DefaultMaxMessageBytes,
},
@@ -124,6 +124,52 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
Assert.True(launcher.Process.IsDisposed);
}
/// <summary>
/// mxaccessgw#192: every <see cref="WorkerClientOptions"/> field comes from configuration.
/// The heartbeat check interval binds from <c>HeartbeatCheckIntervalSeconds</c> (not the
/// worker send cadence), and the event-channel full-mode timeout and heartbeat stuck
/// ceiling — previously fixed compile-time defaults — follow their new options.
/// </summary>
[Fact]
public void CreateWorkerClientOptions_MapsEveryFieldFromConfiguration()
{
GatewayOptions options = new()
{
Worker = new WorkerOptions
{
HeartbeatCheckIntervalSeconds = 3,
HeartbeatGraceSeconds = 20,
HeartbeatStuckCeilingSeconds = 90,
EventChannelFullModeTimeoutMilliseconds = 2500,
},
Events = new EventOptions { QueueCapacity = 64 },
Sessions = new SessionOptions { MaxPendingCommandsPerSession = 32 },
};
WorkerClientOptions clientOptions = SessionWorkerClientFactory.CreateWorkerClientOptions(options);
Assert.Equal(TimeSpan.FromSeconds(3), clientOptions.HeartbeatCheckInterval);
Assert.Equal(TimeSpan.FromSeconds(20), clientOptions.HeartbeatGrace);
Assert.Equal(TimeSpan.FromSeconds(90), clientOptions.HeartbeatStuckCeiling);
Assert.Equal(TimeSpan.FromMilliseconds(2500), clientOptions.EventChannelFullModeTimeout);
Assert.Equal(64, clientOptions.EventChannelCapacity);
Assert.Equal(32, clientOptions.MaxPendingCommands);
}
/// <summary>
/// mxaccessgw#192: with no worker options set, the mapped values equal the historical
/// compile-time defaults, so the change is behaviour-neutral for existing deployments.
/// </summary>
[Fact]
public void CreateWorkerClientOptions_Defaults_MatchHistoricalConstants()
{
WorkerClientOptions clientOptions = SessionWorkerClientFactory.CreateWorkerClientOptions(new GatewayOptions());
Assert.Equal(TimeSpan.FromSeconds(5), clientOptions.HeartbeatCheckInterval);
Assert.Equal(WorkerClientOptions.DefaultHeartbeatStuckCeiling, clientOptions.HeartbeatStuckCeiling);
Assert.Equal(WorkerClientOptions.DefaultEventChannelFullModeTimeout, clientOptions.EventChannelFullModeTimeout);
}
private static GatewayOptions CreateOptions(int startupTimeoutSeconds = 5)
{
return new GatewayOptions
@@ -132,7 +178,7 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
{
StartupTimeoutSeconds = startupTimeoutSeconds,
ShutdownTimeoutSeconds = 5,
HeartbeatIntervalSeconds = 30,
HeartbeatCheckIntervalSeconds = 30,
HeartbeatGraceSeconds = 30,
MaxMessageBytes = WorkerFrameProtocolOptions.DefaultMaxMessageBytes,
},