fix(gateway): wake the worker-ready wait on a state-change signal instead of a 25 ms poll (mxaccessgw#189)
GetReadyWorkerClientAsync re-read the session and worker states every 25 ms until the WorkerReadyWaitTimeoutMs deadline. It now waits on two TaskCompletionSource signals - one completed by every GatewaySession _state / _workerClient write, one by every WorkerClient _state write - and re-evaluates only when one fires or the remaining budget elapses. Both signals are captured under the lock before the state is evaluated, so a transition between the evaluation and the await is not lost. IWorkerClient gains GetStateChangedSignal(), a default interface member that returns null; a client without a signal (the test fakes) is re-read on the old 25 ms interval, so the fakes need no change. The production WorkerClient always publishes one. Default behaviour (WorkerReadyWaitTimeoutMs = 0, fail fast) is unchanged. Regression tests (SessionManagerTests): ...WakesWithoutPollTimer and ...FailsFastWithoutPollTimer never advance the FakeTimeProvider, so they hang and fail against the poll loop; WorkerClientTests.GetStateChangedSignal_ CompletesOnEachTransition pins the worker-side signal. Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
@@ -17,11 +17,18 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
// cannot be mutated by a cast — the tag set is a visibility grant, not a scratch collection.
|
||||
private static readonly IReadOnlySet<string> EmptyTags = FrozenSet<string>.Empty;
|
||||
|
||||
// Re-read interval for a worker client that publishes no state-change signal (test fakes);
|
||||
// see WaitForStateChangeAsync.
|
||||
private static readonly TimeSpan UnsignalledWorkerPollInterval = TimeSpan.FromMilliseconds(25);
|
||||
|
||||
private readonly object _syncRoot = new();
|
||||
private readonly SemaphoreSlim _closeLock = new(1, 1);
|
||||
private readonly SessionEventStreaming _eventStreaming;
|
||||
private IWorkerClient? _workerClient;
|
||||
private SessionState _state = SessionState.Creating;
|
||||
// Completed (and replaced) under _syncRoot whenever _state or _workerClient changes, so the
|
||||
// worker-ready wait is woken by the change rather than polling for it (mxaccessgw#189).
|
||||
private TaskCompletionSource _stateChanged = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private string? _finalFault;
|
||||
private DateTimeOffset _lastClientActivityAt;
|
||||
private DateTimeOffset? _leaseExpiresAt;
|
||||
@@ -456,6 +463,7 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
}
|
||||
|
||||
_workerClient = workerClient;
|
||||
SignalStateChangedUnderLock();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -614,6 +622,8 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
}
|
||||
|
||||
_state = nextState;
|
||||
|
||||
SignalStateChangedUnderLock();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1108,6 +1118,7 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
|
||||
_finalFault = reason;
|
||||
_state = SessionState.Faulted;
|
||||
SignalStateChangedUnderLock();
|
||||
|
||||
// Stamp the fault time once, on the first fault, so the sweeper can apply
|
||||
// FaultedGraceSeconds. A subsequent MarkFaulted (already-faulted session) keeps the
|
||||
@@ -1927,6 +1938,7 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
alreadyClosing = _closeStarted;
|
||||
_closeStarted = true;
|
||||
_state = SessionState.Closing;
|
||||
SignalStateChangedUnderLock();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1994,6 +2006,7 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
|
||||
alreadyClosing = _closeStarted;
|
||||
_state = SessionState.Closing;
|
||||
SignalStateChangedUnderLock();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -2039,6 +2052,16 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
return now - idleSince >= _unattachedGrace;
|
||||
}
|
||||
|
||||
// Wakes every GetReadyWorkerClientAsync waiter that captured the current signal. Called under
|
||||
// _syncRoot after each _state / _workerClient write; RunContinuationsAsynchronously keeps the
|
||||
// waiters' continuations off this thread, so none of them runs while _syncRoot is held.
|
||||
private void SignalStateChangedUnderLock()
|
||||
{
|
||||
TaskCompletionSource changed = _stateChanged;
|
||||
_stateChanged = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
changed.TrySetResult();
|
||||
}
|
||||
|
||||
// Final terminal transition; under _syncRoot to keep _state writes single-lock.
|
||||
// Closed is unconditionally terminal — TransitionTo refuses to overwrite it —
|
||||
// so we don't need to re-check the precondition here.
|
||||
@@ -2047,6 +2070,7 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
lock (_syncRoot)
|
||||
{
|
||||
_state = SessionState.Closed;
|
||||
SignalStateChangedUnderLock();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2264,9 +2288,11 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
/// session is <see cref="SessionState.Ready"/> but the worker has transiently diverged
|
||||
/// to a non-terminal state (<see cref="WorkerClientState.Handshaking"/>/
|
||||
/// <see cref="WorkerClientState.Created"/>) and the configured worker-ready wait timeout
|
||||
/// is positive, this polls (outside <c>_syncRoot</c>) until the worker reaches
|
||||
/// <see cref="WorkerClientState.Ready"/> or the deadline elapses, re-evaluating the
|
||||
/// fast-path/fail-fast decision under the lock on each poll. Terminal worker states, a
|
||||
/// is positive, this waits (outside <c>_syncRoot</c>) until the worker reaches
|
||||
/// <see cref="WorkerClientState.Ready"/> or the deadline elapses. The wait is woken by a
|
||||
/// state-change signal from the session and the worker client rather than a fixed poll,
|
||||
/// and re-evaluates the fast-path/fail-fast decision under the lock on each wake-up, so a
|
||||
/// transition is acted on as soon as it happens (mxaccessgw#189). Terminal worker states, a
|
||||
/// missing worker, or a non-<c>Ready</c> session fail fast immediately. With the default
|
||||
/// timeout of zero this behaves byte-for-byte like the synchronous fail-fast path: no
|
||||
/// await, no delay.
|
||||
@@ -2275,11 +2301,15 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
/// <returns>The worker client once both the session and worker are <c>Ready</c>.</returns>
|
||||
private async Task<IWorkerClient> GetReadyWorkerClientAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
const int pollIntervalMs = 25;
|
||||
|
||||
string? failureMessage;
|
||||
Task sessionChanged;
|
||||
Task? workerChanged;
|
||||
lock (_syncRoot)
|
||||
{
|
||||
// Capture both signals BEFORE evaluating, so a transition that lands after the
|
||||
// evaluation completes a signal this call is about to wait on (no lost wake-up).
|
||||
sessionChanged = _stateChanged.Task;
|
||||
workerChanged = _workerClient?.GetStateChangedSignal();
|
||||
IWorkerClient? ready = EvaluateReadyUnderLock(out failureMessage);
|
||||
if (ready is not null)
|
||||
{
|
||||
@@ -2300,17 +2330,21 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
DateTimeOffset deadline = _eventStreaming.TimeProvider.GetUtcNow() + _workerReadyWaitTimeout;
|
||||
TimeProvider timeProvider = _eventStreaming.TimeProvider;
|
||||
DateTimeOffset deadline = timeProvider.GetUtcNow() + _workerReadyWaitTimeout;
|
||||
while (true)
|
||||
{
|
||||
await Task.Delay(
|
||||
TimeSpan.FromMilliseconds(pollIntervalMs),
|
||||
_eventStreaming.TimeProvider,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
TimeSpan remaining = deadline - timeProvider.GetUtcNow();
|
||||
if (remaining > TimeSpan.Zero)
|
||||
{
|
||||
await WaitForStateChangeAsync(sessionChanged, workerChanged, remaining, timeProvider, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
lock (_syncRoot)
|
||||
{
|
||||
sessionChanged = _stateChanged.Task;
|
||||
workerChanged = _workerClient?.GetStateChangedSignal();
|
||||
IWorkerClient? ready = EvaluateReadyUnderLock(out failureMessage);
|
||||
if (ready is not null)
|
||||
{
|
||||
@@ -2323,26 +2357,47 @@ public sealed class GatewaySession : IAsyncDisposable
|
||||
{
|
||||
throw new SessionManagerException(SessionManagerErrorCode.SessionNotReady, failureMessage);
|
||||
}
|
||||
}
|
||||
|
||||
if (_eventStreaming.TimeProvider.GetUtcNow() >= deadline)
|
||||
{
|
||||
lock (_syncRoot)
|
||||
if (timeProvider.GetUtcNow() >= deadline)
|
||||
{
|
||||
IWorkerClient? ready = EvaluateReadyUnderLock(out failureMessage);
|
||||
if (ready is not null)
|
||||
{
|
||||
return ready;
|
||||
}
|
||||
|
||||
throw new SessionManagerException(
|
||||
SessionManagerErrorCode.SessionNotReady,
|
||||
failureMessage ?? BuildNotReadyMessage());
|
||||
BuildNotReadyMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits until the session or worker state changes, the remaining ready-wait budget
|
||||
/// elapses, or <paramref name="cancellationToken"/> is cancelled. A worker client that
|
||||
/// publishes no state-change signal (<see cref="IWorkerClient.GetStateChangedSignal"/>
|
||||
/// returned <see langword="null"/>) is re-read on <see cref="UnsignalledWorkerPollInterval"/>
|
||||
/// instead; the production <see cref="WorkerClient"/> always publishes one.
|
||||
/// </summary>
|
||||
private static async Task WaitForStateChangeAsync(
|
||||
Task sessionChanged,
|
||||
Task? workerChanged,
|
||||
TimeSpan remaining,
|
||||
TimeProvider timeProvider,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
TimeSpan budget = workerChanged is null && remaining > UnsignalledWorkerPollInterval
|
||||
? UnsignalledWorkerPollInterval
|
||||
: remaining;
|
||||
Task changed = workerChanged is null
|
||||
? sessionChanged
|
||||
: Task.WhenAny(sessionChanged, workerChanged);
|
||||
try
|
||||
{
|
||||
await changed.WaitAsync(budget, timeProvider, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
// Budget elapsed with no transition: the caller re-evaluates and applies the deadline.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates readiness while the caller already holds <c>_syncRoot</c>. Returns the
|
||||
/// worker client when both the session and worker are <see cref="WorkerClientState.Ready"/>
|
||||
|
||||
Reference in New Issue
Block a user