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 1f2a69224..a0b010f95 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 @@ -20,12 +20,16 @@ public sealed partial class DriverHostActor private sealed record ConditionSignalTimedOut(string DriverInstanceId, long Epoch); private sealed record ConditionBackstopElapsed(string DriverInstanceId, long Epoch); - /// Per driver instance: the current connectivity epoch, when its quality went Good, the conditions not - /// yet signalled since then, and the conditions the driver reported unsignalable. + /// Per driver instance: the current connectivity epoch, the child that sent the last edge, its connection + /// epoch at the last Good edge, when its quality went Good, when the current F5 window started, the conditions not + /// yet established since then, and the conditions the driver reported unsignalable. private sealed class ConditionSignalTracker { public long Epoch; + public IActorRef? Owner; + public long? ConnectionEpoch; public DateTime? GoodSinceUtc; + public DateTime? PendingSinceUtc; public readonly HashSet Pending = new(StringComparer.Ordinal); public readonly HashSet Unsignalable = new(StringComparer.Ordinal); public bool DiagnosticRaised; @@ -37,6 +41,9 @@ public sealed partial class DriverHostActor private static string SignalTimeoutKey(string driverInstanceId) => "cond-signal-timeout:" + driverInstanceId; private static string BackstopKey(string driverInstanceId) => "cond-backstop:" + driverInstanceId; + /// The injected clock (review nit: never here). + private DateTime ConditionClockUtc => _writeClock.GetUtcNow().UtcDateTime; + private void ReceiveConditionSignals() { Receive(OnAlarmInitialState); @@ -62,35 +69,117 @@ public sealed partial class DriverHostActor private string? DriverTypeOf(string driverInstanceId) => _children.TryGetValue(driverInstanceId, out var child) ? child.DriverType : null; - /// A connectivity edge restarts the F5 window (from quality Good) and the backstop; a Bad edge cancels both. - private void OnConditionSignalConnectivity(string driverInstanceId, bool connected) + /// Whether is the CURRENT child for — not a + /// stopped (retired) incarnation whose late message must not recreate a tracker after + /// , nor anything else. + private bool IsCurrentChild(string driverInstanceId, IActorRef sender) => + !_retiredChildren.Contains(sender) + && _children.TryGetValue(driverInstanceId, out var child) && Equals(child.Actor, sender); + + /// + /// A connectivity edge restarts the F5 window (from quality Good) and the backstop; a Bad edge cancels both. + /// Review S2: the Bad edge withdraws "known" from the driver's conditions — the source can no longer vouch for + /// their state, and an alarm raised during the outage would otherwise read known-inactive, Good after the + /// reconnect until the replay. A Good edge withdraws too (ahead of the Good quality annotation) when no Bad edge + /// was seen since the previous Good one, or it comes from a new child incarnation. They become known again only + /// on the reconnected source's next signal (or transition). + /// + private void OnConditionSignalConnectivity(string driverInstanceId, bool connected, IActorRef sender, long? connectionEpoch) { + if (!IsCurrentChild(driverInstanceId, sender)) + { + // A stopped incarnation (or a stray sender): never recreate or reset the tracker. Its Bad edge still + // withdraws known unless the CURRENT child of the same id is connected (its state is the live one). + var currentConnected = _conditionSignalTrackers.TryGetValue(driverInstanceId, out var live) && live.GoodSinceUtc is not null + && _children.TryGetValue(driverInstanceId, out var current) && Equals(live.Owner, current.Actor); + if (!connected && !currentConnected) WithdrawDriverConditionsKnown(driverInstanceId); + return; + } + var t = Tracker(driverInstanceId); + // A Good edge with no Bad edge since the previous Good one (or from a new incarnation) — withdraw here instead. + var missedBadEdge = connected && (t.GoodSinceUtc is not null || (t.Owner is not null && !Equals(t.Owner, sender))); + t.Owner = sender; t.Epoch++; Timers.Cancel(SignalTimeoutKey(driverInstanceId)); Timers.Cancel(BackstopKey(driverInstanceId)); t.Pending.Clear(); + t.PendingSinceUtc = null; + if (!connected || missedBadEdge) WithdrawDriverConditionsKnown(driverInstanceId); if (!connected) { t.GoodSinceUtc = null; + t.ConnectionEpoch = null; return; } - t.GoodSinceUtc = DateTime.UtcNow; + t.GoodSinceUtc = ConditionClockUtc; + t.ConnectionEpoch = connectionEpoch; if (_alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs)) foreach (var (rawPath, _) in refs) t.Pending.Add(rawPath); - if (t.Pending.Count > 0 && DriverTypeOf(driverInstanceId) is { } type) - { - Timers.StartSingleTimer(SignalTimeoutKey(driverInstanceId), new ConditionSignalTimedOut(driverInstanceId, t.Epoch), - _conditionSignals.SignalTimeoutFor(type)); - } - + ArmSignalTimeout(driverInstanceId, t); if (t.Unsignalable.Count > 0) ScheduleBackstop(driverInstanceId, t); } + /// (Re)start the F5 window for the tracker's pending conditions, from now. + private void ArmSignalTimeout(string driverInstanceId, ConditionSignalTracker t) + { + if (t.Pending.Count == 0 || DriverTypeOf(driverInstanceId) is not { } type) return; + t.PendingSinceUtc = ConditionClockUtc; + Timers.StartSingleTimer(SignalTimeoutKey(driverInstanceId), new ConditionSignalTimedOut(driverInstanceId, t.Epoch), + _conditionSignals.SignalTimeoutFor(type)); + } + + /// + /// Open-question answer (re-arm F5): after a deploy re-indexed the alarm refs, a CONNECTED driver's newly added + /// refs join Pending and the F5 window restarts now; refs the deploy removed leave it. (Today a deploy that + /// adds alarm refs also changes the driver's config — its RawTags are folded in — so the driver is respawned and + /// the new incarnation's Good edge re-arms F5 anyway; this covers an in-place deploy.) + /// + /// Each driver's alarm RawPaths before the reindex. + private void RearmConditionSignalsAfterReindex(IReadOnlyDictionary> previousRefs) + { + foreach (var (driverInstanceId, t) in _conditionSignalTrackers) + { + if (t.GoodSinceUtc is null) continue; // armed on the next Good edge + var current = _alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs) + ? refs.Select(r => r.RawPath).ToHashSet(StringComparer.Ordinal) + : new HashSet(StringComparer.Ordinal); + previousRefs.TryGetValue(driverInstanceId, out var before); + var added = current.Where(r => before is null || !before.Contains(r)).ToList(); + t.Pending.IntersectWith(current); + t.Unsignalable.IntersectWith(current); + if (added.Count > 0) + { + t.Pending.UnionWith(added); + ArmSignalTimeout(driverInstanceId, t); + } + else if (t.Pending.Count == 0) + { + ClearPendingWindow(driverInstanceId, t); + } + } + } + private void OnAlarmInitialState(DriverInstanceActor.AlarmInitialStatePublished msg) { + if (!IsCurrentChild(msg.DriverInstanceId, Sender)) + { + _log.Debug("DriverHost {Node}: dropping an initial alarm-state signal for {Id} from a sender that is not its current child", + _localNode, msg.DriverInstanceId); + return; + } + var t = Tracker(msg.DriverInstanceId); + // Review S2: a signal from an earlier connection (queued across a Connected→Reconnecting→Connected bounce) + // covers state the reconnect withdrew; it must not mark anything known. + if (msg.ConnectionEpoch is { } epoch && t.ConnectionEpoch != epoch) + { + _log.Debug("DriverHost {Node}: dropping a stale initial alarm-state signal from {Id} (connection {Epoch}, current {Current})", + _localNode, msg.DriverInstanceId, epoch, t.ConnectionEpoch); + return; + } + if (msg.Args.Unsignalable) { // InitialStateUnsignalable: no real signal will come. Only a driver type with a backstop (OpcUaClient) marks @@ -101,23 +190,61 @@ public sealed partial class DriverHostActor } var marked = MarkDriverConditionsKnown(msg.DriverInstanceId, msg.Args.ConditionIds); - t.Pending.ExceptWith(msg.Args.ConditionIds); t.Unsignalable.ExceptWith(msg.Args.ConditionIds); - if (t.Pending.Count == 0) + NoteConditionsEstablished(msg.DriverInstanceId, t, msg.Args.ConditionIds); + _log.Debug("DriverHost {Node}: driver {Driver} established {Count} condition(s) ({Marked} routed)", + _localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, marked); + } + + /// + /// Keep F5's "still unknown" set consistent with the node manager: a condition leaves Pending when the + /// node manager marks it known — on its driver's signal, and on a native transition (a native projection is an + /// established state there). An emptied set ends the F5 window and clears the diagnostic. + /// + private void NoteConditionsEstablished(string driverInstanceId, ConditionSignalTracker t, IEnumerable rawPaths) + { + if (t.Pending.Count == 0) return; + t.Pending.ExceptWith(rawPaths); + if (t.Pending.Count == 0) ClearPendingWindow(driverInstanceId, t); + } + + /// A forwarded native transition established (see ). + private void NoteNativeTransitionEstablished(string driverInstanceId, string rawPath) + { + if (_conditionSignalTrackers.TryGetValue(driverInstanceId, out var t) && t.GoodSinceUtc is not null) + NoteConditionsEstablished(driverInstanceId, t, [rawPath]); + } + + private void ClearPendingWindow(string driverInstanceId, ConditionSignalTracker t) + { + Timers.Cancel(SignalTimeoutKey(driverInstanceId)); + t.PendingSinceUtc = null; + // F5: a late signal clears the "not signalled" diagnostic. + if (!t.DiagnosticRaised) return; + t.DiagnosticRaised = false; + _conditionSignals.Hub?.ClearUnsignalled(driverInstanceId); + _log.Info("DriverHost {Node}: driver {Driver} signalled its initial alarm state late — diagnostic cleared", + _localNode, driverInstanceId); + } + + /// Review S2: withdraw "known" from every condition node of (one + /// with Known: false per realm), on the same chain as its + /// alarm projections and quality annotations. + private void WithdrawDriverConditionsKnown(string driverInstanceId) + { + if (_opcUaPublishActor is null || !_alarmRefsByDriver.TryGetValue(driverInstanceId, out var refs)) return; + var byRealm = new Dictionary>(); + foreach (var (_, nodes) in refs) { - Timers.Cancel(SignalTimeoutKey(msg.DriverInstanceId)); - // F5: a late signal clears the "not signalled" diagnostic. - if (t.DiagnosticRaised) + foreach (var n in nodes) { - t.DiagnosticRaised = false; - _conditionSignals.Hub?.ClearUnsignalled(msg.DriverInstanceId); - _log.Info("DriverHost {Node}: driver {Driver} signalled its initial alarm state late — diagnostic cleared", - _localNode, msg.DriverInstanceId); + if (!byRealm.TryGetValue(n.Realm, out var list)) byRealm[n.Realm] = list = new List(); + list.Add(n.NodeId); } } - _log.Debug("DriverHost {Node}: driver {Driver} established {Count} condition(s) ({Marked} routed)", - _localNode, msg.DriverInstanceId, msg.Args.ConditionIds.Count, marked); + foreach (var (realm, ids) in byRealm) + _opcUaPublishActor.Tell(new PublishActor.MarkConditionsKnown(driverInstanceId, ids, realm, Known: false)); } private void ScheduleBackstop(string driverInstanceId, ConditionSignalTracker t) @@ -130,7 +257,7 @@ public sealed partial class DriverHostActor return; } - var remaining = goodSince + settle - DateTime.UtcNow; + var remaining = goodSince + settle - ConditionClockUtc; Timers.StartSingleTimer(BackstopKey(driverInstanceId), new ConditionBackstopElapsed(driverInstanceId, t.Epoch), remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero); } @@ -141,9 +268,8 @@ public sealed partial class DriverHostActor return; var ids = t.Unsignalable.ToList(); t.Unsignalable.Clear(); - t.Pending.ExceptWith(ids); - if (t.Pending.Count == 0) Timers.Cancel(SignalTimeoutKey(msg.DriverInstanceId)); var marked = MarkDriverConditionsKnown(msg.DriverInstanceId, ids); + NoteConditionsEstablished(msg.DriverInstanceId, t, ids); _log.Info("DriverHost {Node}: backstop settled — {Count} unsignalable condition(s) of {Driver} marked known (residual: an upstream alarm active and never re-transitioned reads inactive)", _localNode, marked, msg.DriverInstanceId); } @@ -153,7 +279,7 @@ public sealed partial class DriverHostActor if (!_conditionSignalTrackers.TryGetValue(msg.DriverInstanceId, out var t) || t.Epoch != msg.Epoch || t.Pending.Count == 0) return; // F5: the conditions STAY unknown (Uncertain on a consumer) — never known-inactive. - var elapsed = t.GoodSinceUtc is { } since ? DateTime.UtcNow - since : TimeSpan.Zero; + var elapsed = (t.PendingSinceUtc ?? t.GoodSinceUtc) is { } since ? ConditionClockUtc - since : TimeSpan.Zero; t.DiagnosticRaised = true; if (_conditionSignals.Hub is { } hub) hub.ReportUnsignalled(msg.DriverInstanceId, elapsed, t.Pending.Count); else OtOpcUaTelemetry.DataConnConditionsUnsignalled.Add(t.Pending.Count, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index f4b139703..e61fa43cb 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -2016,7 +2016,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // The mux fan-out is independent of the OPC UA sink — a node with scripted alarms but no // publish actor (the mux-only test/dev path) must still see comms loss. Done before the early // return for exactly that reason. - OnConditionSignalConnectivity(msg.DriverInstanceId, msg.Connected); + OnConditionSignalConnectivity(msg.DriverInstanceId, msg.Connected, Sender, msg.ConnectionEpoch); if (!msg.Connected) { if (!_retiredChildren.Contains(Sender) && @@ -2340,6 +2340,8 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _localNode, msg.DriverInstanceId, msg.Args.ConditionId); } + // A1 review S2: the node manager marks a native condition known on this projection, so F5 stops counting it. + NoteNativeTransitionEstablished(msg.DriverInstanceId, msg.Args.ConditionId); foreach (var n in nodeIds) { var nodeId = n.NodeId; @@ -4058,6 +4060,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // The per-driver secondary indexes are rebuilt WHOLE alongside their primaries below — same pass, // same clear — so no incremental maintenance exists to get out of step with them. _valueRefsByDriver.Clear(); + // A1 review (re-arm F5): each driver's alarm refs before this reindex, so a deploy's added refs can be found. + var previousAlarmRefs = _alarmRefsByDriver.ToDictionary( + kv => kv.Key, kv => kv.Value.Select(e => e.RawPath).ToHashSet(StringComparer.Ordinal), StringComparer.Ordinal); _alarmRefsByDriver.Clear(); foreach (var t in composition.RawTags) { @@ -4139,6 +4144,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn // so the two stay in step. Keyed by the bare condition NodeId, exactly as ForwardNativeAlarm projects. _nativeAlarmProjector.RetainOnly(_driverRefByAlarmNodeId.Keys.ToHashSet(StringComparer.Ordinal)); PublishAckPreflight(); + RearmConditionSignalsAfterReindex(previousAlarmRefs); // Cache the per-driver payload as THE authority, in the same clear-and-repopulate pass as the routing // maps above so a rename/removal can never leave a stale entry behind. Keyed over the UNION of the two @@ -4680,6 +4686,9 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn _dataWriteRuntime?.BeforeDriverStopForTests?.Invoke(driverInstanceId); Context.Stop(entry.Actor); _children.Remove(driverInstanceId); + // A1 review S2: the stopped incarnation can no longer vouch for its conditions (a respawn's carried-over + // known state would otherwise stand until the new incarnation signals). No-op when the deploy removed them. + WithdrawDriverConditionsKnown(driverInstanceId); ForgetConditionSignals(driverInstanceId); PublishAckPreflight(); EvictRetainedValues(driverInstanceId); 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 984763c26..a97c84030 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -108,7 +108,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// annotates this driver's native alarm conditions' source-data Quality from it (comms lost → Bad, /// restored → Good) — independently of alarm transitions, since a comms-lost driver emits no alarm /// events. Fire-and-forget. - public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected, long? ProducerIncarnation = null); + public sealed record ConnectivityChanged(string DriverInstanceId, bool Connected, long? ProducerIncarnation = null, + long? ConnectionEpoch = null); /// /// Sent to the parent from so the host re-provisions THIS incarnation. @@ -236,8 +237,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// . It travels the SAME self-Tell → parent path as /// , so it reaches after every alarm event the /// driver raised before it. - public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args); - private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args); + /// A1 review S2: is the connection (Connected entry) the driver raised + /// it under, matching of that Good edge. + public sealed record AlarmInitialStatePublished(string DriverInstanceId, AlarmInitialStateEventArgs Args, + long? ConnectionEpoch = null); + private sealed record NativeAlarmInitialState(AlarmInitialStateEventArgs Args, long Epoch); /// Self-sent on Connected entry / when alarm refs are (re)pushed, to establish the native-alarm /// subscription that un-gates an driver's feed. Handled async so the /// call is bounded + off the synchronous handlers. @@ -505,6 +509,8 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers // A1 (plan §5.1 G5): attached and detached WITH the alarm handler, so the signal obeys exactly the gate // OnAlarmEvent obeys. private EventHandler? _alarmInitialStateHandler; + // A1 review S2: bumped on every Connected entry; read on the driver's thread when it raises its signal. + private long _connectionEpoch; private EventHandler? _rediscoveryHandler; private EventHandler? _hostStatusHandler; private EventHandler? _connectionLossHandler; @@ -898,7 +904,10 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers // Announce connectivity to the host so it can clear any comms-lost Quality annotation on this // driver's native alarm conditions (Bad → Good). Fire-and-forget; the host defaults conditions to a // non-Good "waiting for initial data" quality at materialise, and this is what confirms them Good. - Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true, ProducerIncarnation: _sourceIncarnation)); + // A1 review S2: a new connection epoch — a signal the driver raised under an earlier one is dropped below. + var epoch = Interlocked.Increment(ref _connectionEpoch); + Context.Parent.Tell(new ConnectivityChanged(_driverInstanceId, Connected: true, ProducerIncarnation: _sourceIncarnation, + ConnectionEpoch: epoch)); // Baseline for the comms-loss watchdog. Re-stamped on every Connected entry so a driver that // reconnects but never manages a read is measured from THIS connect, not from a stale earlier one. @@ -1000,7 +1009,18 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers // project it to the parent the same way DataChangeForward projects AttributeValueBatchPublished. Receive(m => Context.Parent.Tell(new AttributeAlarmPublished(_driverInstanceId, m.Args))); // A1 F2: the same mailbox and the same forward, so the signal follows every alarm event raised before it. - Receive(m => Context.Parent.Tell(new AlarmInitialStatePublished(_driverInstanceId, m.Args))); + // Review S2: a signal raised under an earlier connection (queued across a Connected→Reconnecting→Connected + // bounce, e.g. while an async reconnect held the mailbox) covers events of a feed that no longer exists — drop it. + Receive(m => + { + if (m.Epoch != Interlocked.Read(ref _connectionEpoch)) + { + _log.Debug("DriverInstance {Id}: initial alarm-state signal from an earlier connection — dropped", _driverInstanceId); + return; + } + + Context.Parent.Tell(new AlarmInitialStatePublished(_driverInstanceId, m.Args, m.Epoch)); + }); // ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the // sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter. Receive(msg => @@ -2557,7 +2577,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers src.OnAlarmEvent += _alarmEventHandler; if (_driver is IAlarmInitialStateSignal signal) { - _alarmInitialStateHandler = (_, e) => self.Tell(new NativeAlarmInitialState(e)); + _alarmInitialStateHandler = (_, e) => self.Tell(new NativeAlarmInitialState(e, Interlocked.Read(ref _connectionEpoch))); signal.InitialAlarmStateDelivered += _alarmInitialStateHandler; } } 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 9c3adfc69..d1c0e4108 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -1176,7 +1176,8 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers var discarded = 0; foreach (var mark in _deferred.Marks) { - if (_deferred.SourceLost(mark.Source)) + // A withdrawal (Known: false) is never discarded: it only makes conditions unknown, which is always safe. + if (mark.Known && _deferred.SourceLost(mark.Source)) { discarded++; continue; 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 e6a900a16..e23e47d39 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 @@ -1,7 +1,9 @@ using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers; @@ -112,4 +114,92 @@ public sealed class NativeAlarmInitialStateSignalTests : NativeAlarmSignalTestBa rig.Driver.Signal([A, B]).ShouldBeFalse(); AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(300)); } + + // ---------------------------------------------------------------- review S2 / re-arm F5 / nits + + /// + /// Review S2 — comms loss and a Connected→Reconnecting→Connected bounce: the Bad edge withdraws "known"; the + /// reconnect's Good quality annotation arrives with nothing marked known (an alarm raised during the outage must + /// not read known-inactive, Good); a signal queued under the earlier connection is dropped; the reconnected + /// driver's own signal marks them known again. + /// + [Fact] + public void Comms_loss_withdraws_known_and_a_signal_from_before_the_bounce_is_dropped() + { + var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"]); + rig.Driver.Signal([A, B]).ShouldBeTrue(); + rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); + var child = ChildOf(rig); + + rig.Host.Tell(new ReconnectDriver("c1", DriverId, "test", Guid.NewGuid()), TestActor); + var withdrawal = rig.Publish.FishForMessage(m => !m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); + withdrawal.Source.ShouldBe(DriverId); + withdrawal.ConditionIds.ShouldBe([A, B], ignoreOrder: true); + + // The child retries the connection on its reconnect interval; until its Good edge nothing is marked known. + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (true) + { + var m = rig.Publish.ReceiveOne(deadline - DateTime.UtcNow, Ct); + m.ShouldNotBeNull("the reconnect's Good quality annotation never arrived"); + if (m is OpcUaPublishActor.MarkConditionsKnown { Known: true } mark) + throw new ShouldAssertException($"marked known before the reconnected driver signalled: {string.Join(",", mark.ConditionIds)}"); + if (m is OpcUaPublishActor.AlarmQualityUpdate { StatusCode: OpcUaStatus.Good }) break; + } + + // A signal raised under the first connection, delivered after the bounce: dropped. + rig.Host.Tell(new DriverInstanceActor.AlarmInitialStatePublished(DriverId, new AlarmInitialStateEventArgs([A, B]), ConnectionEpoch: 1), child); + AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(400)); + + // Positive control: the reconnected driver's own signal marks them known. + AwaitCondition(() => rig.Driver.Signal([A, B]), TimeSpan.FromSeconds(10), Ct); + rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct) + .ConditionIds.ShouldBe([A, B], ignoreOrder: true); + } + + /// Open question answered — re-arm F5 for refs a deploy adds while the driver is connected. Today every such + /// deploy changes the driver's config (its authored RawTags are folded into it), so the driver is respawned: the + /// stopped incarnation's conditions are withdrawn, and the new incarnation's Good edge puts EVERY ref — the added one + /// included — in the F5 window, so a driver that never signals raises the diagnostic for all of them. (The reindex + /// re-arm covers a future in-place deploy.) + [Fact] + public void A_deploy_that_adds_alarm_refs_while_connected_covers_them_with_F5() + { + var rig = StartRig(DriverTypeNames.Galaxy, ["hi"], o => o.WithSignalTimeout(DriverTypeNames.Galaxy, TimeSpan.FromMilliseconds(400))); + rig.Driver.Signal([A]).ShouldBeTrue(); + rig.Publish.FishForMessage(m => m.Known, TimeSpan.FromSeconds(5), cancellationToken: Ct); + rig.Hub.Unsignalled.ShouldBeEmpty(); + + Redeploy(rig, ["hi", "lo"]); + rig.Publish.FishForMessage(m => !m.Known && m.ConditionIds.Contains(A), + TimeSpan.FromSeconds(5), cancellationToken: Ct); + + AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); + rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(2); + AwaitCondition(() => rig.Driver.Signal([A, B]), TimeSpan.FromSeconds(5), Ct); + AwaitCondition(() => !rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); + } + + /// Review S2 — F5's "still unknown" set follows the node manager: a native transition (which the node + /// manager treats as an established state) takes its condition out of the F5 count. + [Fact] + public void A_native_transition_leaves_the_F5_pending_set_like_the_node_manager() + { + var rig = StartRig(DriverTypeNames.Galaxy, ["hi", "lo"], o => o.WithSignalTimeout(DriverTypeNames.Galaxy, TimeSpan.FromMilliseconds(600))); + rig.Driver.Raise(A).ShouldBeTrue(); + rig.Publish.FishForMessage(u => u.AlarmNodeId == A, TimeSpan.FromSeconds(5), cancellationToken: Ct); + + AwaitCondition(() => rig.Hub.Unsignalled.ContainsKey(DriverId), TimeSpan.FromSeconds(5), Ct); + rig.Hub.Unsignalled[DriverId].Conditions.ShouldBe(1); // only B is still unknown + } + + /// Review nit — a signal from anything but the current child (a stopped incarnation, a stray sender) is + /// dropped and never (re)creates a tracker. + [Fact] + public void A_signal_from_a_sender_that_is_not_the_current_child_is_dropped() + { + var rig = StartRig(DriverTypeNames.Galaxy, ["hi"]); + rig.Host.Tell(new DriverInstanceActor.AlarmInitialStatePublished(DriverId, new AlarmInitialStateEventArgs([A])), TestActor); + AssertNoMark(rig.Publish, TimeSpan.FromMilliseconds(400)); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs index f3c09d527..ad92b811f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/NativeAlarmSignalTestBase.cs @@ -33,6 +33,10 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase protected const string DriverId = "drv-sig"; private static readonly NodeId RigNode = NodeId.Parse("a1-signal-rig"); private static readonly RevisionHash Rev = RevisionHash.Parse(new string('c', 64)); + private IDbContextFactory? _rigDb; + private TestProbe? _rigCoordinator; + private string? _rigDriverType; + private int _redeploys; /// The RawPath of alarm tag under the rig's folder/driver/device. /// The tag name. @@ -57,13 +61,15 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase Func? configure = null, FakeSignallingAlarmDriver? driver = null) { var db = NewInMemoryDbFactory(); - var deploymentId = Seed(db, driverType, alarmTags); + var deploymentId = Seed(db, driverType, alarmTags, Rev); + _rigDb = db; + _rigDriverType = driverType; driver ??= new FakeSignallingAlarmDriver(DriverId, driverType); var hub = new ConditionStateHub(); var options = new ConditionSignalOptions { Hub = hub }; options = configure?.Invoke(options) ?? options; - var coordinator = CreateTestProbe(); + var coordinator = _rigCoordinator = CreateTestProbe(); var publish = this.CreateCleanOutcomePublishProbe(); var host = Sys.ActorOf(DriverHostActor.Props( db, RigNode, coordinator.Ref, @@ -81,8 +87,27 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase return new Rig(host, publish, driver, hub); } + /// Re-deploys the last started rig with (a new revision) and waits for the apply. + /// The rig. + /// The alarm tag names the new revision carries. + protected void Redeploy(Rig rig, IReadOnlyList alarmTags) + { + var rev = RevisionHash.Parse(new string((char)('d' + _redeploys++ % 3), 64)); + var deploymentId = Seed(_rigDb!, _rigDriverType!, alarmTags, rev); + rig.Host.Tell(new DispatchDeployment(deploymentId, rev, CorrelationId.NewId())); + _rigCoordinator!.FishForMessage(a => a.DeploymentId == deploymentId, TimeSpan.FromSeconds(10), + cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied); + } + + /// The rig's current driver child (the DriverInstanceActor the host spawned). + /// The rig. + /// Its actor ref. + protected IActorRef ChildOf(Rig rig) => + Sys.ActorSelection(rig.Host.Path + "/drv-*").ResolveOne(TimeSpan.FromSeconds(5)).GetAwaiter().GetResult(); + /// Negative control: for , the probe receives no - /// (other traffic — quality annotations — is ignored). + /// that marks known (other traffic — quality annotations, + /// withdrawals — is ignored). /// The probe. /// How long to watch. protected static void AssertNoMark(TestProbe publish, TimeSpan duration) @@ -91,7 +116,7 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase while (DateTime.UtcNow < deadline) { var m = publish.ReceiveOne(deadline - DateTime.UtcNow); - if (m is OpcUaPublishActor.MarkConditionsKnown mark) + if (m is OpcUaPublishActor.MarkConditionsKnown { Known: true } mark) throw new ShouldAssertException($"unexpected MarkConditionsKnown({string.Join(",", mark.ConditionIds)})"); } } @@ -118,7 +143,8 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase throw new ShouldAssertException($"stop condition not met; saw {seen.Count} alarm message(s)"); } - private static DeploymentId Seed(IDbContextFactory db, string driverType, IReadOnlyList alarmTags) + private static DeploymentId Seed(IDbContextFactory db, string driverType, IReadOnlyList alarmTags, + RevisionHash rev) { var artifact = JsonSerializer.SerializeToUtf8Bytes(new { @@ -140,7 +166,7 @@ public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase using var ctx = db.CreateDbContext(); ctx.Deployments.Add(new Deployment { - DeploymentId = id.Value, RevisionHash = Rev.Value, Status = DeploymentStatus.Sealed, CreatedBy = "test", + DeploymentId = id.Value, RevisionHash = rev.Value, Status = DeploymentStatus.Sealed, CreatedBy = "test", SealedAtUtc = DateTime.UtcNow, ArtifactBlob = artifact, }); ctx.SaveChanges(); 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 aaaa12bcd..e05c52f35 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 @@ -123,6 +123,31 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase AwaitAssert(() => sink.Log.ShouldBe(["known:al-1", "unknown:al-1"]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); } + /// Review S2: a deferred WITHDRAWAL (Known: false) is never discarded by G3 — it only makes conditions + /// unknown, which is always safe — so it replays after the plan even for a source that lost a deferred projection. + [Fact] + public void A_deferred_withdrawal_is_replayed_even_for_a_source_that_lost_a_projection() + { + var sink = new OrderSink("al-1"); + using var gate = new ManualResetEventSlim(false); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests( + sink, new AddressSpaceApplier(sink, NullLogger.Instance), + new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() }, deferredWriteCapacity: 1)); + + actor.Tell(Rebuild()); + actor.Tell(new OpcUaPublishActor.AttributeValueBatchUpdate([new ValueWrite("Plant/x", 1, OpcUaStatus.Good, DateTime.UtcNow, AddressSpaceRealm.Raw)])); + actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src)); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns, Known: false)); + // Applied live (to the pre-plan node) as well as deferred. + AwaitAssert(() => sink.Log.ShouldContain("unknown:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + var unknownBeforeReplay = sink.Log.Count(l => l == "unknown:al-1"); + + gate.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + AwaitAssert(() => sink.Log.Count(l => l == "unknown:al-1").ShouldBe(unknownBeforeReplay + 1), PlanBudget, + cancellationToken: TestContext.Current.CancellationToken); + } + private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) => Sys.ActorOf(OpcUaPublishActor.PropsForTests( sink, new AddressSpaceApplier(sink, NullLogger.Instance),