fix(galaxy): an ack does not supersede a re-read entry; a stream reopen discards the re-read (#925 review r1)

- Only full-state live messages (snapshot entry, Raise, Retrigger, Clear) supersede a
  QueryActiveAlarms entry; an Acknowledge merges (Active => ActiveAcked) instead of
  skipping it and then signalling a cold condition known.
- Stream epoch bumped before StreamOpened; a changed epoch at replay drops the replay
  and the signal (an alarm cleared in the gap is absent, never touched); no re-read
  before the current stream's sentinel.
- Lows: dispose race returns false; teardown token on the RPC and the retry wait;
  an unexpected failure keeps a queued follow-up.
This commit is contained in:
Joseph Doherty
2026-11-28 09:34:24 -05:00
parent b4c27bd5b8
commit 14ca1b7168
6 changed files with 181 additions and 30 deletions
@@ -175,6 +175,8 @@ public sealed class GalaxyDriver
private bool _streamSnapshotDelivered;
// lmxopcua#925: the active-alarm re-read coalescer — 0 idle, 1 running, 2 running with another run requested.
private int _alarmRefreshState;
// Cancelled (and replaced) by every runtime teardown, so an in-flight re-read or its retry wait stops quietly.
private CancellationTokenSource _alarmRefreshCts = new();
// Production runtime owned by InitializeAsync (BuildProductionRuntimeAsync). The
// driver builds these when it opens a real gw session; tests bypass them by
@@ -1101,6 +1103,9 @@ public sealed class GalaxyDriver
}
// lmxopcua#925: the next feed (or the re-wired injected one) starts with no delivered stream snapshot.
lock (_alarmHandlersLock) _streamSnapshotDelivered = false;
// A re-read in flight (or waiting to retry) belongs to the torn-down runtime. Not disposed: its token may
// still be observed by the unwinding re-read.
Interlocked.Exchange(ref _alarmRefreshCts, new CancellationTokenSource()).Cancel();
if (releaseFeed)
{
try { await alarmFeed!.DisposeAsync().ConfigureAwait(false); }
@@ -3140,24 +3145,24 @@ public sealed class GalaxyDriver
private async Task RunAlarmSnapshotRefreshesAsync()
{
try
while (true)
{
while (true)
try
{
await RefreshAlarmSnapshotOnceAsync().ConfigureAwait(false);
// 1 → 0: nothing was requested meanwhile. 2: run once more for the requests that arrived.
if (Interlocked.CompareExchange(ref _alarmRefreshState, 0, 1) == 1) return;
Volatile.Write(ref _alarmRefreshState, 1);
await RefreshAlarmSnapshotOnceAsync(Volatile.Read(ref _alarmRefreshCts).Token).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Volatile.Write(ref _alarmRefreshState, 0);
_logger.LogWarning(ex, "GalaxyDriver active-alarm re-read loop failed unexpectedly");
catch (Exception ex)
{
// Logged, then the coalescing step below still runs: a follow-up requested meanwhile is not lost.
_logger.LogWarning(ex, "GalaxyDriver active-alarm re-read failed unexpectedly");
}
// 1 → 0: nothing was requested meanwhile. 2: run once more for the requests that arrived.
if (Interlocked.CompareExchange(ref _alarmRefreshState, 0, 1) == 1) return;
Volatile.Write(ref _alarmRefreshState, 1);
}
}
private async Task RefreshAlarmSnapshotOnceAsync()
private async Task RefreshAlarmSnapshotOnceAsync(CancellationToken teardown)
{
GalaxyAlarmSubscriptionHandle? under;
IGalaxyAlarmFeed? feed;
@@ -3167,14 +3172,15 @@ public sealed class GalaxyDriver
for (var attempt = 1; ; attempt++)
{
if (_disposed) return;
if (_disposed || teardown.IsCancellationRequested) return;
try
{
using var timeout = new CancellationTokenSource(AlarmSnapshotRefreshTimeout);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(teardown);
timeout.CancelAfter(AlarmSnapshotRefreshTimeout);
if (!await feed.RefreshSnapshotAsync(timeout.Token).ConfigureAwait(false)) return;
break;
}
catch (Exception ex) when (ex is ObjectDisposedException || _disposed)
catch (Exception ex) when (ex is ObjectDisposedException || _disposed || teardown.IsCancellationRequested)
{
return; // the feed or the driver is being torn down
}
@@ -3187,7 +3193,8 @@ public sealed class GalaxyDriver
{
_logger.LogWarning("GalaxyDriver active-alarm re-read attempt {Attempt} failed ({Reason}); retrying in {Delay}",
attempt, ex.Message, AlarmSnapshotRefreshRetryDelay);
await Task.Delay(AlarmSnapshotRefreshRetryDelay).ConfigureAwait(false);
try { await Task.Delay(AlarmSnapshotRefreshRetryDelay, teardown).ConfigureAwait(false); }
catch (OperationCanceledException) { return; } // torn down while waiting to retry
}
catch (Exception ex)
{
@@ -80,9 +80,17 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
// lmxopcua#925: serialises live dispatch with a re-read's replay, so "did the live stream already deliver a newer
// message for this alarm" and the replay of the re-read entry are one atomic step.
private readonly Lock _dispatchLock = new();
// The alarms the live stream delivered any message for since the in-flight re-read was issued (null when none is
// in flight). Guarded by _dispatchLock.
private HashSet<string>? _touchedDuringRefresh;
// The alarms the live stream delivered a message for since the in-flight re-read was issued (null when none is in
// flight), mapped to whether any of them carried the FULL state (snapshot entry, Raise, Retrigger, Clear) — true —
// or only the ack dimension (Acknowledge) — false. Guarded by _dispatchLock.
private Dictionary<string, bool>? _touchedDuringRefresh;
// Review r1 #2: bumped (under _dispatchLock) each time a stream is (re)opened, before any of its messages. A
// re-read replays only if no stream opened since it was issued: an alarm that cleared in a reopen gap is merely
// ABSENT from the new snapshot, so the touched map cannot catch the re-read's stale entry for it.
private long _streamEpoch;
// Whether the current stream has delivered its snapshot_complete sentinel. Guarded by _dispatchLock. A re-read is
// pointless (and could signal mid-snapshot) while it has not: that stream's own sentinel covers the subscription.
private bool _streamSnapshotComplete;
// One re-read at a time (a second one waits for the first).
private readonly SemaphoreSlim _refreshGate = new(1, 1);
private readonly ILogger _logger;
@@ -162,6 +170,12 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
AlarmFilterPrefix = _alarmFilterPrefix,
};
lock (_dispatchLock)
{
_streamEpoch++;
_streamSnapshotComplete = false;
}
// A1 review round 2 F4: before any message of this stream, on this (the dispatch) thread.
try { StreamOpened?.Invoke(this, EventArgs.Empty); }
catch (Exception ex) { _logger.LogWarning(ex, "Galaxy alarm feed StreamOpened handler threw — continuing."); }
@@ -202,14 +216,23 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
public async Task<bool> RefreshSnapshotAsync(CancellationToken cancellationToken)
{
if (_queryFactory is null || _disposed) return false;
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token);
CancellationTokenSource linked;
try { linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _cts.Token); }
catch (ObjectDisposedException) { return false; } // disposed concurrently: not an RPC failure
using var _ = linked;
await _refreshGate.WaitAsync(linked.Token).ConfigureAwait(false);
try
{
// Track BEFORE the query is issued: any live message dispatched from here on may be newer than the
// query's view of that alarm.
var touched = new HashSet<string>(StringComparer.Ordinal);
lock (_dispatchLock) _touchedDuringRefresh = touched;
var touched = new Dictionary<string, bool>(StringComparer.Ordinal);
long epoch;
lock (_dispatchLock)
{
if (!_streamSnapshotComplete) return false; // the current stream's own sentinel covers it
epoch = _streamEpoch;
_touchedDuringRefresh = touched;
}
try
{
var entries = new List<ActiveAlarmSnapshot>();
@@ -228,10 +251,31 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
lock (_dispatchLock)
{
linked.Token.ThrowIfCancellationRequested();
if (_streamEpoch != epoch)
{
// Review r1 #2: a stream (re)opened meanwhile. Its snapshot (and sentinel) is the newer
// statement of every alarm; replaying this older view could resurrect one that cleared in the gap.
_logger.LogDebug("Galaxy alarm feed re-read discarded: the stream reopened while it was in flight.");
return false;
}
foreach (var entry in entries)
{
if (touched.Contains(entry.AlarmFullReference)) { superseded++; continue; }
DispatchSnapshotEntry(entry);
if (!touched.TryGetValue(entry.AlarmFullReference, out var fullState))
{
DispatchSnapshotEntry(entry);
}
else if (fullState)
{
superseded++; // a newer full statement of this alarm already reached the host
}
else
{
// Review r1 #1: only acknowledged since the query read it — the entry's ACTIVE state still
// stands, merged with the ack (Active ⇒ ActiveAcked; ActiveAcked / Inactive unchanged).
DispatchSnapshotEntry(entry.CurrentState == AlarmConditionState.Active
? MergeAcknowledged(entry)
: entry);
}
}
}
@@ -253,6 +297,20 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
}
}
private static ActiveAlarmSnapshot MergeAcknowledged(ActiveAlarmSnapshot entry)
{
var merged = entry.Clone();
merged.CurrentState = AlarmConditionState.ActiveAcked;
return merged;
}
/// <summary>Under <see cref="_dispatchLock"/>: note a live message for an alarm while a re-read is in flight.</summary>
private void NoteTouched(string reference, bool fullState)
{
if (_touchedDuringRefresh is not { } touched) return;
touched[reference] = fullState || (touched.TryGetValue(reference, out var prior) && prior);
}
private void Dispatch(AlarmFeedMessage message)
{
lock (_dispatchLock)
@@ -266,16 +324,19 @@ internal sealed class GatewayGalaxyAlarmFeed : IGalaxyAlarmFeed
switch (message.PayloadCase)
{
case AlarmFeedMessage.PayloadOneofCase.ActiveAlarm:
_touchedDuringRefresh?.Add(message.ActiveAlarm.AlarmFullReference);
NoteTouched(message.ActiveAlarm.AlarmFullReference, fullState: true);
DispatchSnapshotEntry(message.ActiveAlarm);
break;
case AlarmFeedMessage.PayloadOneofCase.Transition:
_touchedDuringRefresh?.Add(message.Transition.AlarmFullReference);
// An Acknowledge carries only the ack dimension; every other kind restates the active state too.
NoteTouched(message.Transition.AlarmFullReference,
fullState: message.Transition.TransitionKind != AlarmTransitionKind.Acknowledge);
DispatchTransition(message.Transition);
break;
case AlarmFeedMessage.PayloadOneofCase.SnapshotComplete:
_logger.LogDebug("Galaxy alarm feed active-alarm snapshot complete.");
_initialSnapshot.TrySetResult();
_streamSnapshotComplete = true; // before the signal, whose handler may request a re-read
// grpc-data A1: the ordered per-sentinel signal — on THIS thread, after the snapshot entries above
// were raised; every reopened stream's sentinel raises it again.
RaiseSnapshotDelivered();
@@ -64,9 +64,12 @@ internal interface IGalaxyAlarmFeed : IAsyncDisposable
/// lmxopcua#925: re-read the gateway's current active-alarm set (<c>QueryActiveAlarms</c>, the same monitor
/// cache the stream's opening snapshot comes from) and raise each entry on <see cref="OnAlarmTransition"/> as a
/// restatement, exactly like a snapshot entry, while the live stream stays open. An entry is skipped when the
/// live stream delivered any message for the same alarm after the query was issued: that message is at least
/// as new as the query's view, and replaying the older view after it would be a phantom transition.
/// Completes true once every entry was raised; false when the feed has no query. Throws on an RPC failure.
/// live stream delivered a full-state message (snapshot entry, Raise, Retrigger, Clear) for the same alarm after
/// the query was issued: that message is at least as new as the query's view, and replaying the older view after
/// it would be a phantom transition. An Acknowledge alone is merged instead (an Active entry replays as
/// ActiveAcked). Completes true once every entry was raised; false — nothing replayed — when the feed has no
/// query, is disposed, the current stream has not delivered its sentinel yet, or a stream (re)opened while the
/// query was in flight (that stream's own sentinel then covers the subscription). Throws on an RPC failure.
/// Raises no signal itself — the caller decides which subscription the re-read establishes.
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>