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

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:
Joseph Doherty
2026-12-03 13:10:35 -05:00
parent a38578d0e2
commit bb63c8ba72
7 changed files with 193 additions and 8 deletions
+1 -1
View File
@@ -534,7 +534,7 @@ behavior.
| `MxGateway:Alarms:SubscriptionExpression` | _(empty)_ | AVEVA alarm-subscription expression the monitor subscribes on startup, in canonical `\\<machine>\Galaxy!<area>` form. The literal `Galaxy` provider is correct regardless of the Galaxy database name. When empty and `Enabled` is `true`, the gateway falls back to `\\<MachineName>\Galaxy!<DefaultArea>` if `DefaultArea` is set. |
| `MxGateway:Alarms:DefaultArea` | _(empty)_ | Area name used to compose a default subscription when `SubscriptionExpression` is empty. If both are empty while `Enabled` is `true`, the monitor faults with a configuration diagnostic. |
| `MxGateway:Alarms:ReconcileIntervalSeconds` | `30` | How often the monitor reconciles its in-process alarm cache against the worker's authoritative active-alarm snapshot, and, on a separate loop at the same cadence, re-resolves and on material change hot-swaps the subtag fallback watch-list (the resolution is cached per Galaxy deploy time, so an undeployed galaxy costs one deploy-time query per tick). The acknowledged watch-list fingerprint advances only after an OK worker reply. Must be between 1 and 86,400 when `Enabled` is true; the monitor floors it at 5 seconds. |
| `MxGateway:Alarms:PollIntervalMilliseconds` | `500` | Cadence at which the worker's STA polls the AVEVA alarm consumer (`GetXmlCurrentAlarms2`) for the active-alarm snapshot the live feed diffs. Must be between `100` and `3600000` (one hour): every poll is a COM call plus an XML parse on the same STA that serves reads and writes, so a tighter cadence starves the command path, while a value above an hour stops being a cadence and silently disables alarm polling. The gateway conveys the value to the worker via the `MXGATEWAY_ALARM_POLL_INTERVAL_MS` environment variable; a missing or out-of-range value leaves the worker on the 500 ms default rather than failing the session. |
| `MxGateway:Alarms:PollIntervalMilliseconds` | `500` | Cadence at which the worker's STA polls the AVEVA alarm consumer (`GetXmlCurrentAlarms2`) for the active-alarm snapshot the live feed diffs. The worker polls only while the session has an alarm subscription; an unsubscribed session's poll loop is parked and costs nothing at this cadence. Must be between `100` and `3600000` (one hour): every poll is a COM call plus an XML parse on the same STA that serves reads and writes, so a tighter cadence starves the command path, while a value above an hour stops being a cadence and silently disables alarm polling. The gateway conveys the value to the worker via the `MXGATEWAY_ALARM_POLL_INTERVAL_MS` environment variable; a missing or out-of-range value leaves the worker on the 500 ms default rather than failing the session. |
| `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` | Cap the worker passes to `GetXmlCurrentAlarms2`'s `maxAlmCnt`. Must be between `64` and `65536` — the worker is a 32-bit process that materializes each reply as one BSTR (streamed into one record per alarm, not a DOM), so an unbounded cap faults the STA with an out-of-memory rather than merely slowing it. It doubles as the **truncation threshold**: a fetch returning exactly this many records is treated as truncated, because the COM API caps its reply with no "more available" flag. On a truncated poll the worker retains the alarms the capped reply could not mention instead of letting their absence read as a clear, and logs a rate-limited `AlarmSnapshotTruncated` warning to its stderr (identifiers and counts only). **Remediation when you see that warning: raise this value** so the steady-state active-alarm count fits inside one fetch. A galaxy permanently above the cap holds stale entries in the snapshot until a sub-cap poll, and loses clear→re-raise cycles that happen entirely out of window (see `docs/DesignDecisions.md`). Conveyed to the worker via the `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` environment variable; a missing or out-of-range value leaves the worker on the 1024 default. |
| `MxGateway:Alarms:AckClientName` | `MxGateway` | MXAccess client name the alarm worker's ack writer registers with; the Historian records it as each acknowledgement's OperatorNode. 1-64 printable characters. Conveyed via `MXGATEWAY_ALARM_ACK_CLIENT_NAME`. |
+13
View File
@@ -1083,6 +1083,19 @@ the STA more than 75 s without pumping *should* fault — that is the ceiling's
contract). The flag is named generically so any future non-dispatcher STA work
reuses it.
The poll loop runs only while the handler has an alarm subscription (MXA-011).
It starts with the session but parks on a semaphore while
`IAlarmCommandHandler.IsSubscribed` is false, so a session that never subscribes
to alarms — or has unsubscribed — takes no timer, thread-pool or STA wake-ups at
the poll rate. A successful `Subscribe` raises `SubscriptionActivated`, which
releases the semaphore; the loop then resumes ticking at `AlarmPollInterval`.
While subscribed it never parks, so the failover consumer still sees every
`PollOnce` it counts primary failures and failback probes on (MXA-001). Shutdown
cancels a parked loop the same way as a sleeping one, so the graceful-shutdown
join and its grace bound (MXA-003) are unchanged. The consecutive-failure count
below resets when the loop parks, so a new subscription does not inherit an
earlier one's failure run.
A `PollOnce` that throws does not fault the session on the first failure. The
poll loop counts consecutive failures and records the alarm-poll fault
(`MxaccessEventConversionFailed`) only when the count reaches
@@ -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;