diff --git a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md index 6039f7e72..ddeba7f60 100644 --- a/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md +++ b/docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md @@ -545,8 +545,13 @@ conditions re-report (`NM:5639-5651`). Some state changes never produce an event - `DriverHostActor` turns it into `MarkConditionsKnown(driverInstanceId, conditionIds)` and sends it to `OpcUaPublishActor` **after** the `AlarmStateUpdate`s it already forwarded (Akka preserves per-sender-pair order). - `OpcUaPublishActor` treats it as an alarm message. While a plan apply is in progress (`PlanPipelineBusy`) it is - deferred beside the `AlarmStateUpdate`s (`HandleAlarmUpdate`/`DeferAlarm`) and replayed **after** the deferred - alarms. + deferred beside the `AlarmStateUpdate`s (`HandleAlarmUpdate`/`DeferAlarm`). **As implemented after #926 review + r2:** the deferred alarm states, alarm qualities and marks are replayed in **arrival order** (one list, per-entry + sequence). Marks are held per condition, so a later mark of the same condition replaces an earlier one, and + withdrawals are bounded by the number of conditions. + - A "known" mark still lands after the projections it summarises, because it arrived after them. + - A withdrawal followed by a re-establishing transition now ends known, as the live path leaves it. Replaying all + marks last had ended it unknown. - **Loss rule (G3).** The deferral is a bounded keyed store, not a queue. An `AlarmStateUpdate` that does not fit is dropped (`DeferAlarm` → `WarnDeferredOverflow`, `OpcUaPublishActor.cs:1048-1051`), and replay skips alarms outside the applied scope (`:1106-1112`). diff --git a/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md b/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md index b51bf7d54..27073486b 100644 --- a/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md +++ b/docs/plans/evidence/grpc-data-ext/926-refresh-bracket.md @@ -145,3 +145,33 @@ M6 goes through the `ReportRefreshFailedForTest` seam. The catch that calls it i **Residual.** If a subscription never signalled (its initial refresh is still pending), a loss withdraws nothing, because nothing was known. + +## Review round 2 (2026-11-28) + +| # | Finding | Outcome | +|---|---|---| +| 1 | `OpcUaPublishActor` replayed every deferred alarm first and every mark last. So a withdrawal followed by a transition, both deferred by a plan, ended **unknown** although the transition had re-established the condition, and the host no longer counted it in F5. | **Fixed.** Deferred alarm states, alarm qualities and marks replay as **one list in arrival order**. Each entry carries a sequence number, and consecutive marks of the same (source, realm, known) are batched into one sink call. The G3 out-of-scope check is a pre-pass, so a source's known marks are still discarded wherever they sit in the list. Pinned by `Deferred_alarms_and_marks_replay_in_arrival_order`, which also checks the mirror order (transition then withdrawal ends unknown). That test is red against the previous actor. | +| 5 | The deferred-withdrawal list was "bounded by connectivity edges", which stopped being true once #926 made withdrawals routine. | **Fixed.** Deferred marks are now held **per (realm, condition)**, and the latest mark wins. Withdrawals are never dropped, and are bounded by the number of conditions. Known marks for a new condition beyond `Capacity` still overflow, as before. `A_withdrawal_beyond_the_deferral_capacity_is_never_dropped` now expects one coalesced replay instead of three (it is red against the old list). | +| 2 | The driver looked up the subscription outside `_alarmStateLock`, so a stale record could signal or withdraw. | **Fixed.** `IsRegisteredLocked` is re-checked under the lock before a RefreshEnd signals and before a withdrawal, and both removals (`UnsubscribeAlarmsAsync`, the shutdown loop) now take the lock. There is no deterministic unit test for this race; the lock is the guarantee. | +| 3 | A withdrawal after F5 had already raised its diagnostic did not update the diagnostic's count. | **Fixed.** The host calls `Hub.UpdateUnsignalled` when the pending set grows under a raised diagnostic. Covered by `A_withdrawal_after_the_diagnostic_updates_its_count`, which is red with the call removed. | +| 4 | Conditions on unsignalable subscriptions never withdraw. | **Documented** in `IAlarmInitialStateSignal`. Only a source that signalled withdraws; conditions made known by the backstop stay known through a later loss. That is the backstop's own residual. | +| 6 | The backstop test had no positive control. | **Fixed.** The sibling condition that was not withdrawn is marked known by the same backstop. | +| — | `AlarmInitialStatePublished` serialization | A comment now says it must stay in-process: a serialized copy that lost `Withdrawn` would default it to false and turn a withdrawal into a known mark. | + +**Found, not mine.** `OpcUaPublishActorWarmTests.A_deployed_cluster_mode_that_disagrees_with_the_local_mode_is_logged_and_counted` +fails when run in isolation. It has the same `MeterListener` and static-initializer trap fixed in the live test above: +it matches `ReferenceEquals(instrument, OtOpcUaTelemetry.RedundancyModeMismatch)` before that field has been initialized. +Reported as a follow-up. + +**Round 2 gates:** + +- Full Release build: 0 warnings. +- OpcUaClient.Tests: 430/430. +- OpcUaClient.IntegrationTests: 13/13, live against opc-plc. +- `GrpcDataV1CompatibilityTests`: 49/49. +- Runtime.Tests: 2095 of 2100 passed and 3 were skipped. + - The 2 failures are pre-existing; neither is caused by #926. + - `DriverHostActorApplyingStashTests.ACompletedApply_NeverReportsAWedge` fails every time on base `05f431f5d` too. I + confirmed this in a clean worktree at that commit. + - `GrpcDataConfiguredDiscoveryWireTests.Bad_null_sdk_notification_cannot_borrow_unproven_sample_evidence(different_timestamp)` + fails only under full-suite load. It passes in isolation, both on this branch and on base. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs index 8983ae9d9..c7f059d06 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/IAlarmInitialStateSignal.cs @@ -38,7 +38,10 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions; /// Withdrawing (#926). A source that signalled and then LOSES events for those conditions (an OPC UA /// event-queue overflow, a publish gap) raises the event with /// set: the host takes "known" back from them (Uncertain on a consumer) until the source signals again or a -/// transition re-establishes one. Same ordering rule: after every alarm event raised before it. +/// transition re-establishes one. Same ordering rule: after every alarm event raised before it. Only a source +/// that SIGNALLED withdraws: conditions that became known through the +/// backstop are not withdrawn by a later loss (the OPC UA client has no refresh bracket there, and its loss +/// detection never re-arms the backstop) — that residual is the backstop's own. /// /// public interface IAlarmInitialStateSignal diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs index b28c97282..fe9d23324 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient/OpcUaClientDriver.cs @@ -1374,7 +1374,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit foreach (var key in _alarmSubscriptions.Keys) { - if (!_alarmSubscriptions.TryRemove(key, out var ras)) continue; + RemoteAlarmSubscription? ras; + // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it. + lock (_alarmStateLock) + if (!_alarmSubscriptions.TryRemove(key, out ras)) continue; try { ras.EventItem.Notification -= ras.Handler; } catch { /* best-effort */ } if (sessionAlive) deletes.Add(DeleteSubscriptionBestEffortAsync(ras.Subscription, budget.Token)); @@ -2646,7 +2649,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit public async Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken) { if (handle is not OpcUaAlarmSubscriptionHandle h) return; - if (!_alarmSubscriptions.TryRemove(h.Id, out var rs)) return; + RemoteAlarmSubscription? rs; + // #926 review r2: removed under the emission lock, so no signal / withdrawal is mid-flight for it. + lock (_alarmStateLock) + if (!_alarmSubscriptions.TryRemove(h.Id, out rs)) return; var emptied = NoteSubscriptionDeleted(); await _subscriptionGate.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -2992,6 +2998,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit b.Open = false; if (opened && b.LossSinceStart is null) { + // #926 review r2: re-checked UNDER the lock (the lookup above ran outside it, and an unsubscribe + // removes the record under this lock): a released subscription never signals. + if (!IsRegisteredLocked(ras)) return; // grpc-data A1 (F1): the refresh replay this subscription requested is complete, lossless, and every // refreshed event before it was routed (sequential publishing, G2). Under the emission lock, so the // signal is ordered behind every emission. Covers the subscription's alarm RawPaths. Ends the @@ -3045,6 +3054,9 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit { if (!ras.Bracket.Signalled) return; ras.Bracket.Signalled = false; + // #926 review r2: a stale record (unsubscribed after the caller's lookup, still Signalled) must not withdraw + // refs that may now belong to a NEW subscription. Checked under the lock the unsubscribe removes it under. + if (!IsRegisteredLocked(ras)) return; _logger.LogWarning( "OpcUaClientDriver '{DriverInstanceId}': alarm subscription {SubscriptionId} lost events after its conditions " + "were declared known ({Reason}); withdrawing 'known' until a lossless ConditionRefresh.", @@ -3052,6 +3064,13 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit RaiseInitialAlarmState(ras.AlarmRefs, unsignalable: false, withdrawn: true); } + /// #926 review r2: is still the registered subscription for its handle. Caller holds + /// _alarmStateLock; removals take it too, so the answer holds for the rest of the critical section. + /// The alarm subscription record. + /// Whether it is the live registration. + private bool IsRegisteredLocked(RemoteAlarmSubscription ras) => + _alarmSubscriptions.TryGetValue(ras.Handle.Id, out var current) && ReferenceEquals(current, ras); + /// /// #926: the publish-sequence check of alarm subscription . The alarm subscription holds /// exactly one (event) monitored item, so every data-bearing notification message it receives carries its diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs index 0fe0adc7c..e5508bc3e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.ConditionSignals.cs @@ -225,8 +225,13 @@ public sealed partial class DriverHostActor var ownedPaths = owned.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal); var before = t.Pending.Count; t.Pending.UnionWith(msg.Args.ConditionIds.Where(ownedPaths.Contains)); - // An F5 window already running covers them; otherwise start one now. - if (t.Pending.Count != before && t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t); + // An F5 window already running covers them; otherwise start one now. A diagnostic already raised for + // that window must count them too (#926 review r2). + if (t.Pending.Count != before) + { + if (t.PendingSinceUtc is null) ArmSignalTimeout(msg.DriverInstanceId, t); + else if (t.DiagnosticRaised) _conditionSignals.Hub?.UpdateUnsignalled(msg.DriverInstanceId, t.Pending.Count); + } } _log.Info("DriverHost {Node}: driver {Driver} withdrew {Count} condition(s) ({Routed} routed) — state no longer known (events lost)", _localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, withdrawn); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index a97c84030..c444541bf 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -238,7 +238,9 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// , so it reaches after every alarm event the /// driver raised before it. /// A1 review S2: is the connection (Connected entry) the driver raised - /// it under, matching of that Good edge. + /// it under, matching of that Good edge. #926: keep this message + /// IN-PROCESS (child → parent only) — it carries by reference, and a + /// serialized copy that dropped Withdrawn would default it to false and turn a withdrawal into a "known" mark. public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args, long? ConnectionEpoch = null); private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs index dc173ba12..850d97126 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -1165,47 +1165,89 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying {Count} deferred status writes threw", statuses.Count); } } + // G3 pre-pass: a deferred projection outside the applied scope is skipped — its source's KNOWN marks are discarded + // wherever they sit in the arrival order (the conservative reading of "never known over a projection that did + // not land"). + foreach (var (alarm, _) in _deferred.Alarms) + if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) _deferred.NoteAlarmLoss(alarm.Source); + + // #926 review r2: alarm states, alarm qualities and condition-known marks replay as ONE list in ARRIVAL order. + // Marks used to replay after every alarm, which was right for a "known" mark (it summarises the projections + // before it) but wrong for a withdrawal followed by a live transition: replayed transition-then-withdrawal, + // the condition ended unknown although the transition had re-established it — and the host, which saw the + // transition last, no longer counted it in F5. Arrival order is exactly what the live path applies. + var items = new List<(long Seq, int Kind, int Index)>(); + var alarmList = _deferred.Alarms.ToList(); + var qualityList = _deferred.AlarmQualities.ToList(); + var markList = _deferred.Marks.ToList(); + for (var i = 0; i < alarmList.Count; i++) items.Add((alarmList[i].Seq, 0, i)); + for (var i = 0; i < qualityList.Count; i++) items.Add((qualityList[i].Seq, 1, i)); + for (var i = 0; i < markList.Count; i++) items.Add((markList[i].Seq, 2, i)); + items.Sort((x, y) => x.Seq.CompareTo(y.Seq)); + var alarms = 0; - foreach (var alarm in _deferred.Alarms) - { - if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) - { - _deferred.NoteAlarmLoss(alarm.Source); // G3: a skipped projection — the source's marks go too - continue; - } - - alarms++; - try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); } - catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); } - } - var qualities = 0; - foreach (var quality in _deferred.AlarmQualities) - { - if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue; - qualities++; - try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); } - catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); } - } - - // A1 F2/G3: the deferred "known" marks replay LAST, after every deferred alarm — and only for a source none of - // whose deferred projections was dropped or skipped. A discarded mark leaves its conditions unknown (Uncertain) - // until the source's next signal. var marks = 0; var discarded = 0; - foreach (var (mark, sender) in _deferred.Marks) + var discardedBySender = new Dictionary<(string Source, AddressSpaceRealm Realm), (IActorRef? Sender, List Ids)>(); + // Consecutive marks of one (source, realm, known) are applied as one sink call. + string? runSource = null; + AddressSpaceRealm runRealm = default; + var runKnown = false; + var runIds = new List(); + void FlushRun() { - // A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe. - if (mark.Known && _deferred.SourceLost(mark.Source)) + if (runIds.Count == 0) return; + marks++; + ApplyMark(new MarkConditionsKnown(runSource!, runIds.ToList(), runRealm, runKnown)); + runIds.Clear(); + } + + foreach (var (_, kind, index) in items) + { + if (kind == 2) { - discarded++; - TellDiscarded(sender, new ConditionMarksDiscarded(mark.Source, mark.ConditionIds, mark.Realm)); + var m = markList[index]; + // A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe. + if (m.Known && _deferred.SourceLost(m.Source)) + { + discarded++; + if (!discardedBySender.TryGetValue((m.Source, m.Realm), out var d)) + discardedBySender[(m.Source, m.Realm)] = d = (m.Sender, new List()); + d.Ids.Add(m.ConditionId); + continue; + } + + if (runIds.Count > 0 && (runSource != m.Source || runRealm != m.Realm || runKnown != m.Known)) FlushRun(); + runSource = m.Source; + runRealm = m.Realm; + runKnown = m.Known; + runIds.Add(m.ConditionId); continue; } - marks++; - ApplyMark(mark); + FlushRun(); + if (kind == 0) + { + var alarm = alarmList[index].Msg; + if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue; // counted in the pre-pass + alarms++; + try { _sink.WriteAlarmCondition(alarm.AlarmNodeId, alarm.State, alarm.TimestampUtc, alarm.Realm, alarm.EstablishesState); } + catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); } + } + else + { + var quality = qualityList[index].Msg; + if (!scope.Conditions.Contains((quality.Realm, quality.AlarmNodeId))) continue; + qualities++; + try { _sink.WriteAlarmQuality(quality.AlarmNodeId, quality.StatusCode, quality.TimestampUtc, quality.Realm); } + catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm-quality write threw for {Node}", quality.AlarmNodeId); } + } } + FlushRun(); + + foreach (var ((source, realm), (sender, ids)) in discardedBySender) + TellDiscarded(sender, new ConditionMarksDiscarded(source, ids, realm)); // N1: a KNOWN mark that did not fit the deferral was dropped (staying unknown is safe) — its sender hears it. foreach (var (source, sender) in _deferred.OverflowedMarkSources) @@ -1233,6 +1275,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// the two live writes leave on the node). Bounded by distinct keys across all kinds; /// beyond it a NEW key is not held (an existing key still updates), counted in . /// + /// One deferred condition-known mark (#926 review r2: per condition, with its arrival sequence). + private sealed record DeferredMark( + string Source, string ConditionId, AddressSpaceRealm Realm, bool Known, IActorRef? Sender, long Seq); + private sealed class DeferredWrites(int capacity) { private struct VariableEntry @@ -1246,11 +1292,14 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers } private readonly Dictionary<(AddressSpaceRealm, string), VariableEntry> _variables = new(); - private readonly Dictionary<(AddressSpaceRealm, string), AlarmStateUpdate> _alarms = new(); - private readonly Dictionary<(AddressSpaceRealm, string), AlarmQualityUpdate> _qualities = new(); - // A1: condition-known marks in arrival order (bounded by Capacity — a dropped mark only keeps conditions - // unknown, which is always safe), and the sources that lost a deferred alarm projection (G3). - private readonly List<(MarkConditionsKnown Msg, IActorRef? Sender)> _marks = new(); + private readonly Dictionary<(AddressSpaceRealm, string), (AlarmStateUpdate Msg, long Seq)> _alarms = new(); + private readonly Dictionary<(AddressSpaceRealm, string), (AlarmQualityUpdate Msg, long Seq)> _qualities = new(); + // A1 / #926 review r2: the LATEST condition-known mark per (realm, condition id), with its arrival sequence, and + // the sources that lost a deferred alarm projection (G3). Per-condition, so a withdrawal-heavy plan window holds + // at most one entry per condition (bounded by the address space), and replay can interleave marks with alarm + // states in arrival order. + private readonly Dictionary<(AddressSpaceRealm, string), DeferredMark> _marks = new(); + private long _seq; private readonly Dictionary _overflowedMarkSources = new(StringComparer.Ordinal); private readonly HashSet _lossySources = new(StringComparer.Ordinal); private bool _unattributedLoss; @@ -1259,20 +1308,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers public long Dropped { get; private set; } public int Count => _variables.Count + _alarms.Count + _qualities.Count; public bool IsEmpty => Count == 0 && _marks.Count == 0; - public IEnumerable Alarms => _alarms.Values; - public IEnumerable AlarmQualities => _qualities.Values; - public IReadOnlyList<(MarkConditionsKnown Msg, IActorRef? Sender)> Marks => _marks; + public IEnumerable<(AlarmStateUpdate Msg, long Seq)> Alarms => _alarms.Values; + public IEnumerable<(AlarmQualityUpdate Msg, long Seq)> AlarmQualities => _qualities.Values; + public IEnumerable Marks => _marks.Values; /// - /// Defer a mark. A withdrawal (Known: false) is never dropped — review round 2 N1: staying KNOWN over a - /// lost withdrawal is the unsafe direction, and withdrawals are bounded by connectivity edges. A known mark - /// beyond is dropped (unknown is safe) and its source is remembered so the sender hears - /// of it at replay (N2). + /// Defer a mark, per condition: a later mark of the same condition replaces the earlier (the later one is what + /// the live path leaves). A withdrawal (Known: false) is never dropped — review round 2 N1: staying KNOWN + /// over a lost withdrawal is the unsafe direction. It is bounded anyway: one entry per condition, so at most + /// the number of conditions in the address space (#926 made withdrawals routine, so the old "bounded by + /// connectivity edges" no longer held). A known mark for a NEW condition beyond marks is + /// dropped (unknown is safe) and its source is remembered so the sender hears of it at replay (N2). /// public void Mark(MarkConditionsKnown msg, IActorRef? sender) { - if (!msg.Known || _marks.Count < Capacity) _marks.Add((msg, sender)); - else _overflowedMarkSources[msg.Source] = sender; + foreach (var id in msg.ConditionIds) + { + if (string.IsNullOrEmpty(id)) continue; + var key = (msg.Realm, id); + if (msg.Known && !_marks.ContainsKey(key) && _marks.Count >= Capacity) + { + _overflowedMarkSources[msg.Source] = sender; + continue; + } + _marks[key] = new DeferredMark(msg.Source, id, msg.Realm, msg.Known, sender, ++_seq); + } } public IEnumerable<(string Source, IActorRef? Sender)> OverflowedMarkSources => @@ -1325,12 +1385,18 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers public bool Alarm(AlarmStateUpdate msg) { var key = (msg.Realm, msg.AlarmNodeId); - if (!Put(_alarms, key, msg)) return false; + if (!Put(_alarms, key, (msg, _seq + 1))) return false; + _seq++; _qualities.Remove(key); return true; } - public bool AlarmQuality(AlarmQualityUpdate msg) => Put(_qualities, (msg.Realm, msg.AlarmNodeId), msg); + public bool AlarmQuality(AlarmQualityUpdate msg) + { + if (!Put(_qualities, (msg.Realm, msg.AlarmNodeId), (msg, _seq + 1))) return false; + _seq++; + return true; + } public (List Values, List Statuses) VariableWrites(Func<(AddressSpaceRealm, string), bool> include) { @@ -1357,6 +1423,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers _lossySources.Clear(); _unattributedLoss = false; Dropped = 0; + _seq = 0; } private bool Put(Dictionary<(AddressSpaceRealm, string), T> map, (AddressSpaceRealm, string) key, T value) diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs index 86bed3f56..661ddb660 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmInitialStateSignalTests.cs @@ -160,14 +160,30 @@ public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBa } /// #926: a withdrawal removes the conditions from the OpcUaClient backstop — the timer must never mark a - /// condition known whose source just said it lost events. + /// condition known whose source just said it lost events. Positive control: the sibling it did not withdraw IS + /// marked by the same backstop. [Fact] public void A_withdrawal_cancels_the_backstop_for_its_conditions() { - var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi"], o => o.WithOpcUaClientSettle(TimeSpan.FromMilliseconds(600))); - rig.Driver.Signal([A], unsignalable: true); + var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"], o => o.WithOpcUaClientSettle(TimeSpan.FromMilliseconds(600))); + rig.Driver.Signal([A, B], unsignalable: true); rig.Driver.Signal([A], withdrawn: true); - AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(1500)); + var mark = rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); + mark.ConditionIds.ShouldBe([B], "only the sibling the driver did not withdraw"); + AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(800)); + } + + /// #926 review r2: a withdrawal after F5 already raised its diagnostic updates the diagnostic's count. + [Fact] + public void A_withdrawal_after_the_diagnostic_updates_its_count() + { + var rig = StartRig(DriverTypeNames.OpcUaClient, ["hi", "lo"], + o => o.WithSignalTimeout(DriverTypeNames.OpcUaClient, TimeSpan.FromMilliseconds(300))); + rig.Driver.Signal([A]).ShouldBeTrue(); // B stays pending + AwaitCondition(() => rig.Hub.Unsignalled.TryGetValue(DriverId, out var d) && d.Conditions == 1, TimeSpan.FromSeconds(5), Ct); + + rig.Driver.Signal([A], withdrawn: true).ShouldBeTrue(); + AwaitCondition(() => rig.Hub.Unsignalled.TryGetValue(DriverId, out var d) && d.Conditions == 2, TimeSpan.FromSeconds(5), Ct); } /// #926: the payload is either unsignalable or a withdrawal. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs index 523a0e65c..0e35fffb5 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs @@ -13,8 +13,9 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.OpcUa; /// /// A1 (plan §5.1 F2/G3): is an alarm message. Live it applies in -/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed AFTER them — and a -/// source that lost a deferred projection (overflow or out-of-scope skip) has its deferred marks discarded. +/// arrival order; while a plan is in flight it is deferred beside the alarm states and replayed with them in arrival +/// order (#926 review r2) — and a source that lost a deferred projection (overflow or out-of-scope skip) has its +/// deferred KNOWN marks discarded. /// [Trait("Feature", "GrpcData")] [Trait("Phase", "A1")] @@ -171,7 +172,8 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase } /// Review round 2 N1: a deferred withdrawal is never dropped by the deferral's capacity (a known mark may be — - /// unknown is the safe side). + /// unknown is the safe side). #926 review r2: deferred marks are held per condition, so repeated withdrawals of one + /// condition coalesce into one replayed withdrawal (bounded by the number of conditions). [Fact] public void A_withdrawal_beyond_the_deferral_capacity_is_never_dropped() { @@ -187,7 +189,45 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase gate.Set(); ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); - AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(6), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(4), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink.IsKnown("al-1").ShouldBeFalse(); + } + + /// + /// #926 review r2: a withdrawal followed by a live transition of the same condition, both deferred by a plan, + /// replays in ARRIVAL order — withdrawal, then the transition that re-establishes it — so the condition ends known, + /// as the live path leaves it (marks used to replay after every alarm, ending it unknown while the host no longer + /// counted it in F5). The mirror order (transition, then withdrawal) ends unknown. + /// + [Fact] + public void Deferred_alarms_and_marks_replay_in_arrival_order() + { + var sink = new OrderSink(); + using var gate = new ManualResetEventSlim(false); + var actor = Spawn(sink, gate); + + actor.Tell(Rebuild()); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false)); + actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1")); + AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + gate.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink.Log.ShouldBe(["unknown:al-1", "alarm:al-1:True"], "replayed in arrival order"); + sink.IsKnown("al-1").ShouldBeTrue("the transition after the withdrawal re-established it"); + + // Mirror (positive control for the order): transition, then withdrawal ⇒ unknown. + var sink2 = new OrderSink(); + using var gate2 = new ManualResetEventSlim(false); + var actor2 = Spawn(sink2, gate2); + actor2.Tell(Rebuild()); + actor2.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, "drv-1")); + actor2.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns, Known: false)); + AwaitAssert(() => sink2.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + gate2.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink2.Log.ShouldBe(["alarm:al-1:True", "unknown:al-1"]); + sink2.IsKnown("al-1").ShouldBeFalse(); } /// Review round 2 N2: a G3 discard of a driver's deferred mark is reported back to the mark's sender, so its