perf(worker): alarm poll loop parks until a subscription activates instead of ticking (MXA-011, #258)
ci / windows-x86 (push) Successful in 3m10s
ci / java (push) Failing after 11m14s
ci / portable (push) Failing after 19m30s
ci / windows-x86 (push) Successful in 3m10s
ci / java (push) Failing after 11m14s
ci / portable (push) Failing after 19m30s
The poll loop skipped the STA hop while unsubscribed but its timer still woke every interval (a Task.Delay timer plus a thread-pool continuation per tick on every idle worker). It now parks on a semaphore while IsSubscribed is false and is released by the handler's new SubscriptionActivated event; a subscribe that races the park is kept by the semaphore count. While subscribed it never parks, so failover polling and probes (MXA-001) are unchanged, and shutdown cancels a parked loop like a sleeping one, so the MXA-003 join and grace bound hold. The failure run resets when the loop parks.
This commit is contained in:
@@ -588,6 +588,9 @@ public sealed class AlarmCommandExecutorTests
|
||||
/// <inheritdoc />
|
||||
public bool IsSubscribed => LastSubscription is not null && !UnsubscribeCalled;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? SubscriptionActivated;
|
||||
|
||||
/// <summary>Gets the last subscription expression.</summary>
|
||||
public string? LastSubscription { get; private set; }
|
||||
|
||||
@@ -627,6 +630,7 @@ public sealed class AlarmCommandExecutorTests
|
||||
{
|
||||
LastSubscription = command.SubscriptionExpression;
|
||||
LastSessionId = sessionId;
|
||||
SubscriptionActivated?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>Gets the most recent replacement watch list.</summary>
|
||||
|
||||
@@ -416,6 +416,61 @@ public sealed class MxAccessStaSessionTests
|
||||
Assert.True(handler.PollCount > 0, "Polling should start once the handler is subscribed.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MXA-011: an unsubscribed poll loop parks instead of waking on its timer, polls once a
|
||||
/// subscription activates, parks again after unsubscribe, and resumes on the next subscribe.
|
||||
/// Each loop wake-up reads <see cref="FakeAlarmCommandHandler.IsSubscribed"/>, so a parked loop
|
||||
/// leaves the read count flat while a timer-driven one would add one read per interval.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RunAlarmPollLoop_WhileUnsubscribed_ParksWithoutTimerWakeUps()
|
||||
{
|
||||
FakeAlarmCommandHandler handler = new();
|
||||
using StaRuntime runtime = CreateRuntime();
|
||||
using MxAccessStaSession session = new(
|
||||
runtime,
|
||||
new FakeMxAccessComObjectFactory(),
|
||||
new FakeMxAccessEventSink(),
|
||||
new MxAccessEventQueue(),
|
||||
(_eq, _affinity, _comFactory) => handler);
|
||||
session.AlarmPollInterval = TimeSpan.FromMilliseconds(10);
|
||||
|
||||
await session.StartAsync("session-1", workerProcessId: 1);
|
||||
|
||||
// Never subscribed: one check, then parked. A 10 ms timer would read ~30 times here.
|
||||
await Task.Delay(300);
|
||||
Assert.InRange(handler.IsSubscribedReadCount, 1, 2);
|
||||
Assert.Equal(0, handler.PollCount);
|
||||
|
||||
handler.IsSubscribed = true;
|
||||
await WaitForAsync(() => handler.PollCount >= 3);
|
||||
|
||||
// Unsubscribe: the loop notices on its next wake-up and parks again.
|
||||
handler.IsSubscribed = false;
|
||||
await Task.Delay(100);
|
||||
int readsWhenParked = handler.IsSubscribedReadCount;
|
||||
int pollsWhenParked = handler.PollCount;
|
||||
await Task.Delay(300);
|
||||
Assert.InRange(handler.IsSubscribedReadCount - readsWhenParked, 0, 1);
|
||||
Assert.Equal(pollsWhenParked, handler.PollCount);
|
||||
|
||||
// A later subscribe wakes it again.
|
||||
handler.IsSubscribed = true;
|
||||
await WaitForAsync(() => handler.PollCount > pollsWhenParked);
|
||||
}
|
||||
|
||||
private static async Task WaitForAsync(Func<bool> condition)
|
||||
{
|
||||
using CancellationTokenSource timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
while (!condition() && !timeout.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(10, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
Assert.True(condition(), "Condition not met within 5 seconds.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gap 2: Verifies that the STA poll loop stops when the session is disposed —
|
||||
/// no further PollOnce calls after disposal. <see cref="MxAccessStaSession.Dispose"/>
|
||||
@@ -868,14 +923,36 @@ public sealed class MxAccessStaSessionTests
|
||||
private int pollCount;
|
||||
private int? lastPollThreadId;
|
||||
|
||||
/// <summary>Gets a value indicating whether the alarm client is currently subscribed.</summary>
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? SubscriptionActivated;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the alarm client is currently subscribed. Setting it
|
||||
/// to true raises <see cref="SubscriptionActivated"/>, as a successful Subscribe does.
|
||||
/// </summary>
|
||||
public bool IsSubscribed
|
||||
{
|
||||
get => Volatile.Read(ref subscribed) != 0;
|
||||
set => Volatile.Write(ref subscribed, value ? 1 : 0);
|
||||
get
|
||||
{
|
||||
Interlocked.Increment(ref isSubscribedReads);
|
||||
return Volatile.Read(ref subscribed) != 0;
|
||||
}
|
||||
|
||||
set
|
||||
{
|
||||
Volatile.Write(ref subscribed, value ? 1 : 0);
|
||||
if (value)
|
||||
{
|
||||
SubscriptionActivated?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int subscribed;
|
||||
private int isSubscribedReads;
|
||||
|
||||
/// <summary>Gets how many times <see cref="IsSubscribed"/> was read — once per poll-loop wake-up.</summary>
|
||||
public int IsSubscribedReadCount => Volatile.Read(ref isSubscribedReads);
|
||||
|
||||
/// <summary>Gets the last alarm subscription name.</summary>
|
||||
public string? LastSubscription { get; private set; }
|
||||
|
||||
@@ -164,6 +164,9 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler
|
||||
get { lock (syncRoot) return dispatcher is not null; }
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public event EventHandler? SubscriptionActivated;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Subscribe(SubscribeAlarmsCommand command, string sessionId)
|
||||
{
|
||||
@@ -210,6 +213,11 @@ public sealed class AlarmCommandHandler : IAlarmCommandHandler
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
// Outside the lock: the subscription is in force, so wake the parked poll loop. A
|
||||
// listener failure must not turn a successful subscribe into a failed command.
|
||||
try { SubscriptionActivated?.Invoke(this, EventArgs.Empty); }
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { /* swallow */ }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -21,6 +21,14 @@ public interface IAlarmCommandHandler : IDisposable
|
||||
/// </summary>
|
||||
bool IsSubscribed { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Raised after a <see cref="Subscribe"/> call succeeds, on the thread that made it (the
|
||||
/// STA). The STA alarm poll loop parks while <see cref="IsSubscribed"/> is false and waits on
|
||||
/// this signal instead of a timer, so a session that is not subscribed takes no timer or
|
||||
/// thread-pool wake-ups at all. Handlers must be cheap and must not throw.
|
||||
/// </summary>
|
||||
event EventHandler? SubscriptionActivated;
|
||||
|
||||
/// <summary>
|
||||
/// Begin an alarm subscription from the supplied command. The command's
|
||||
/// <see cref="SubscribeAlarmsCommand.ForcedMode"/> and
|
||||
|
||||
@@ -65,6 +65,11 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
private IAlarmCommandHandler? alarmCommandHandler;
|
||||
private CancellationTokenSource? alarmPollCts;
|
||||
private Task? alarmPollTask;
|
||||
|
||||
// Wakes the parked alarm poll loop when the handler subscribes (MXA-011). Count 0..1: a signal
|
||||
// that arrives before the loop parks is kept, so a subscribe racing the park is never missed.
|
||||
private SemaphoreSlim? alarmPollWake;
|
||||
private EventHandler? alarmSubscriptionActivatedHandler;
|
||||
private int? alarmConsumerThreadId;
|
||||
|
||||
// True on the STA thread exactly around the alarm PollOnce COM call. The alarm poll runs outside
|
||||
@@ -392,15 +397,59 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
|
||||
if (alarmCommandHandler is not null)
|
||||
{
|
||||
SemaphoreSlim wake = new SemaphoreSlim(0, 1);
|
||||
alarmPollWake = wake;
|
||||
alarmSubscriptionActivatedHandler = (_, _) => SignalAlarmPollWake(wake);
|
||||
alarmCommandHandler.SubscriptionActivated += alarmSubscriptionActivatedHandler;
|
||||
alarmPollCts = new CancellationTokenSource();
|
||||
alarmPollTask = RunAlarmPollLoopAsync(alarmCommandHandler, alarmPollCts.Token);
|
||||
alarmPollTask = RunAlarmPollLoopAsync(alarmCommandHandler, wake, alarmPollCts.Token);
|
||||
}
|
||||
|
||||
return ready;
|
||||
}
|
||||
|
||||
private static void SignalAlarmPollWake(SemaphoreSlim wake)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (wake.CurrentCount == 0)
|
||||
{
|
||||
wake.Release();
|
||||
}
|
||||
}
|
||||
catch (SemaphoreFullException)
|
||||
{
|
||||
// Already signalled by a concurrent subscribe — one pending wake is enough.
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// The session is shutting down; there is no loop left to wake.
|
||||
}
|
||||
}
|
||||
|
||||
// Detaches the subscribe signal and disposes the wake semaphore. Called after the poll loop
|
||||
// was cancelled (and joined, when it stopped in time): a loop still parked sees the
|
||||
// cancellation first, and one that outlived the join treats a disposed semaphore as a stop.
|
||||
private void ReleaseAlarmPollWake()
|
||||
{
|
||||
SemaphoreSlim? wake = alarmPollWake;
|
||||
EventHandler? activated = alarmSubscriptionActivatedHandler;
|
||||
alarmPollWake = null;
|
||||
alarmSubscriptionActivatedHandler = null;
|
||||
if (activated is not null && alarmCommandHandler is not null)
|
||||
{
|
||||
try { alarmCommandHandler.SubscriptionActivated -= activated; } catch { /* best effort */ }
|
||||
}
|
||||
|
||||
if (wake is not null)
|
||||
{
|
||||
try { wake.Dispose(); } catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
private Task RunAlarmPollLoopAsync(
|
||||
IAlarmCommandHandler handler,
|
||||
SemaphoreSlim wake,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
TimeSpan pollInterval = AlarmPollInterval;
|
||||
@@ -410,6 +459,31 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
int consecutiveFailures = 0;
|
||||
while (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Park while nothing is subscribed (MXA-011): no timer, no thread-pool wake-up and
|
||||
// no STA hop until SubscriptionActivated signals. The loop never parks while a
|
||||
// subscription is in force, so the failover consumer still gets every PollOnce it
|
||||
// counts failures and failback probes on, and shutdown cancels a parked loop as
|
||||
// promptly as a sleeping one. A failure run does not carry across subscriptions.
|
||||
if (!handler.IsSubscribed)
|
||||
{
|
||||
consecutiveFailures = 0;
|
||||
try
|
||||
{
|
||||
await wake.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-check: a stale signal from an earlier subscription parks again.
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(pollInterval, cancellationToken).ConfigureAwait(false);
|
||||
@@ -424,9 +498,8 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
return;
|
||||
}
|
||||
|
||||
// No subscription means PollOnce would find no dispatcher and return. Skip the STA
|
||||
// hop (a work item plus a message-loop wake) so a session that never subscribes, or
|
||||
// has not yet, costs no STA time at the poll rate.
|
||||
// Unsubscribed during the delay: PollOnce would find no dispatcher. Skip the STA hop
|
||||
// and park on the next iteration.
|
||||
if (!handler.IsSubscribed)
|
||||
{
|
||||
continue;
|
||||
@@ -806,6 +879,7 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
}
|
||||
|
||||
pollCtsToDispose.Dispose();
|
||||
ReleaseAlarmPollWake();
|
||||
}
|
||||
|
||||
// Stop the alarm consumer's polling timer and tear down the
|
||||
@@ -954,6 +1028,7 @@ public sealed class MxAccessStaSession : IWorkerRuntimeSession
|
||||
catch (ObjectDisposedException) { }
|
||||
}
|
||||
try { pollCtsToDispose.Dispose(); } catch { }
|
||||
ReleaseAlarmPollWake();
|
||||
}
|
||||
|
||||
IAlarmCommandHandler? alarmHandlerToDispose = alarmCommandHandler;
|
||||
|
||||
Reference in New Issue
Block a user