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
+5 -1
View File
@@ -208,7 +208,11 @@ Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `G
**Establishing a changed alarm subscription without a stream reopen (#925).** The driver turns each `snapshot_complete` sentinel into `IAlarmInitialStateSignal.InitialAlarmStateDelivered` (grpc-data A1) for the live alarm subscription, but a sentinel only comes when `StreamAlarms` opens. A subscription that becomes live while the stream is already past its sentinel (a re-subscribe with a changed alarm set, a reconnect that kept the session-less feed, or a change during the snapshot phase, which the sentinel cannot vouch for) would otherwise stay "unknown" (Uncertain on gRPC-data consumers) until the stream happened to reopen. The driver now re-reads the active-alarm set with the gateway's `QueryActiveAlarms` RPC instead. That RPC serves the same monitor cache as the stream's opening snapshot and needs the same `EventsRead` scope.
- **How a re-read is applied.** The entries are replayed exactly like snapshot entries: as restatements, with the same kind mapping. The signal follows the replay, and only if the subscription the re-read was made under is still the live one.
- **Why there are no phantom transitions.** The stream stays open. An entry is skipped when the live stream delivered any message for the same alarm after the query was issued, because that message is at least as new as the query's view of it (counter `galaxy.alarm_feed.snapshot_refresh.superseded`). Live dispatch and the replay are serialised, so this check and the replay happen as one step.
- **Why there are no phantom transitions.** The stream stays open. Live dispatch and the replay are serialised, so each check below and its replay happen as one step.
- An entry is skipped when the live stream delivered a full-state message for the same alarm after the query was issued (a snapshot entry, `Raise`, `Retrigger` or `Clear`), because that message is at least as new as the query's view of it (counter `galaxy.alarm_feed.snapshot_refresh.superseded`).
- An `Acknowledge` carries only the ack, so it is merged, not treated as superseding: an `Active` entry replays as `ActiveAcked`. Skipping it would have marked a cold condition known while it still showed inactive.
- If a stream (re)opened while the query was in flight, the whole re-read is discarded and does not signal. An alarm that cleared in the reopen gap is simply absent from the new snapshot, so the query's entry for it would be a phantom `Active`. The reopened stream's own sentinel covers the subscription.
- A re-read is not started while the current stream has not yet delivered its sentinel.
- **Bounded.** One re-read runs at a time. Requests that arrive while it runs collapse into one follow-up run. A failure is retried 3 times, 5 s apart. A gateway without the RPC (`Unimplemented`) is not retried. A re-read that fails never signals: the conditions stay unknown, F5 diagnoses them, and the next stream sentinel signals as before.
- **Residuals.** The query can be *ahead* of the stream: it can show a raise whose live `Raise` is still queued. That `Raise` then lands on an already-active condition, and the host treats it as the re-statement it is. Like every snapshot replay, the query lists active alarms only. An alarm that cleared while no subscription was live, so that its live `Clear` was dropped, is not cleared by it. This is a pre-existing limit of every snapshot replay.
- **In practice.** A deploy that changes a Galaxy driver's alarm tags also changes its config, so the driver respawns and its fresh feed's first sentinel covers the new set (#665: there is no in-place path). The re-read is the safety net for the paths where the feed outlives the subscription.
@@ -224,6 +224,17 @@ Heidenhain legs are **blocked**: Galaxy needs the VPN and mxaccessgw, and Heiden
(5 red), no supersede check, no handle check at the signal, Unimplemented retried, no re-read at a mismatched sentinel,
no coalescing. The F5 re-arm for deploy-added refs was already in place (`RearmConditionSignalsAfterReindex`, review
round 1). **Not live-gated:** no Galaxy or mxaccessgw is reachable (wonder-box hold).
**#925 review round 1:**
- *Ack-only supersede:* a live `Acknowledge` no longer supersedes an entry. It is merged instead (Active ⇒ ActiveAcked).
Test `An_acknowledge_during_the_reread_merges_into_its_entry_instead_of_superseding_it`. Red on the original code, and
on either mutation: ack counted as full state, or no merge.
- *Reopen during the query:* a stream epoch is bumped before `StreamOpened`. A changed epoch at replay time drops the
re-read and its signal. No re-read starts before the current stream's sentinel. Test
`A_stream_reopen_during_the_reread_drops_its_replay_and_its_signal`. Red on the original code (phantom Tank2
Retrigger plus a second signal), and with the epoch check removed.
- *Lows:* a dispose race returns false instead of throwing `ObjectDisposedException`. The retry wait and the RPC observe
a teardown token, which every runtime teardown cancels. An unexpected failure no longer discards a queued follow-up.
- Galaxy.Tests: 645 passed, 13 skipped. The 13 alarm-signal tests passed 15 runs out of 15.
- **OpcUaClient: no signal suppression on an SDK-reported sequence gap during a refresh.** Plan G2 says such a `RefreshEnd`
"does not signal".
- The SDK 2.0.1 surface the driver sees (the per-item `Notification` callback) exposes no per-message gap or republish
@@ -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>
@@ -89,6 +89,71 @@ public sealed class GalaxyAlarmSnapshotRefreshTests
]);
}
/// <summary>
/// Review r1 #1: an Acknowledge carries only the ack dimension, so it does not supersede the re-read's view of
/// the alarm's ACTIVE state. Tank2 is Active+unacked when the query reads it; an operator acks it before the
/// replay ⇒ the replay must project Active+acked (not skip it and then signal a cold, inactive condition known).
/// </summary>
[Fact]
public async Task An_acknowledge_during_the_reread_merges_into_its_entry_instead_of_superseding_it()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var trace = Record(driver);
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
await driver.UnsubscribeAlarmsAsync(h1, Ct);
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var q = await rig.NextQueryAsync();
await s.WriteAsync(Transition(Tank2, AlarmTransitionKind.Acknowledge), Ct);
await TestWait.UntilAsync(() => Count(trace) == 2, "the live acknowledge", () => Dump(trace));
q.Complete(Entry(Tank2, AlarmConditionState.Active));
await TestWait.UntilAsync(() => Count(trace) == 4, "the merged entry then the signal", () => Dump(trace));
Snapshot(trace).ShouldBe([
"signal:" + Tank1,
"event:" + Tank2 + ":Acknowledge:live",
"event:" + Tank2 + ":ActiveAcknowledged:restatement",
$"signal:{Tank1},{Tank2}",
]);
}
/// <summary>
/// Review r1 #2: the stream reopens while the query is in flight. An alarm that cleared in the gap is simply
/// absent from the reopened stream's snapshot (never "touched"), so the query's stale Active entry must NOT be
/// replayed, and the re-read must not signal — the reopened stream's own sentinel covers the subscription.
/// </summary>
[Fact]
public async Task A_stream_reopen_during_the_reread_drops_its_replay_and_its_signal()
{
await using var rig = new Rig();
using var driver = NewDriver(rig.Feed);
var trace = Record(driver);
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
var s = await rig.NextStreamAsync();
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
await TestWait.UntilAsync(() => Count(trace) == 1, "the first sentinel's signal", () => Dump(trace));
await driver.UnsubscribeAlarmsAsync(h1, Ct);
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
var q = await rig.NextQueryAsync();
s.TryComplete(new InvalidOperationException("gateway stream fault"));
var s2 = await rig.NextStreamAsync();
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct); // Tank2 cleared in the gap: absent
await TestWait.UntilAsync(() => Count(trace) == 2, "the reopened stream's signal", () => Dump(trace));
q.Complete(Entry(Tank2, AlarmConditionState.Active)); // stale: read before the clear
await Task.Delay(200, Ct);
Snapshot(trace).ShouldBe(["signal:" + Tank1, $"signal:{Tank1},{Tank2}"],
"no phantom Active from the stale re-read, and no second signal");
rig.QueryCount.ShouldBe(1, "positive control: the re-read really ran");
}
/// <summary>F4: a subscription changed during the snapshot phase is re-read at the sentinel instead of waiting for a reopen.</summary>
[Fact]
public async Task A_sentinel_under_an_earlier_subscription_triggers_a_reread_that_signals()