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
+1 -1
View File
@@ -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. |
+15
View File
@@ -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
@@ -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();