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)

This commit is contained in:
Joseph Doherty
2026-12-03 09:52:19 -05:00
parent 159524edd9
commit 2c22ae6bd4
6 changed files with 345 additions and 21 deletions
@@ -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();
}
/// <inheritdoc />
@@ -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
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="commandEnvelope">Command envelope to enqueue.</param>
/// <param name="correlationId">Command correlation id.</param>
/// <param name="pendingCommand">The command's pending entry.</param>
/// <param name="method">Command method name for metrics and messages.</param>
/// <param name="timeout">The whole command deadline.</param>
/// <param name="cancellationToken">The caller's token.</param>
/// <returns>The part of <paramref name="timeout"/> left for the reply wait.</returns>
private async Task<TimeSpan> 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);
}
/// <summary>Creates gateway hello envelope.</summary>
/// <returns>The hello envelope.</returns>
private WorkerEnvelope CreateGatewayHelloEnvelope()
@@ -57,11 +57,13 @@ public sealed class WorkerClientOptions
/// <summary>
/// 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 <c>HeartbeatLoopAsync</c> fires the
/// <c>HeartbeatExpired</c> fault even if commands are still pending;
/// a truly stuck COM call shouldn't keep the watchdog suppressed
/// indefinitely. Mirrors <c>HeartbeatStuckCeiling</c> on
/// the worker side.
/// than this, or the last heartbeat is older than this, the gateway-side
/// <c>HeartbeatLoopAsync</c> fires the <c>HeartbeatExpired</c> 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 <c>HeartbeatStuckCeiling</c> on the worker side.
/// </summary>
public TimeSpan HeartbeatStuckCeiling { get; init; }
}
@@ -1152,6 +1152,197 @@ public sealed class WorkerClientTests
Assert.Equal(WorkerClientState.Faulted, client.State);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerCommandReply>? previousInvoke = null;
for (int round = 0; round < 6 && client.State == WorkerClientState.Ready; round++)
{
CancellationTokenSource caller = new();
Task<WorkerCommandReply> 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<Exception>(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();
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>
/// 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
/// <see cref="WorkerClientErrorCode.CommandTimeout"/> after its timeout instead of waiting
/// indefinitely.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerCommandReply> invokeTask = client.InvokeAsync(
CreateCommand(MxCommandKind.Advise),
TestTimeout,
callerCts.Token);
if (round == 0)
{
await gatewayStream.FirstStalledWrite.WaitAsync(TestTimeout);
}
await callerCts.CancelAsync();
await Assert.ThrowsAnyAsync<OperationCanceledException>(
async () => await invokeTask.WaitAsync(TestTimeout));
}
TimeSpan commandTimeout = TimeSpan.FromMilliseconds(300);
WorkerClientException exception = await Assert.ThrowsAsync<WorkerClientException>(
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<WorkerClientException>(
async () => await client.InvokeAsync(CreateCommand(MxCommandKind.Ping), commandTimeout, CancellationToken.None)
.WaitAsync(TestTimeout));
Assert.Equal(WorkerClientErrorCode.CommandTimeout, second.ErrorCode);
}
/// <summary>
/// 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
/// <see cref="WorkerClientErrorCode.CommandTimeout"/>.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<WorkerCommandReply> 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);
}
/// <summary>
/// A transient burst that exceeds
/// <see cref="WorkerClientOptions.EventChannelCapacity"/> must be
@@ -13,9 +13,27 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider
private long _watchedTimersCreated;
private long _watchedTimersConsumed;
private long _timestampReads;
/// <summary>Gets the number of times <see cref="GetUtcNow"/> has been read.</summary>
public long UtcNowReads => Interlocked.Read(ref _utcNowReads);
/// <summary>
/// Gets the number of times <see cref="GetTimestamp"/> has been read. A loop that measures
/// elapsed time on the monotonic clock (<see cref="TimeProvider.GetElapsedTime(long)"/>)
/// evaluates its condition through this read rather than through <see cref="GetUtcNow"/>.
/// </summary>
public long TimestampReads => Interlocked.Read(ref _timestampReads);
/// <summary>
/// Gets or sets how far the monotonic timestamp (<see cref="GetTimestamp"/>) lags the wall
/// clock. Raising it right before an <see cref="FakeTimeProvider.Advance"/> of the same size
/// models a host wall-clock step: <see cref="GetUtcNow"/> 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.
/// </summary>
public TimeSpan MonotonicLag { get; set; }
/// <inheritdoc />
public override DateTimeOffset GetUtcNow()
{
@@ -23,6 +41,13 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider
return base.GetUtcNow();
}
/// <inheritdoc />
public override long GetTimestamp()
{
Interlocked.Increment(ref _timestampReads);
return base.GetTimestamp() - (long)(MonotonicLag.TotalSeconds * TimestampFrequency);
}
/// <summary>
/// Gets or sets the due time of the timer the loop under test re-arms each iteration
/// (for <c>Task.Delay(interval, timeProvider, ct)</c> this is the interval). When set,
@@ -66,8 +91,9 @@ public sealed class TickObservingTimeProvider : FakeTimeProvider
}
/// <summary>
/// Advances the clock and waits until a consumer has read <see cref="GetUtcNow"/> again,
/// which proves the awakened loop evaluated its condition against the advanced time.
/// Advances the clock and waits until a consumer has read <see cref="GetUtcNow"/> or
/// <see cref="GetTimestamp"/> again, which proves the awakened loop evaluated its condition
/// against the advanced time.
/// </summary>
/// <param name="delta">Amount to advance.</param>
/// <param name="timeout">Real-time bound on the wait.</param>
@@ -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();