From 0ccf3d400b46677abd872cfc49b4c0b7ebb6c460 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:08:07 -0500 Subject: [PATCH] fix(alarms): diff across monitor restarts, version reconciles, cache the watch-list (SEC-005..SEC-010, #250, #254) - SEC-005: a lifecycle that ends keeps its cache as the previous generation; the next lifecycle's first reconcile diffs against it and broadcasts Clear for alarms gone during the gap (derived from the new worker snapshot, documented in gateway.md as a reconcile repair, not a synthesized event). The retired set is hidden from CurrentAlarms; gap joiners get the whole set. Each lifecycle start broadcasts its re-baselined provider status. - SEC-006: live transitions stamp a sequence; a reconcile leaves alarms changed live after it was issued alone (no stale Clear / re-raise). - SEC-007: an Acknowledge of an uncached alarm is broadcast but no longer inserts an ActiveAcked row; other non-Raise kinds do not touch the cache. - SEC-009: a changed original raise time is a Raise repair; a non-OK reconcile is logged/surfaced and fails the initial reconcile. - SEC-008: watch-list resolution cached per Galaxy deploy time and fingerprinted by SHA-256 once per resolution; refresh runs on its own loop; the failover-edge refresh is bounded to 10 s. - SEC-010: restart backoff doubles from 5 s to a 5 min cap and resets on Monitoring; repeated identical faults log one summary line. --- docs/AlarmClientDiscovery.md | 14 +- docs/GatewayConfiguration.md | 2 +- gateway.md | 42 +- .../Alarms/AlarmWatchListResolver.cs | 62 +- .../Alarms/GatewayAlarmMonitor.cs | 493 +++++++++-- .../Alarms/AlarmWatchListResolverTests.cs | 107 +++ .../Alarms/GatewayAlarmMonitorCacheTests.cs | 835 ++++++++++++++++++ 7 files changed, 1484 insertions(+), 71 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Tests/Alarms/GatewayAlarmMonitorCacheTests.cs diff --git a/docs/AlarmClientDiscovery.md b/docs/AlarmClientDiscovery.md index 4bdfedd4..855e3dc9 100644 --- a/docs/AlarmClientDiscovery.md +++ b/docs/AlarmClientDiscovery.md @@ -900,10 +900,16 @@ MXAccess item addresses for the `InAlarm`, `Acked`, `AckMsg`, and `Priority` subtags (confirmed AVEVA `AlarmExtension` field names, verified against the live ZB Galaxy `attribute_definition` rows). -The gateway refreshes this list on the existing alarm reconciliation cadence -and immediately before publishing a failover-to-subtag status. It compares a -canonical fingerprint of all six target fields and sends -`UpdateAlarmWatchListCommand` only for a material change. The worker constructs, +The gateway refreshes this list on the alarm reconciliation cadence, on a loop +of its own so a slow or hung Galaxy SQL query never delays a reconcile pass, and +immediately before publishing a failover-to-subtag status (bounded to 10 seconds, +after which the status is published with the last acknowledged list and the +periodic loop retries). The resolver caches a successful resolution against the +Galaxy's last deploy time (`GetLastDeployTimeAsync`), so an undeployed galaxy +costs one deploy-time query per refresh rather than the alarm-attribute query +and a rebuilt list; a failed discovery or an unknown deploy time is not cached. +The gateway compares a SHA-256 of a canonical fingerprint of all six target +fields and sends `UpdateAlarmWatchListCommand` only for a material change. The worker constructs, subscribes, and attaches the replacement standby on its STA before swapping it in; a setup failure leaves the previous standby and the current primary/subtag mode unchanged. The gateway advances its acknowledged fingerprint only after an diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index a0ab3893..ad38f11a 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -527,7 +527,7 @@ behavior. | `MxGateway:Alarms:Enabled` | `false` | Gates the gateway's always-on central alarm monitor. When `true`, the gateway opens one gateway-owned worker session dedicated to alarms, caches the active-alarm set, and fans it out to every client through the `StreamAlarms` RPC — no client opens its own session to see alarms. | | `MxGateway:Alarms:SubscriptionExpression` | _(empty)_ | AVEVA alarm-subscription expression the monitor subscribes on startup, in canonical `\\\Galaxy!` form. The literal `Galaxy` provider is correct regardless of the Galaxy database name. When empty and `Enabled` is `true`, the gateway falls back to `\\\Galaxy!` 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 re-resolves and, on material change, hot-swaps the subtag fallback watch-list, then reconciles its in-process alarm cache against the worker's authoritative active-alarm snapshot. 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: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: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`. | diff --git a/gateway.md b/gateway.md index a7713d4f..24ef4497 100644 --- a/gateway.md +++ b/gateway.md @@ -190,6 +190,44 @@ at-least-once: alarm-feed consumers (`StreamAlarms` clients and the dashboard alarm hub) must apply transitions idempotently — treat one as "set this alarm to this state", never as an increment or a toggle. +**Reconcile snapshots are versioned against the live feed.** The reply to +`QueryActiveAlarms` and a later live transition travel different paths, so a +snapshot can land after a transition it predates. Every live transition takes a +monotonic sequence number and stamps its alarm; a reconcile captures the sequence +before it sends the command, and leaves any alarm stamped after that capture +alone — no synthetic Clear for an alarm a newer live Raise added, no re-raise for +one a newer live Clear removed. The next pass reconciles it. A pass also treats a +changed original raise timestamp as a new instance (a Raise repair even when the +state is unchanged), and an alarm that is not in the cache is repaired as a Raise +followed by an Acknowledge when the worker reports it already acknowledged. A live +`Acknowledge` for an alarm the cache does not hold (an ack of an alarm that already +returned to normal) is forwarded on the feed but does not create a cache entry. +A non-OK reconcile reply is logged and surfaced on the monitor's `LastError`; on +the initial reconcile of a lifecycle it fails the lifecycle instead of entering +`Monitoring` with an empty cache. + +**Monitor restart diffs instead of dropping the cache.** Feed subscribers outlive +the monitor's worker session, so when a lifecycle ends (worker exit, lease +overflow, command failure) the monitor keeps its cache as the previous +generation. The first reconcile of the next lifecycle diffs the new worker's +snapshot against it and broadcasts a Clear for every alarm that is no longer +active, and a repair for every alarm that changed. These Clears are not invented +events: like every reconcile repair they are feed transitions derived from the +worker's own authoritative snapshot, compared with the last set the feed +published, and the only difference from a periodic pass is that the gap spans a +session instead of one interval. Without them, an alarm that returned to normal +while the monitor was down stayed active on every attached consumer indefinitely, +because the new cache never contained it and nothing would ever clear it. While a +lifecycle is down the retained set is hidden from `CurrentAlarms` +(`QueryActiveAlarms` and the dashboard poll report no alarms rather than a set of +unknown age); a subscriber that attaches in that gap gets an empty snapshot and +is sent every active alarm as repairs on the first reconcile. Each lifecycle start +also broadcasts its re-baselined provider status, so a subscriber that last saw a +subtag failover learns the restarted monitor is back on the alarm manager. A +failed lifecycle restarts after 5 seconds, doubling per consecutive failure up to +5 minutes and resetting once a lifecycle reaches `Monitoring`; each attempt launches +a worker, so a permanent misconfiguration must not cycle one every few seconds. + ### Alarm providers and failover The alarm feed has two providers, both implemented worker-side: @@ -293,8 +331,8 @@ frames, so the caveat precedes the records it qualifies — and thereafter only a *change* of verdict (a status frame repeated every reconcile is one consumers learn to ignore). The open-time frame is unconditional: an explicit `truncated = false` is what separates a complete set from a gateway that never -sends the frame. A monitor restart drops the verdict with the cache generation it -describes, and because feed subscribers outlive the monitor's worker session that +sends the frame. A monitor restart drops the verdict with the worker session that +produced it, and because feed subscribers outlive the monitor's worker session that drop is emitted as a clearing frame too. The flag means "this active set may be incomplete", not "this record is unreliable" — it is independent of the subtag-fallback `degraded` field above. It is not diff --git a/src/ZB.MOM.WW.MxGateway.Server/Alarms/AlarmWatchListResolver.cs b/src/ZB.MOM.WW.MxGateway.Server/Alarms/AlarmWatchListResolver.cs index 4c48017f..fa90f18c 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Alarms/AlarmWatchListResolver.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Alarms/AlarmWatchListResolver.cs @@ -10,6 +10,15 @@ namespace ZB.MOM.WW.MxGateway.Server.Alarms; /// and composes the per-attribute subtag item addresses from the configured /// subtag names. /// +/// +/// The alarm monitor re-resolves on every reconcile tick, but the watch-list only changes +/// when the galaxy is deployed. A successful resolution is therefore cached against the +/// Galaxy's last deploy time and the options instance it was built from: while both are +/// unchanged the same instance is returned for the +/// cost of one deploy-time query, and the monitor recognizes it by reference and skips +/// re-fingerprinting (SEC-008). A failed discovery, or an unknown deploy time, is never +/// cached, so the next call queries again. +/// public sealed class AlarmWatchListResolver : IAlarmWatchListResolver { private const string ProviderLiteral = "Galaxy"; @@ -18,6 +27,8 @@ public sealed class AlarmWatchListResolver : IAlarmWatchListResolver private readonly IGalaxyRepository _repository; private readonly ILogger _logger; + private readonly object _cacheSync = new(); + private CachedResolution? _cache; /// Initializes the watch-list resolver. /// Galaxy Repository used for alarm-attribute discovery. @@ -39,6 +50,25 @@ public sealed class AlarmWatchListResolver : IAlarmWatchListResolver AlarmDiscoveryOptions discovery = options.Fallback.Discovery; + // Config-only lists depend on nothing but the options; GR-backed lists also on the + // galaxy's deploy time. Either way an unchanged key returns the cached instance. + DateTime? deployTime = discovery.UseGalaxyRepository + ? await TryGetLastDeployTimeAsync(cancellationToken).ConfigureAwait(false) + : null; + bool cacheable = !discovery.UseGalaxyRepository || deployTime is not null; + if (cacheable) + { + lock (_cacheSync) + { + if (_cache is { } cached + && ReferenceEquals(cached.Options, options) + && cached.DeployTime == deployTime) + { + return cached.Resolution; + } + } + } + // The caller cannot grade an empty watch-list without knowing whether discovery // was asked to contribute and whether it failed while doing so, because the failure is // deliberately swallowed below. @@ -154,13 +184,43 @@ public sealed class AlarmWatchListResolver : IAlarmWatchListResolver _logger.LogDebug("Resolved alarm subtag watch-list with {TargetCount} target(s).", targets.Count); } - return new AlarmWatchListResolution( + AlarmWatchListResolution resolution = new( targets, DiscoveryAttempted: discovery.UseGalaxyRepository, DiscoveryFailed: discoveryFailureMessage is not null, discoveryFailureMessage); + + if (cacheable && !resolution.DiscoveryFailed) + { + lock (_cacheSync) + { + _cache = new CachedResolution(options, deployTime, resolution); + } + } + + return resolution; } + // The deploy-time query is the cache key, not a requirement: when it fails or the galaxy + // reports none, the caller simply resolves uncached, exactly as before the cache existed. + private async Task TryGetLastDeployTimeAsync(CancellationToken cancellationToken) + { + try + { + return await _repository.GetLastDeployTimeAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogDebug(ex, "Galaxy last-deploy-time query failed; resolving the alarm watch-list uncached."); + return null; + } + } + + private sealed record CachedResolution( + AlarmsOptions Options, + DateTime? DeployTime, + AlarmWatchListResolution Resolution); + /// /// Derives the source-object reference for a configuration entry: the /// substring before the first '.', or the whole string when there is no dot. diff --git a/src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs b/src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs index e3bd487e..781e831a 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Alarms/GatewayAlarmMonitor.cs @@ -21,9 +21,16 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic private const string MonitorClientName = "gateway-alarm-monitor"; private const string BackendName = "Galaxy"; private const int SubscriberQueueCapacity = 2048; - private static readonly TimeSpan RestartBackoff = TimeSpan.FromSeconds(5); + private static readonly TimeSpan DefaultInitialRestartBackoff = TimeSpan.FromSeconds(5); + private static readonly TimeSpan MaximumRestartBackoff = TimeSpan.FromMinutes(5); private static readonly TimeSpan StartupGrace = TimeSpan.FromSeconds(2); + // Upper bound on the watch-list refresh the failover edge awaits before publishing the + // provider status. The refresh normally costs one deploy-time query (the resolver caches the + // alarm-attribute query per deploy), but a hung Galaxy SQL must not stall transition + // processing at the moment the feed is degraded (SEC-008). + private static readonly TimeSpan FailoverWatchListRefreshTimeout = TimeSpan.FromSeconds(10); + private readonly ISessionManager _sessionManager; private readonly IAlarmWatchListResolver _watchListResolver; private readonly GatewayMetrics _metrics; @@ -49,6 +56,38 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic // duplicate would be sitting in — and the map stays bounded by the feed's churn per interval. private readonly Dictionary _clearedByReconcile = new(StringComparer.Ordinal); + // Reconcile versioning, guarded by _sync (SEC-006). Every live transition takes the next + // sequence number and stamps its reference with it; a reconcile captures the sequence before + // it issues QueryActiveAlarms. A reference stamped after that capture changed live while the + // snapshot was in flight, so the snapshot is older than the cache for that alarm and must not + // overwrite it — neither by a synthetic Clear nor by a re-raise. Stamps at or below a pass's + // capture are superseded by that pass and pruned, which bounds the map by one interval's churn. + private long _liveSequence; + private readonly Dictionary _liveStampByReference = new(StringComparer.Ordinal); + + // Whether _alarms is the previous lifecycle's generation, guarded by _sync (SEC-005). A + // lifecycle that ends keeps its cache instead of dropping it: feed subscribers outlive the + // monitor's worker session and still hold that set, so the first reconcile of the next + // lifecycle diffs against it and broadcasts a Clear for every alarm that returned to normal + // during the gap. While stale the set is hidden from CurrentAlarms (the poll surfaces report + // nothing rather than a set of unknown age), and a subscriber that attaches in the gap gets an + // empty snapshot and is flagged for a full replay on that first reconcile. + private bool _cacheStale; + + // Last watch-list resolution and its fingerprint hash, guarded by _sync (SEC-008). The resolver + // returns the same instance while the Galaxy deploy time is unchanged, so an unchanged + // resolution is recognized by reference and is not re-fingerprinted every refresh. + private AlarmWatchListResolution? _lastResolution; + private string _lastResolutionFingerprint = string.Empty; + + // Serializes watch-list refreshes: the periodic refresh loop and the failover edge can both + // re-resolve and send UpdateAlarmWatchList, and two replacements must not interleave. + private readonly SemaphoreSlim _watchListRefreshGate = new(1, 1); + + private int _consecutiveLifecycleFailures; + private string? _lastLifecycleFaultMessage; + private bool _reconcileFailing; + // Current provider status (mode + degraded + reason + since), guarded by _sync. // Initialized to the alarm-manager, not-degraded baseline so a late joiner sees // a sensible status even before any OnAlarmProviderModeChanged event arrives. @@ -66,14 +105,16 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic private bool _subtagCoverageMissing; private string _subtagCoverageReason = string.Empty; - // The full canonical watch-list fingerprint acknowledged by the worker and its alarm + // The SHA-256 of the canonical watch-list fingerprint acknowledged by the worker, and its alarm // references, guarded by _sync. The fingerprint advances only after an OK subscribe/update // reply, so a rejected replacement remains material and is retried on the next refresh edge. + // Only the hash is retained: the canonical string covers the whole watch-list and would pin + // several MB for the process lifetime on a large galaxy. private string _acknowledgedWatchListFingerprint = string.Empty; private IReadOnlyCollection _sentWatchListReferences = []; // Whether the worker's most recent reconcile fetch was capped, guarded by _sync. - // Written only by ApplyReconcile (and cleared with the cache), so it describes the last full + // Written only by ApplyReconcile (and cleared when a lifecycle ends), so it describes the last full // reconcile — not necessarily the current _alarms contents, which live transitions keep moving // via ApplyTransition between passes. Read it as "as of the last reconcile, the worker's fetch // was capped", which is the right granularity for a completeness caveat. @@ -101,8 +142,39 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic _metrics = metrics ?? throw new ArgumentNullException(nameof(metrics)); _options = (options ?? throw new ArgumentNullException(nameof(options))).Value.Alarms; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + ReconcileInterval = TimeSpan.FromSeconds(Math.Max(5, _options.ReconcileIntervalSeconds)); } + /// + /// Computes the restart backoff after failed + /// lifecycles in a row: the initial backoff, doubled per further failure, capped at five + /// minutes (SEC-010). Every attempt launches an x86 worker, so a permanent failure must not + /// cycle one every few seconds forever. + /// + /// The first backoff. + /// Failed lifecycles in a row, at least 1. + /// The delay before the next attempt. + internal static TimeSpan ComputeRestartBackoff(TimeSpan initial, int consecutiveFailures) + { + int doublings = Math.Clamp(consecutiveFailures - 1, 0, 30); + double ticks = initial.Ticks * Math.Pow(2, doublings); + return ticks >= MaximumRestartBackoff.Ticks ? MaximumRestartBackoff : TimeSpan.FromTicks((long)ticks); + } + + /// + /// Gets or sets the reconcile cadence. Defaults to + /// floored at 5 seconds; settable so + /// tests can drive reconcile passes without waiting on the production cadence. + /// + internal TimeSpan ReconcileInterval { get; init; } + + /// + /// Gets or sets the first restart backoff after a failed lifecycle. Doubles per consecutive + /// failure up to five minutes and resets once a lifecycle reaches Monitoring. Settable so + /// tests can drive restarts quickly. + /// + internal TimeSpan InitialRestartBackoff { get; init; } = DefaultInitialRestartBackoff; + /// public GatewayAlarmMonitorState State => _state; @@ -125,13 +197,18 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic // Same clone semantics as an uncached read — callers still get instances no // mutation can leak back into the cache — but built once per alarm-set // generation instead of once per caller. - return _currentAlarmsProjection ??= _alarms.Values - .Select(alarm => alarm.Clone()) - .ToArray(); + return BuildProjection(); } } } + // Caller holds _sync. The memoized, cloned projection of the cache — empty while the cache is + // a retired lifecycle's generation (see _cacheStale). + private ActiveAlarmSnapshot[] BuildProjection() => + _currentAlarmsProjection ??= _cacheStale + ? [] + : _alarms.Values.Select(alarm => alarm.Clone()).ToArray(); + /// public bool SnapshotTruncated { @@ -182,13 +259,32 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic { _state = GatewayAlarmMonitorState.Faulted; _lastError = exception.Message; - _logger.LogWarning( - exception, - "Gateway alarm monitor lifecycle faulted; restarting in {Backoff}.", - RestartBackoff); + int failures = ++_consecutiveLifecycleFailures; + TimeSpan backoff = ComputeRestartBackoff(InitialRestartBackoff, failures); + + // The first occurrence of a fault carries the stack; an identical repeat is one + // summary line, so a permanent misconfiguration does not grow the log by a stack + // trace per attempt (SEC-010). + if (string.Equals(exception.Message, _lastLifecycleFaultMessage, StringComparison.Ordinal)) + { + _logger.LogWarning( + "Gateway alarm monitor lifecycle still faulting ({Diagnostic}); attempt {Attempt}, restarting in {Backoff}.", + exception.Message, + failures, + backoff); + } + else + { + _logger.LogWarning( + exception, + "Gateway alarm monitor lifecycle faulted; restarting in {Backoff}.", + backoff); + } + + _lastLifecycleFaultMessage = exception.Message; try { - await Task.Delay(RestartBackoff, stoppingToken).ConfigureAwait(false); + await Task.Delay(backoff, stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -242,6 +338,11 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic _providerDegraded = initialDegraded; _providerReason = initialReason; _providerSince = DateTimeOffset.UtcNow; + + // Feed subscribers outlive the worker session and may still show the previous + // lifecycle's status (a Subtag failover, say). Auto mode raises no mode-change event at + // start, so without this frame they would keep it indefinitely (SEC-005). + BroadcastToAll(new AlarmFeedMessage { ProviderStatus = BuildProviderStatus() }); } // Align the observable gauge with the lifecycle baseline without recording @@ -273,10 +374,12 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic using IEventSubscriberLease alarmLease = session.AttachInternalEventSubscriber(IsAlarmMonitorEvent); await SubscribeAlarmsAsync(session.SessionId, subscription, stoppingToken).ConfigureAwait(false); - await ReconcileAsync(session.SessionId, stoppingToken).ConfigureAwait(false); + await ReconcileAsync(session.SessionId, initial: true, stoppingToken).ConfigureAwait(false); _state = GatewayAlarmMonitorState.Monitoring; _lastError = null; + _consecutiveLifecycleFailures = 0; + _lastLifecycleFaultMessage = null; _logger.LogInformation( "Gateway alarm monitor active on {Subscription} (session {SessionId}, worker pid {WorkerPid}).", subscription, @@ -285,6 +388,10 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic using CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); Task reconcileLoop = ReconcileLoopAsync(session.SessionId, linked.Token); + + // The watch-list refresh runs on its own loop so a slow or hung Galaxy SQL query never + // delays the reconcile cadence (SEC-008). + Task watchListLoop = WatchListRefreshLoopAsync(session.SessionId, linked.Token); try { // Consume mapped MxEvents through the session's single distributor pump (as an @@ -318,11 +425,11 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic await linked.CancelAsync().ConfigureAwait(false); try { - await reconcileLoop.ConfigureAwait(false); + await Task.WhenAll(reconcileLoop, watchListLoop).ConfigureAwait(false); } catch { - // Reconcile-loop teardown errors are not actionable here. + // Reconcile/refresh-loop teardown errors are not actionable here. } } @@ -333,7 +440,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic finally { lock (_sync) { _session = null; } - ClearCache(); + RetireCacheGeneration(); try { await _sessionManager.CloseSessionAsync(session.SessionId, CancellationToken.None).ConfigureAwait(false); @@ -407,9 +514,10 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic throw new InvalidOperationException($"Worker rejected SubscribeAlarms: {diagnostic}"); } + string fingerprint = FingerprintOf(resolution); lock (_sync) { - AcknowledgeWatchList(watchList); + AcknowledgeWatchList(watchList, fingerprint); } } @@ -417,15 +525,12 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic { try { - int seconds = Math.Max(5, _options.ReconcileIntervalSeconds); - using PeriodicTimer timer = new(TimeSpan.FromSeconds(seconds)); + using PeriodicTimer timer = new(ReconcileInterval); while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false)) { try { - await RefreshAlarmWatchListAsync(sessionId, broadcast: true, cancellationToken) - .ConfigureAwait(false); - await ReconcileAsync(sessionId, cancellationToken).ConfigureAwait(false); + await ReconcileAsync(sessionId, initial: false, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -449,8 +554,19 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic } } - private async Task ReconcileAsync(string sessionId, CancellationToken cancellationToken) + // One reconcile pass. The live sequence is captured BEFORE the command goes out, so + // ApplyReconcile can tell which cached entries changed live while the snapshot was in flight + // (SEC-006). A non-OK reply is not silent (SEC-009): it fails the lifecycle when it is the + // initial reconcile — entering Monitoring with an empty cache would look healthy and report + // zero alarms — and is a logged, surfaced error on a periodic pass. + private async Task ReconcileAsync(string sessionId, bool initial, CancellationToken cancellationToken) { + long issuedAt; + lock (_sync) + { + issuedAt = _liveSequence; + } + WorkerCommandReply reply = await _sessionManager.InvokeAsync( sessionId, new WorkerCommand @@ -464,16 +580,42 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic cancellationToken) .ConfigureAwait(false); - if (reply.Reply?.ProtocolStatus?.Code != ProtocolStatusCode.Ok) + QueryActiveAlarmsReplyPayload? payload = reply.Reply?.QueryActiveAlarms; + if (reply.Reply?.ProtocolStatus?.Code != ProtocolStatusCode.Ok || payload is null) { + ProtocolStatusCode? code = reply.Reply?.ProtocolStatus?.Code; + string diagnostic = reply.Reply?.DiagnosticMessage is { Length: > 0 } detail + ? detail + : reply.Reply?.ProtocolStatus?.Message is { Length: > 0 } message + ? message + : payload is null && code == ProtocolStatusCode.Ok + ? "reply carried no active-alarm payload" + : $"status {code}"; + if (initial) + { + throw new InvalidOperationException($"Worker rejected the initial QueryActiveAlarms: {diagnostic}"); + } + + _lastError = $"Alarm reconcile failed: {diagnostic}"; + if (!_reconcileFailing) + { + _reconcileFailing = true; + _logger.LogWarning( + "Alarm reconcile rejected by the worker ({Diagnostic}); keeping the current cache.", + diagnostic); + } + return; } - QueryActiveAlarmsReplyPayload? payload = reply.Reply.QueryActiveAlarms; - if (payload is not null) + if (_reconcileFailing) { - ApplyReconcile(payload.Snapshots, payload.SnapshotTruncated); + _reconcileFailing = false; + _lastError = null; + _logger.LogInformation("Alarm reconcile recovered."); } + + ApplyReconcile(payload.Snapshots, payload.SnapshotTruncated, issuedAt); } // Distributor-side filter for the monitor's internal lease: admits only the event bodies the @@ -494,6 +636,10 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic lock (_sync) { + // Stamp the reference so a reconcile snapshot issued before this transition cannot + // overwrite what it did to the cache (SEC-006). + _liveStampByReference[reference] = ++_liveSequence; + if (transition.TransitionKind == AlarmTransitionKind.Clear) { bool wasKnown = _alarms.Remove(reference); @@ -507,7 +653,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic return; } } - else + else if (UpdatesCache(transition.TransitionKind, _alarms.ContainsKey(reference))) { ActiveAlarmSnapshot snapshot = SnapshotFromTransition(transition); bool duplicate = _alarms.TryGetValue(reference, out ActiveAlarmSnapshot? existing) @@ -524,6 +670,19 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic } } + // Which non-Clear transitions change the active-alarm cache. A Raise inserts or replaces the + // entry. An Acknowledge only moves an alarm the cache already holds to ActiveAcked: an + // acknowledge of an alarm that already returned to normal (the worker maps UNACK_RTN → ACK_RTN + // to Acknowledge) is history, and inserting it would list an inactive alarm as active until + // the next reconcile (SEC-007). Every other kind (Unspecified, the never-emitted Retrigger) + // carries no state the cache can trust. All of them are still broadcast to the feed. + private static bool UpdatesCache(AlarmTransitionKind kind, bool cached) => kind switch + { + AlarmTransitionKind.Raise => true, + AlarmTransitionKind.Acknowledge => cached, + _ => false, + }; + // Best-effort dedup of the reconcile/live race. A reconcile that already synthesized // this transition as a feed repair left the cache carrying the worker's transition timestamp // and resulting state — both derived from the same worker-side value the live transition @@ -574,8 +733,22 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic // the provider switch. if (toMode == AlarmProviderMode.Subtag) { - await RefreshAlarmWatchListAsync(sessionId, broadcast: false, cancellationToken) - .ConfigureAwait(false); + using CancellationTokenSource bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + bounded.CancelAfter(FailoverWatchListRefreshTimeout); + try + { + await RefreshAlarmWatchListAsync(sessionId, broadcast: false, bounded.Token) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // Bounded so a hung Galaxy SQL cannot stall transition processing at the failover + // edge (SEC-008). The periodic refresh loop retries; the status below carries the + // last acknowledged coverage verdict meanwhile. + _logger.LogWarning( + "Alarm watch-list refresh on failover exceeded {Timeout}; publishing the provider status with the last acknowledged watch-list.", + FailoverWatchListRefreshTimeout); + } } AlarmProviderStatus status; @@ -611,7 +784,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic // so holding it across the await here would deadlock. Subscribers therefore // see the ProviderStatus push (above) slightly before the cache is re-seeded // by the reconcile — an accepted brief inconsistency. - await ReconcileAsync(sessionId, cancellationToken).ConfigureAwait(false); + await ReconcileAsync(sessionId, initial: false, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -625,6 +798,45 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic } } + // Periodic watch-list refresh, on its own loop at the reconcile cadence so a slow Galaxy SQL + // query never delays a reconcile pass (SEC-008). The resolver caches the alarm-attribute query + // per Galaxy deploy time, so an unchanged galaxy costs one deploy-time query per tick. + private async Task WatchListRefreshLoopAsync(string sessionId, CancellationToken cancellationToken) + { + if (!CanUseSubtagFallback(MapForcedMode(_options.Fallback.Mode))) + { + return; + } + + try + { + using PeriodicTimer timer = new(ReconcileInterval); + while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false)) + { + try + { + await RefreshAlarmWatchListAsync(sessionId, broadcast: true, cancellationToken) + .ConfigureAwait(false); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception exception) + { + _logger.LogDebug(exception, "Alarm watch-list refresh failed; keeping the last acknowledged watch list."); + } + } + } + catch (OperationCanceledException) + { + } + catch (Exception exception) + { + _logger.LogError(exception, "Alarm watch-list refresh loop stopped."); + } + } + private async Task RefreshAlarmWatchListAsync( string sessionId, bool broadcast, @@ -636,6 +848,24 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic return; } + await _watchListRefreshGate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await RefreshAlarmWatchListCoreAsync(sessionId, forcedMode, broadcast, cancellationToken) + .ConfigureAwait(false); + } + finally + { + _watchListRefreshGate.Release(); + } + } + + private async Task RefreshAlarmWatchListCoreAsync( + string sessionId, + AlarmProviderMode forcedMode, + bool broadcast, + CancellationToken cancellationToken) + { AlarmWatchListResolution resolution; try { @@ -653,7 +883,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic return; } - string resolvedFingerprint = CanonicalWatchListFingerprint(resolution.Targets); + string resolvedFingerprint = FingerprintOf(resolution); string acknowledgedFingerprint; lock (_sync) { @@ -691,7 +921,7 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic { if (code == ProtocolStatusCode.Ok) { - AcknowledgeWatchList(resolution.Targets); + AcknowledgeWatchList(resolution.Targets, resolvedFingerprint); SetSubtagCoverage( GradeSubtagCoverage(forcedMode, resolution, staleAgainstSent: false), broadcast); @@ -713,14 +943,39 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic || _options.Fallback.Discovery.IncludeAttributes.Length > 0); // Caller holds _sync. - private void AcknowledgeWatchList(IReadOnlyList watchList) + private void AcknowledgeWatchList(IReadOnlyList watchList, string fingerprint) { - _acknowledgedWatchListFingerprint = CanonicalWatchListFingerprint(watchList); + _acknowledgedWatchListFingerprint = fingerprint; _sentWatchListReferences = watchList .Select(target => target.AlarmFullReference) .ToHashSet(StringComparer.OrdinalIgnoreCase); } + // The fingerprint hash of a resolution, computed once per resolution instance: the resolver + // hands back the same instance while the galaxy is undeployed, so the steady state builds no + // per-target strings at all (SEC-008). + private string FingerprintOf(AlarmWatchListResolution resolution) + { + lock (_sync) + { + if (ReferenceEquals(resolution, _lastResolution)) + { + return _lastResolutionFingerprint; + } + } + + string fingerprint = Convert.ToHexString( + System.Security.Cryptography.SHA256.HashData( + System.Text.Encoding.UTF8.GetBytes(CanonicalWatchListFingerprint(resolution.Targets)))); + lock (_sync) + { + _lastResolution = resolution; + _lastResolutionFingerprint = fingerprint; + } + + return fingerprint; + } + private static string CanonicalWatchListFingerprint(IEnumerable watchList) => string.Join( "\n", @@ -898,7 +1153,21 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic // The flag is set-level status, not a delta: it is recorded, and a CHANGE of verdict is pushed // to the feed as a snapshot_status frame (SetSnapshotTruncated) so live consumers learn the // completeness caveat without polling QueryActiveAlarms. - private void ApplyReconcile(IEnumerable snapshots, bool snapshotTruncated) + // + // Versioning (SEC-006): the snapshot is a point-in-time read issued at `issuedAt` on the live + // sequence. An alarm stamped by a live transition after that point changed while the snapshot + // was in flight, so for that alarm the cache is newer than the snapshot: the pass leaves its + // cache entry (present or absent) alone and broadcasts no repair for it. The next pass, issued + // after the transition, reconciles it. + // + // Restart (SEC-005): the first pass of a lifecycle diffs against the previous lifecycle's + // retained cache, which is what every attached subscriber still holds, so an alarm that + // returned to normal while the monitor was down gets its Clear. Those Clears are derived from + // the worker's own snapshot of the new session compared with the last set the feed published — + // the same presence-delta repair every reconcile makes, not an invented event. A subscriber + // that attached during the gap was given an empty snapshot, so it is sent the whole set as + // Raise (and Acknowledge) repairs instead. + private void ApplyReconcile(IEnumerable snapshots, bool snapshotTruncated, long issuedAt) { Dictionary next = new(StringComparer.Ordinal); foreach (ActiveAlarmSnapshot snapshot in snapshots) @@ -915,8 +1184,22 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic // guard against (one full reconcile interval); start this pass's generation fresh. _clearedByReconcile.Clear(); + bool firstPassAfterRestart = _cacheStale; + Func diffAudience = firstPassAfterRestart + ? subscriber => !subscriber.NeedsFullReplay + : static _ => true; + + Dictionary rebuilt = new(StringComparer.Ordinal); + foreach (KeyValuePair existing in _alarms) { + if (ChangedLiveSince(existing.Key, issuedAt)) + { + // The live feed moved this alarm after the snapshot was taken; keep its state. + rebuilt[existing.Key] = existing.Value; + continue; + } + if (!next.ContainsKey(existing.Key)) { if (existing.Value.OriginalRaiseTimestamp is not null) @@ -926,37 +1209,64 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic Broadcast( new AlarmFeedMessage { Transition = TransitionFromSnapshot(existing.Value, AlarmTransitionKind.Clear) }, - existing.Key); + existing.Key, + diffAudience); } } foreach (KeyValuePair incoming in next) { - if (!_alarms.TryGetValue(incoming.Key, out ActiveAlarmSnapshot? existing)) + if (ChangedLiveSince(incoming.Key, issuedAt)) { - Broadcast( - new AlarmFeedMessage { Transition = TransitionFromSnapshot(incoming.Value, AlarmTransitionKind.Raise) }, - incoming.Key); + // Absent from the cache because a live Clear (or nothing) came after the + // snapshot: the snapshot's presence is the older fact. Present: kept above. + continue; } - else if (existing.CurrentState != incoming.Value.CurrentState) + + rebuilt[incoming.Key] = incoming.Value; + _alarms.TryGetValue(incoming.Key, out ActiveAlarmSnapshot? existing); + foreach (AlarmTransitionKind kind in RepairKinds(existing, incoming.Value)) { - // The alarm was already known but the worker now reports a different state. An - // ActiveAcked snapshot repairs a missed Acknowledge. Any other incoming active - // state repairs a missed Raise for the incoming instance (including an - // acknowledged alarm reference that was cleared and re-raised between passes). - AlarmTransitionKind kind = incoming.Value.CurrentState == AlarmConditionState.ActiveAcked - ? AlarmTransitionKind.Acknowledge - : AlarmTransitionKind.Raise; Broadcast( new AlarmFeedMessage { Transition = TransitionFromSnapshot(incoming.Value, kind) }, - incoming.Key); + incoming.Key, + diffAudience); + } + + if (firstPassAfterRestart) + { + foreach (AlarmTransitionKind kind in RepairKinds(existing: null, incoming.Value)) + { + Broadcast( + new AlarmFeedMessage { Transition = TransitionFromSnapshot(incoming.Value, kind) }, + incoming.Key, + static subscriber => subscriber.NeedsFullReplay); + } } } _alarms.Clear(); - foreach (KeyValuePair incoming in next) + foreach (KeyValuePair entry in rebuilt) { - _alarms[incoming.Key] = incoming.Value; + _alarms[entry.Key] = entry.Value; + } + + // Stamps at or below this pass's capture are superseded by it. + foreach (string reference in _liveStampByReference + .Where(stamp => stamp.Value <= issuedAt) + .Select(stamp => stamp.Key) + .ToArray()) + { + _liveStampByReference.Remove(reference); + } + + if (firstPassAfterRestart) + { + _cacheStale = false; + foreach (Subscriber subscriber in _subscribers) + { + subscriber.NeedsFullReplay = false; + } } SetSnapshotTruncated(snapshotTruncated); @@ -964,6 +1274,46 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic } } + // Caller holds _sync. True when a live transition touched the reference after the reconcile + // whose live-sequence capture is issuedAt was issued. + private bool ChangedLiveSince(string reference, long issuedAt) => + _liveStampByReference.TryGetValue(reference, out long stamp) && stamp > issuedAt; + + // The feed repairs that move a subscriber holding `existing` (null: not holding the alarm) to + // the worker-reported `incoming` state. + // + // - Not held: Raise, plus Acknowledge when the alarm is already acknowledged, so a consumer + // applying transitions as "set this state" ends on ActiveAcked rather than Active. + // - Held, but a different instance (the original raise timestamp moved): the alarm cleared and + // re-raised between passes with both live transitions missed. That is a Raise even when the + // state is unchanged (SEC-009), plus Acknowledge when the new instance is already acked. + // - Held, same instance, state moved to ActiveAcked: a missed Acknowledge. + // - Held, same instance, any other state change: a Raise for the incoming state. + private static IEnumerable RepairKinds(ActiveAlarmSnapshot? existing, ActiveAlarmSnapshot incoming) + { + bool acked = incoming.CurrentState == AlarmConditionState.ActiveAcked; + bool newInstance = existing is null + || (existing.OriginalRaiseTimestamp is not null + && incoming.OriginalRaiseTimestamp is not null + && !existing.OriginalRaiseTimestamp.Equals(incoming.OriginalRaiseTimestamp)); + + if (newInstance) + { + yield return AlarmTransitionKind.Raise; + if (acked) + { + yield return AlarmTransitionKind.Acknowledge; + } + + yield break; + } + + if (existing!.CurrentState != incoming.CurrentState) + { + yield return acked ? AlarmTransitionKind.Acknowledge : AlarmTransitionKind.Raise; + } + } + // Caller holds _sync. Records the truncation verdict and, on a CHANGE of verdict, pushes the // feed-level snapshot_status frame. Edge-triggered rather than per-reconcile: a status frame // repeated every reconcile interval is one consumers learn to ignore. The verdict describes the @@ -987,12 +1337,15 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic // a subscriber that has fallen behind is completed with an AlarmFeedSubscriberOverflowException // and dropped. The typed fault is what lets StreamAlarms answer ResourceExhausted instead of // treating a slow client as a gateway failure. - private void Broadcast(AlarmFeedMessage message, string reference) + private void Broadcast(AlarmFeedMessage message, string reference) => Broadcast(message, reference, null); + + // Caller holds _sync. As Broadcast, restricted to the subscribers `audience` admits. + private void Broadcast(AlarmFeedMessage message, string reference, Func? audience) { for (int index = _subscribers.Count - 1; index >= 0; index--) { Subscriber subscriber = _subscribers[index]; - if (!subscriber.Matches(reference)) + if (!subscriber.Matches(reference) || (audience is not null && !audience(subscriber))) { continue; } @@ -1021,16 +1374,22 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic } } - private void ClearCache() + // Ends the cache generation of a lifecycle that stopped. The alarms are KEPT, marked stale, + // so the next lifecycle's first reconcile can diff against what subscribers were last told + // (see _cacheStale and ApplyReconcile); they are hidden from CurrentAlarms meanwhile. + private void RetireCacheGeneration() { lock (_sync) { - _alarms.Clear(); - // The truncation verdict describes the cache generation being discarded, so it goes - // with it. Carrying it across a monitor restart would caveat an empty set as "may be - // incomplete" on evidence from a session that no longer exists. Dropping a truncated - // verdict IS a completeness change, and feed subscribers outlive the monitor's worker - // session, so this routes through the edge path and they see the clearing frame. + _cacheStale = true; + _clearedByReconcile.Clear(); + _liveStampByReference.Clear(); + + // The truncation verdict describes the session that produced it, so it is dropped with + // that session. Carrying it across a monitor restart would caveat the next set on + // evidence from a session that no longer exists. Dropping a truncated verdict IS a + // completeness change, and feed subscribers outlive the monitor's worker session, so + // this routes through the edge path and they see the clearing frame. SetSnapshotTruncated(false); _currentAlarmsProjection = null; } @@ -1064,15 +1423,17 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic providerStatus = BuildProviderStatus(); snapshotTruncated = _snapshotTruncated; + // Attaching while the cache is a retired generation: the snapshot below is empty, so + // the next lifecycle's first reconcile sends this subscriber the whole set (SEC-005). + subscriber.NeedsFullReplay = _cacheStale; + // Take the memoized projection rather than cloning the whole set per attach: the // clone runs at most once per alarm-set generation (shared with CurrentAlarms), so a // burst of reconnecting subscribers no longer holds the broadcast lock for one full // copy each. The array is never mutated once built — a write to _alarms replaces it // with null — so capturing the reference here pins exactly the generation this // subscriber registered against, which is what keeps snapshot-then-live ordering. - snapshot = _currentAlarmsProjection ??= _alarms.Values - .Select(alarm => alarm.Clone()) - .ToArray(); + snapshot = BuildProjection(); } try @@ -1379,6 +1740,12 @@ public sealed class GatewayAlarmMonitor : BackgroundService, IGatewayAlarmServic /// Gets the channel for publishing alarm messages to this subscriber. public Channel Channel { get; } = channel; + /// + /// Gets or sets a value indicating whether this subscriber attached while the cache was + /// a retired generation and so received an empty snapshot. Guarded by the monitor's lock. + /// + public bool NeedsFullReplay { get; set; } + /// Determines whether the alarm reference matches this subscriber's filter. /// The alarm reference to match. /// if the reference matches this subscriber's prefix filter. diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Alarms/AlarmWatchListResolverTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Alarms/AlarmWatchListResolverTests.cs index 6e89c67c..44a445f1 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Alarms/AlarmWatchListResolverTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Alarms/AlarmWatchListResolverTests.cs @@ -445,6 +445,113 @@ public sealed class AlarmWatchListResolverTests Assert.DoesNotContain(result, t => t.ActiveSubtag.Contains("Pump01", StringComparison.OrdinalIgnoreCase)); } + /// + /// SEC-008: while the galaxy's deploy time is unchanged, repeated resolutions reuse one + /// alarm-attribute query and return the same resolution instance (which the monitor + /// recognizes without re-fingerprinting). A deploy re-queries. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ResolveAsync_UnchangedDeployTime_ReusesTheCachedResolution() + { + DeployingGalaxyRepository repo = new( + [ + new GalaxyAlarmAttributeRow + { + FullTagReference = "Tank01.Level.HiHi", + SourceObjectReference = "Tank01", + Area = "Area1", + }, + ]) + { + DeployTime = new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc), + }; + AlarmWatchListResolver resolver = CreateResolver(repo); + AlarmsOptions options = Options(); + + AlarmWatchListResolution first = await resolver.ResolveAsync(options); + AlarmWatchListResolution second = await resolver.ResolveAsync(options); + AlarmWatchListResolution third = await resolver.ResolveAsync(options); + + Assert.Same(first, second); + Assert.Same(first, third); + Assert.Equal(1, repo.GetAlarmAttributesCount); + Assert.Equal(3, repo.GetLastDeployTimeCount); + + repo.DeployTime = repo.DeployTime!.Value.AddMinutes(5); + AlarmWatchListResolution afterDeploy = await resolver.ResolveAsync(options); + + Assert.NotSame(first, afterDeploy); + Assert.Equal(2, repo.GetAlarmAttributesCount); + } + + /// SEC-008: a failed discovery is never cached; the next resolution queries again. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ResolveAsync_FailedDiscovery_IsNotCached() + { + DeployingGalaxyRepository repo = new([]) + { + DeployTime = new DateTime(2026, 12, 1, 8, 0, 0, DateTimeKind.Utc), + FailAlarmAttributes = true, + }; + AlarmWatchListResolver resolver = CreateResolver(repo); + AlarmsOptions options = Options(); + + AlarmWatchListResolution failed = await resolver.ResolveAsync(options); + Assert.True(failed.DiscoveryFailed); + + repo.FailAlarmAttributes = false; + AlarmWatchListResolution recovered = await resolver.ResolveAsync(options); + + Assert.False(recovered.DiscoveryFailed); + Assert.Equal(2, repo.GetAlarmAttributesCount); + } + + /// with a settable deploy time, counting both queries. + /// The alarm rows to return. + private sealed class DeployingGalaxyRepository(List rows) : IGalaxyRepository + { + /// Gets or sets the deploy time reported. + public DateTime? DeployTime { get; set; } + + /// Gets or sets a value indicating whether the alarm-attribute query fails. + public bool FailAlarmAttributes { get; set; } + + /// Gets the number of alarm-attribute queries. + public int GetAlarmAttributesCount { get; private set; } + + /// Gets the number of deploy-time queries. + public int GetLastDeployTimeCount { get; private set; } + + /// + public Task TestConnectionAsync(CancellationToken ct = default) => Task.FromResult(true); + + /// + public Task GetLastDeployTimeAsync(CancellationToken ct = default) + { + GetLastDeployTimeCount++; + return Task.FromResult(DeployTime); + } + + /// + public Task> GetHierarchyAsync(CancellationToken ct = default) => + Task.FromResult(new List()); + + /// + public Task> GetAttributesAsync(CancellationToken ct = default) => + Task.FromResult(new List()); + + /// + public Task> GetAlarmAttributesAsync(CancellationToken ct = default) + { + GetAlarmAttributesCount++; + return FailAlarmAttributes + ? Task.FromException>(new InvalidOperationException("gr offline")) + : Task.FromResult(rows); + } + } + /// In-memory returning a fixed alarm rowset. private sealed class StubGalaxyRepository(List rows) : IGalaxyRepository { diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Alarms/GatewayAlarmMonitorCacheTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Alarms/GatewayAlarmMonitorCacheTests.cs new file mode 100644 index 00000000..844189e4 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Alarms/GatewayAlarmMonitorCacheTests.cs @@ -0,0 +1,835 @@ +using System.Diagnostics.CodeAnalysis; +using System.Threading.Channels; +using Google.Protobuf.WellKnownTypes; +using Microsoft.Extensions.Logging.Abstractions; +using ZB.MOM.WW.MxGateway.Contracts.Proto; +using ZB.MOM.WW.MxGateway.Server.Alarms; +using ZB.MOM.WW.MxGateway.Server.Configuration; +using ZB.MOM.WW.MxGateway.Server.Metrics; +using ZB.MOM.WW.MxGateway.Server.Sessions; +using ZB.MOM.WW.MxGateway.Tests.TestSupport; + +namespace ZB.MOM.WW.MxGateway.Tests.Alarms; + +/// +/// Cache-correctness tests for from the 2026-12-02 review: +/// acknowledge of an uncached alarm (SEC-007), reconcile versioning against live transitions +/// (SEC-006), same-state re-raise and non-OK reconcile (SEC-009), and monitor restart +/// (SEC-005). The fake session manager hands out a fresh worker event stream per session, so +/// ending one session and letting the supervisor open the next is a real monitor restart. +/// +public sealed class GatewayAlarmMonitorCacheTests +{ + private const string AlarmA = "Galaxy!Area.Tank01.Hi"; + private const string AlarmB = "Galaxy!Area.Tank02.Hi"; + private static readonly TimeSpan WaitTimeout = TimeSpan.FromSeconds(30); + + /// + /// SEC-007: an alarm that raised and returned to normal unacknowledged is gone from the + /// cache; a later Acknowledge of that returned alarm is history and must not re-insert it as + /// an active-acked row. The transition itself still reaches the feed. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task AcknowledgeOfUncachedAlarm_IsBroadcastButNotCached() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout); + + FeedRecorder feed = FeedRecorder.Start(monitor); + await feed.SnapshotComplete.WaitAsync(WaitTimeout); + + sessions.EmitEvent(Transition(1, AlarmA, AlarmTransitionKind.Raise, Ts(0), Ts(0))); + sessions.EmitEvent(Transition(2, AlarmA, AlarmTransitionKind.Clear, Ts(5), Ts(0))); + sessions.EmitEvent(Transition(3, AlarmA, AlarmTransitionKind.Acknowledge, Ts(9), Ts(0))); + + await feed.WaitForTransitionAsync(AlarmA, AlarmTransitionKind.Acknowledge, WaitTimeout); + + Assert.Empty(monitor.CurrentAlarms); + + await feed.StopAsync(); + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// SEC-007: an Acknowledge of an alarm the cache holds still moves it to ActiveAcked. + /// A task that represents the asynchronous operation. + [Fact] + public async Task AcknowledgeOfCachedAlarm_MovesItToActiveAcked() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout); + + sessions.EmitEvent(Transition(1, AlarmA, AlarmTransitionKind.Raise, Ts(0), Ts(0))); + sessions.EmitEvent(Transition(2, AlarmA, AlarmTransitionKind.Acknowledge, Ts(3), Ts(0))); + + await WaitUntilAsync( + () => monitor.CurrentAlarms.Any(a => a.AlarmFullReference == AlarmA + && a.CurrentState == AlarmConditionState.ActiveAcked), + WaitTimeout); + + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// + /// SEC-006: a reconcile snapshot taken before a live Raise must not clear the alarm the + /// Raise put in the cache. The snapshot is parked after it is captured, the Raise is applied, + /// then the stale snapshot lands. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task StaleSnapshotWithoutLiveRaisedAlarm_DoesNotClearIt() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, reconcileInterval: TimeSpan.FromMilliseconds(200)); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout); + FeedRecorder feed = FeedRecorder.Start(monitor); + await feed.SnapshotComplete.WaitAsync(WaitTimeout); + + // The parked pass captures {B}: taken before A raised. + sessions.SetSnapshot(Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1))); + sessions.HoldNextReconcile(); + await sessions.ReconcileParked.WaitAsync(WaitTimeout); + + // Later passes see both, as the worker would once A raised. + sessions.SetSnapshot( + Snapshot(AlarmA, AlarmConditionState.Active, Ts(2), Ts(2)), + Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1))); + sessions.EmitEvent(Transition(1, AlarmA, AlarmTransitionKind.Raise, Ts(2), Ts(2))); + await WaitUntilAsync(() => monitor.CurrentAlarms.Any(a => a.AlarmFullReference == AlarmA), WaitTimeout); + + sessions.ReleaseReconcile(); + await feed.WaitForTransitionAsync(AlarmB, AlarmTransitionKind.Raise, WaitTimeout); + + Assert.DoesNotContain(AlarmTransitionKind.Clear, feed.TransitionsFor(AlarmA)); + Assert.Contains(monitor.CurrentAlarms, a => a.AlarmFullReference == AlarmA); + + await feed.StopAsync(); + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// + /// SEC-006 mirror: a snapshot taken before a live Clear must not re-raise the cleared alarm. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task StaleSnapshotWithLiveClearedAlarm_DoesNotReRaiseIt() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0))); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, reconcileInterval: TimeSpan.FromMilliseconds(200)); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.CurrentAlarms.Any(a => a.AlarmFullReference == AlarmA), WaitTimeout); + FeedRecorder feed = FeedRecorder.Start(monitor); + await feed.SnapshotComplete.WaitAsync(WaitTimeout); + + // The parked pass captures {A, B}: taken before A cleared. + sessions.SetSnapshot( + Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)), + Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1))); + sessions.HoldNextReconcile(); + await sessions.ReconcileParked.WaitAsync(WaitTimeout); + + sessions.SetSnapshot(Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1))); + sessions.EmitEvent(Transition(1, AlarmA, AlarmTransitionKind.Clear, Ts(3), Ts(0))); + await feed.WaitForTransitionAsync(AlarmA, AlarmTransitionKind.Clear, WaitTimeout); + + sessions.ReleaseReconcile(); + await feed.WaitForTransitionAsync(AlarmB, AlarmTransitionKind.Raise, WaitTimeout); + + Assert.Equal([AlarmTransitionKind.Clear], feed.TransitionsFor(AlarmA)); + Assert.DoesNotContain(monitor.CurrentAlarms, a => a.AlarmFullReference == AlarmA); + + await feed.StopAsync(); + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// + /// SEC-009: an alarm that cleared and re-raised between passes, with both live transitions + /// missed, is in the same state with a new original raise time. That is a new instance and + /// must be repaired with a Raise. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task SameStateReRaiseBetweenPasses_BroadcastsRaise() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0))); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, reconcileInterval: TimeSpan.FromMilliseconds(200)); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.CurrentAlarms.Any(a => a.AlarmFullReference == AlarmA), WaitTimeout); + FeedRecorder feed = FeedRecorder.Start(monitor); + await feed.SnapshotComplete.WaitAsync(WaitTimeout); + + sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(60), Ts(60))); + await feed.WaitForTransitionAsync(AlarmA, AlarmTransitionKind.Raise, WaitTimeout); + + AlarmFeedMessage raise = feed.Live.First(m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.Transition); + Assert.Equal(Ts(60), raise.Transition.OriginalRaiseTimestamp); + + await feed.StopAsync(); + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// + /// SEC-009: a worker that rejects the initial QueryActiveAlarms must not leave a + /// healthy-looking monitor with an empty cache; the lifecycle fails and is retried. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task InitialReconcileRejected_FailsTheLifecycle() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + sessions.SetReconcileCode(ProtocolStatusCode.MxaccessFailure); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => sessions.Opens >= 2, WaitTimeout); + + Assert.NotEqual(GatewayAlarmMonitorState.Monitoring, monitor.State); + Assert.Contains("QueryActiveAlarms", monitor.LastError ?? string.Empty, StringComparison.Ordinal); + + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// SEC-009: a rejected periodic reconcile is surfaced on LastError and keeps the cache. + /// A task that represents the asynchronous operation. + [Fact] + public async Task PeriodicReconcileRejected_IsSurfacedAndKeepsTheCache() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0))); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, reconcileInterval: TimeSpan.FromMilliseconds(200)); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.CurrentAlarms.Count == 1, WaitTimeout); + + sessions.SetReconcileCode(ProtocolStatusCode.MxaccessFailure); + await WaitUntilAsync( + () => (monitor.LastError ?? string.Empty).Contains("Alarm reconcile failed", StringComparison.Ordinal), + WaitTimeout); + Assert.Equal(GatewayAlarmMonitorState.Monitoring, monitor.State); + Assert.Single(monitor.CurrentAlarms); + + sessions.SetReconcileCode(ProtocolStatusCode.Ok); + await WaitUntilAsync(() => monitor.LastError is null, WaitTimeout); + + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// + /// SEC-005: an alarm that returned to normal while the monitor was restarting gets its Clear. + /// The first reconcile of the new lifecycle diffs against the retained previous generation + /// — what the subscriber still holds — instead of an emptied cache. An alarm still active in + /// the same state is not re-raised. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Restart_BroadcastsClearForAlarmsGoneDuringTheGap() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + sessions.SetSnapshot( + Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)), + Snapshot(AlarmB, AlarmConditionState.Active, Ts(1), Ts(1))); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.CurrentAlarms.Count == 2, WaitTimeout); + FeedRecorder feed = FeedRecorder.Start(monitor); + await feed.SnapshotComplete.WaitAsync(WaitTimeout); + + sessions.SetSnapshot(Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0))); + sessions.EndCurrentSession(); + + await feed.WaitForTransitionAsync(AlarmB, AlarmTransitionKind.Clear, WaitTimeout); + await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring && sessions.Opens == 2, WaitTimeout); + + Assert.Empty(feed.TransitionsFor(AlarmA)); + Assert.Equal(AlarmA, Assert.Single(monitor.CurrentAlarms).AlarmFullReference); + + await feed.StopAsync(); + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// + /// SEC-005: a subscriber that last saw a Subtag/degraded status is told the restarted + /// lifecycle's baseline (alarm manager) — Auto mode raises no mode-change event at start. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Restart_BroadcastsTheRebaselinedProviderStatus() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout); + FeedRecorder feed = FeedRecorder.Start(monitor); + await feed.SnapshotComplete.WaitAsync(WaitTimeout); + + sessions.EmitEvent(ModeChange(AlarmProviderMode.Subtag, "alarmmgr failed")); + await WaitUntilAsync( + () => feed.Live.Any(m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.ProviderStatus + && m.ProviderStatus.Mode == AlarmProviderMode.Subtag), + WaitTimeout); + + sessions.EndCurrentSession(); + + await WaitUntilAsync( + () => feed.Live + .Where(m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.ProviderStatus) + .SkipWhile(m => m.ProviderStatus.Mode != AlarmProviderMode.Subtag) + .Any(m => m.ProviderStatus.Mode == AlarmProviderMode.Alarmmgr && !m.ProviderStatus.Degraded), + WaitTimeout); + + await feed.StopAsync(); + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// + /// SEC-005: during the restart gap the retired set is hidden from CurrentAlarms and a + /// subscriber attaching then gets an empty snapshot; the first reconcile of the new + /// lifecycle sends that subscriber every active alarm (acknowledged ones as Raise then + /// Acknowledge). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task SubscriberAttachedDuringRestartGap_ReceivesTheWholeSet() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + sessions.SetSnapshot( + Snapshot(AlarmA, AlarmConditionState.Active, Ts(0), Ts(0)), + Snapshot(AlarmB, AlarmConditionState.ActiveAcked, Ts(1), Ts(2))); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, restartBackoff: TimeSpan.FromSeconds(2)); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.CurrentAlarms.Count == 2, WaitTimeout); + + sessions.EndCurrentSession(); + await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Faulted, WaitTimeout); + + Assert.Empty(monitor.CurrentAlarms); + FeedRecorder feed = FeedRecorder.Start(monitor); + await feed.SnapshotComplete.WaitAsync(WaitTimeout); + Assert.DoesNotContain(feed.Preamble, m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.ActiveAlarm); + + await feed.WaitForTransitionAsync(AlarmB, AlarmTransitionKind.Acknowledge, WaitTimeout); + Assert.Equal([AlarmTransitionKind.Raise], feed.TransitionsFor(AlarmA)); + Assert.Equal([AlarmTransitionKind.Raise, AlarmTransitionKind.Acknowledge], feed.TransitionsFor(AlarmB)); + Assert.Equal(2, monitor.CurrentAlarms.Count); + + await feed.StopAsync(); + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// + /// SEC-008: the watch-list refresh runs on its own loop, so a Galaxy SQL query that hangs + /// does not hold up the reconcile cadence. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task HungWatchListRefresh_DoesNotDelayReconcile() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + HangingAfterFirstResolver resolver = new(); + using GatewayAlarmMonitor monitor = CreateMonitor( + sessions, + metrics, + reconcileInterval: TimeSpan.FromMilliseconds(200), + resolver: resolver); + + using CancellationTokenSource cts = new(); + await monitor.StartAsync(cts.Token); + await WaitUntilAsync(() => monitor.State == GatewayAlarmMonitorState.Monitoring, WaitTimeout); + await WaitUntilAsync(() => resolver.Calls >= 2, WaitTimeout); + + int reconcilesWhileHung = sessions.Reconciles; + await WaitUntilAsync(() => sessions.Reconciles >= reconcilesWhileHung + 3, WaitTimeout); + Assert.Equal(2, resolver.Calls); + + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + /// SEC-010: the restart backoff doubles per consecutive failure and is capped at five minutes. + [Fact] + public void RestartBackoff_IsExponentialAndCapped() + { + TimeSpan initial = TimeSpan.FromSeconds(5); + + Assert.Equal(TimeSpan.FromSeconds(5), GatewayAlarmMonitor.ComputeRestartBackoff(initial, 1)); + Assert.Equal(TimeSpan.FromSeconds(10), GatewayAlarmMonitor.ComputeRestartBackoff(initial, 2)); + Assert.Equal(TimeSpan.FromSeconds(40), GatewayAlarmMonitor.ComputeRestartBackoff(initial, 4)); + Assert.Equal(TimeSpan.FromMinutes(5), GatewayAlarmMonitor.ComputeRestartBackoff(initial, 8)); + Assert.Equal(TimeSpan.FromMinutes(5), GatewayAlarmMonitor.ComputeRestartBackoff(initial, int.MaxValue)); + } + + /// + /// SEC-010: a lifecycle that keeps failing (here a rejected initial reconcile) opens worker + /// sessions at a growing interval rather than at a fixed cadence. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task PermanentLifecycleFailure_BacksOffBetweenAttempts() + { + using GatewayMetrics metrics = new(); + FakeSessionManager sessions = new(); + sessions.SetReconcileCode(ProtocolStatusCode.MxaccessFailure); + using GatewayAlarmMonitor monitor = CreateMonitor(sessions, metrics, restartBackoff: TimeSpan.FromMilliseconds(200)); + + using CancellationTokenSource cts = new(); + System.Diagnostics.Stopwatch clock = System.Diagnostics.Stopwatch.StartNew(); + await monitor.StartAsync(cts.Token); + + // Backoffs 200, 400, 800 ms: the fourth open cannot come before ~1.4 s after the first. + await WaitUntilAsync(() => sessions.Opens >= 1, WaitTimeout); + TimeSpan firstOpen = clock.Elapsed; + await WaitUntilAsync(() => sessions.Opens >= 4, WaitTimeout); + Assert.True(clock.Elapsed - firstOpen >= TimeSpan.FromMilliseconds(1_300), $"Opens came too fast: {clock.Elapsed - firstOpen}"); + + await cts.CancelAsync(); + await monitor.StopAsync(CancellationToken.None); + } + + internal static GatewayAlarmMonitor CreateMonitor( + FakeSessionManager sessions, + GatewayMetrics metrics, + TimeSpan? reconcileInterval = null, + TimeSpan? restartBackoff = null, + IAlarmWatchListResolver? resolver = null) + { + AlarmsOptions options = new() + { + Enabled = true, + SubscriptionExpression = @"\\NODE\Galaxy!Area", + }; + return new GatewayAlarmMonitor( + sessions, + resolver ?? new EmptyWatchListResolver(), + metrics, + Microsoft.Extensions.Options.Options.Create(new GatewayOptions { Alarms = options }), + NullLogger.Instance) + { + ReconcileInterval = reconcileInterval ?? TimeSpan.FromMinutes(10), + InitialRestartBackoff = restartBackoff ?? TimeSpan.FromMilliseconds(50), + }; + } + + internal static Timestamp Ts(int seconds) => + Timestamp.FromDateTimeOffset(new DateTimeOffset(2026, 12, 3, 9, 0, 0, TimeSpan.Zero).AddSeconds(seconds)); + + internal static MxEvent Transition( + ulong sequence, + string reference, + AlarmTransitionKind kind, + Timestamp transitionTimestamp, + Timestamp originalRaise) => new() + { + Family = MxEventFamily.OnAlarmTransition, + WorkerSequence = sequence, + OnAlarmTransition = new OnAlarmTransitionEvent + { + AlarmFullReference = reference, + SourceObjectReference = "Tank", + AlarmTypeName = "AnalogLimitAlarm.Hi", + TransitionKind = kind, + Severity = 500, + SourceProvider = AlarmProviderMode.Alarmmgr, + TransitionTimestamp = transitionTimestamp, + OriginalRaiseTimestamp = originalRaise, + }, + }; + + internal static MxEvent ModeChange(AlarmProviderMode mode, string reason) => new() + { + Family = MxEventFamily.OnAlarmProviderModeChanged, + OnAlarmProviderModeChanged = new OnAlarmProviderModeChangedEvent + { + Mode = mode, + Reason = reason, + At = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow), + }, + }; + + internal static ActiveAlarmSnapshot Snapshot( + string reference, + AlarmConditionState state, + Timestamp originalRaise, + Timestamp lastTransition) => new() + { + AlarmFullReference = reference, + SourceObjectReference = "Tank", + AlarmTypeName = "AnalogLimitAlarm.Hi", + CurrentState = state, + Severity = 500, + SourceProvider = AlarmProviderMode.Alarmmgr, + OriginalRaiseTimestamp = originalRaise, + LastTransitionTimestamp = lastTransition, + }; + + internal static Task WaitUntilAsync(Func condition, TimeSpan timeout) + => Eventually.WaitUntilAsync(condition, timeout); + + /// Records everything one feed subscription receives after its snapshot preamble. + internal sealed class FeedRecorder + { + private readonly List _preamble = []; + private readonly List _live = []; + private readonly TaskCompletionSource _snapshotComplete = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly CancellationTokenSource _cts = new(); + private Task _reader = Task.CompletedTask; + + /// Gets a task that completes when the subscription's snapshot sentinel arrives. + public Task SnapshotComplete => _snapshotComplete.Task; + + /// Gets a copy of the frames received before (and including) the snapshot sentinel. + public AlarmFeedMessage[] Preamble + { + get { lock (_preamble) { return [.. _preamble]; } } + } + + /// Gets a copy of the frames received after the snapshot sentinel. + public AlarmFeedMessage[] Live + { + get { lock (_live) { return [.. _live]; } } + } + + /// Starts a feed subscription on the monitor. + /// The monitor to subscribe to. + /// The recorder. + public static FeedRecorder Start(GatewayAlarmMonitor monitor) + { + FeedRecorder recorder = new(); + recorder._reader = Task.Run(async () => + { + try + { + await foreach (AlarmFeedMessage message in monitor.StreamAsync(null, recorder._cts.Token)) + { + if (recorder._snapshotComplete.Task.IsCompleted) + { + lock (recorder._live) + { + recorder._live.Add(message); + } + } + else + { + lock (recorder._preamble) + { + recorder._preamble.Add(message); + } + + if (message.PayloadCase == AlarmFeedMessage.PayloadOneofCase.SnapshotComplete) + { + recorder._snapshotComplete.TrySetResult(); + } + } + } + } + catch (OperationCanceledException) + { + // Expected when the test stops the recorder. + } + }); + return recorder; + } + + /// Gets the live transitions for one alarm, in arrival order. + /// The alarm reference. + /// The transition kinds. + public AlarmTransitionKind[] TransitionsFor(string reference) => Live + .Where(m => m.PayloadCase == AlarmFeedMessage.PayloadOneofCase.Transition + && m.Transition.AlarmFullReference == reference) + .Select(m => m.Transition.TransitionKind) + .ToArray(); + + /// Waits for a live transition of the given kind for one alarm. + /// The alarm reference. + /// The transition kind. + /// The maximum time to wait. + /// A task that represents the asynchronous operation. + public Task WaitForTransitionAsync(string reference, AlarmTransitionKind kind, TimeSpan timeout) + => WaitUntilAsync(() => TransitionsFor(reference).Contains(kind), timeout); + + /// Stops the subscription and waits for the reader to finish. + /// A task that represents the asynchronous operation. + public async Task StopAsync() + { + await _cts.CancelAsync(); + await _reader; + _cts.Dispose(); + } + } + + /// + /// whose first call (the subscribe) resolves and + /// every later call hangs until cancelled — a Galaxy SQL server that stopped answering. + /// + private sealed class HangingAfterFirstResolver : IAlarmWatchListResolver + { + private int _calls; + + /// Gets the number of resolutions started. + public int Calls => Volatile.Read(ref _calls); + + /// + public async Task ResolveAsync( + AlarmsOptions options, + CancellationToken cancellationToken = default) + { + if (Interlocked.Increment(ref _calls) > 1) + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken).ConfigureAwait(false); + } + + return new AlarmWatchListResolution( + [], + DiscoveryAttempted: true, + DiscoveryFailed: false, + DiscoveryFailureMessage: null); + } + } + + /// that resolves an empty watch-list. + private sealed class EmptyWatchListResolver : IAlarmWatchListResolver + { + /// + public Task ResolveAsync( + AlarmsOptions options, + CancellationToken cancellationToken = default) => + Task.FromResult(new AlarmWatchListResolution( + [], + DiscoveryAttempted: false, + DiscoveryFailed: false, + DiscoveryFailureMessage: null)); + } + + /// + /// that opens a genuinely Ready session with a fresh worker + /// event stream per open, answers QueryActiveAlarms from a settable snapshot (or a + /// settable non-OK code), and can park the next reconcile reply until released. + /// + internal sealed class FakeSessionManager : ISessionManager + { + private readonly object _sync = new(); + private Channel _events = Channel.CreateUnbounded(); + private ActiveAlarmSnapshot[] _snapshot = []; + private ProtocolStatusCode _reconcileCode = ProtocolStatusCode.Ok; + private TaskCompletionSource? _reconcileGate; + private TaskCompletionSource _reconcileParked = new(TaskCreationOptions.RunContinuationsAsynchronously); + private int _opens; + private int _reconciles; + + /// Gets the number of sessions opened so far. + public int Opens => Volatile.Read(ref _opens); + + /// Gets the number of QueryActiveAlarms commands received so far. + public int Reconciles => Volatile.Read(ref _reconciles); + + /// Sets the snapshot every reconcile returns. + /// The snapshots. + public void SetSnapshot(params ActiveAlarmSnapshot[] snapshots) + { + lock (_sync) + { + _snapshot = snapshots; + } + } + + /// Sets the protocol status every reconcile replies with. + /// The status code. + public void SetReconcileCode(ProtocolStatusCode code) + { + lock (_sync) + { + _reconcileCode = code; + } + } + + /// + /// Parks the next reconcile after it captures its reply snapshot, until + /// . completes when it parks. + /// + public void HoldNextReconcile() + { + lock (_sync) + { + _reconcileGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _reconcileParked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + } + } + + /// Gets a task that completes when a held reconcile has parked. + public Task ReconcileParked + { + get { lock (_sync) { return _reconcileParked.Task; } } + } + + /// Releases a reconcile parked by . + public void ReleaseReconcile() + { + lock (_sync) + { + _reconcileGate?.TrySetResult(); + _reconcileGate = null; + } + } + + /// Pushes a worker event into the current session's distributor pump. + /// The event. + public void EmitEvent(MxEvent mxEvent) + { + lock (_sync) + { + _events.Writer.TryWrite(new WorkerEvent { Event = mxEvent }); + } + } + + /// Ends the current session's worker event stream, as a worker exit would. + public void EndCurrentSession() + { + lock (_sync) + { + _events.Writer.TryComplete(); + } + } + + /// + public Task OpenSessionAsync( + SessionOpenRequest request, + string? clientIdentity, + string? ownerKeyId, + CancellationToken cancellationToken) + { + Channel events = Channel.CreateUnbounded(); + lock (_sync) + { + _events = events; + } + + Interlocked.Increment(ref _opens); + GatewaySession session = new( + Guid.NewGuid().ToString("N"), + "Galaxy", + "pipe-test", + "nonce-test", + clientIdentity, + null, + null, + TimeSpan.FromSeconds(30), + TimeSpan.FromSeconds(30), + TimeSpan.FromSeconds(30), + DateTimeOffset.UtcNow); + session.AttachWorkerClient(new ChannelWorkerClient(session.SessionId, events.Reader)); + session.MarkReady(); + return Task.FromResult(session); + } + + /// + public async Task InvokeAsync( + string sessionId, + WorkerCommand command, + CancellationToken cancellationToken) + { + MxCommandReply reply = new() + { + ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, + }; + + if (command.Command?.Kind == MxCommandKind.QueryActiveAlarms) + { + Interlocked.Increment(ref _reconciles); + QueryActiveAlarmsReplyPayload payload = new(); + Task? gate; + lock (_sync) + { + reply.ProtocolStatus.Code = _reconcileCode; + payload.Snapshots.AddRange(_snapshot.Select(snapshot => snapshot.Clone())); + gate = _reconcileGate?.Task; + if (gate is not null) + { + _reconcileParked.TrySetResult(); + } + } + + if (gate is not null) + { + await gate.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + if (reply.ProtocolStatus.Code == ProtocolStatusCode.Ok) + { + reply.QueryActiveAlarms = payload; + } + } + + return new WorkerCommandReply { Reply = reply }; + } + + /// + public bool TryGetSession(string sessionId, [MaybeNullWhen(false)] out GatewaySession session) + { + session = null; + return false; + } + + /// + public Task CloseSessionAsync(string sessionId, CancellationToken cancellationToken) + { + EndCurrentSession(); + return Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false)); + } + + /// + public Task KillWorkerAsync(string sessionId, string reason, CancellationToken cancellationToken) => + Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false)); + + /// + public Task CloseExpiredLeasesAsync(DateTimeOffset now, CancellationToken cancellationToken) => + Task.FromResult(0); + + /// + public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask; + } +}