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 c301388c6..862b1ac8b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -2338,7 +2338,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS var nodeId = n.NodeId; var snapshot = _nativeAlarmProjector.Project(nodeId, msg.Args, out IReadOnlyList historyKinds); _opcUaPublishActor.Tell(new ZB.MOM.WW.OtOpcUa.Runtime.OpcUa.OpcUaPublishActor.AlarmStateUpdate( - nodeId, snapshot, msg.Args.SourceTimestampUtc, n.Realm)); + nodeId, snapshot, msg.Args.SourceTimestampUtc, n.Realm, Source: msg.DriverInstanceId)); // Only the Primary publishes the cluster-wide alerts transition (see the gate above). The projector // decides WHICH rows the transition warrants: none for a re-statement (a Raise on an 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 418fdb752..9c3adfc69 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/OpcUa/OpcUaPublishActor.cs @@ -76,7 +76,28 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers /// The source timestamp of the transition in UTC. /// The namespace realm the condition lives in — for /// scripted alarms (default), for v3 native raw conditions. - public sealed record AlarmStateUpdate(string AlarmNodeId, AlarmConditionSnapshot State, DateTime TimestampUtc, AddressSpaceRealm Realm); + /// A1 (plan §5.1 G3): the emitting source — the driver instance id for a native projection, + /// for the scripted host, null when unattributed. Only used to discard a source's + /// deferred when one of its deferred projections is dropped or skipped. + public sealed record AlarmStateUpdate(string AlarmNodeId, AlarmConditionSnapshot State, DateTime TimestampUtc, AddressSpaceRealm Realm, + string? Source = null); + + /// The / of the scripted host. + public const string ScriptedSource = "scripted-alarms"; + + /// + /// A1 (plan §5.1 T1/F2/G3): the state of has been established by + /// (or, with false, can no longer be vouched for). Treated as an + /// alarm message: applied after every the same sender sent before it (Akka per-pair + /// order), deferred beside them while a plan is in flight and replayed AFTER the deferred alarms — or discarded + /// when one of the same source's deferred projections was dropped (overflow) or skipped (out of scope), so a + /// condition is never made known over a projection that did not land. + /// + /// The driver instance id, or . + /// The condition node ids (RawPath for native, ScriptedAlarmId for scripted). + /// Their realm. + /// True = mark known; false = withdraw (a scripted input reverted to never-pushed). + public sealed record MarkConditionsKnown(string Source, IReadOnlyList ConditionIds, AddressSpaceRealm Realm, bool Known = true); /// Annotate a materialised condition's source-data Quality out of band from any alarm /// transition (the driver-connectivity path: comms lost → , /// restored → ). Routed to , @@ -562,6 +583,7 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers Receive(HandleAttributeStatusBatchUpdate); Receive(HandleAlarmUpdate); Receive(HandleAlarmQualityUpdate); + Receive(HandleMarkConditionsKnown); Receive(HandleRebuild); Receive(HandlePlanReady); Receive(HandlePlanFailed); @@ -775,6 +797,25 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers } } + private void HandleMarkConditionsKnown(MarkConditionsKnown msg) + { + if (PlanPipelineBusy) _deferred.Mark(msg); + ApplyMark(msg); + } + + private void ApplyMark(MarkConditionsKnown msg) + { + try + { + if (msg.Known) _sink.MarkConditionsKnown(msg.Source, msg.ConditionIds, msg.Realm); + else _sink.MarkConditionsUnknown(msg.Source, msg.ConditionIds, msg.Realm); + } + catch (Exception ex) + { + _log.Warning(ex, "OpcUaPublish: sink.MarkConditions{Kind} threw for {Source}", msg.Known ? "Known" : "Unknown", msg.Source); + } + } + private void HandleAlarmQualityUpdate(AlarmQualityUpdate msg) { if (PlanPipelineBusy) DeferAlarmQuality(msg); @@ -1047,7 +1088,10 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers private void DeferAlarm(AlarmStateUpdate msg) { - if (!_deferred.Alarm(msg)) WarnDeferredOverflow(); + if (_deferred.Alarm(msg)) return; + // G3: this source's projection will not be replayed, so its deferred "known" marks must not be either. + _deferred.NoteAlarmLoss(msg.Source); + WarnDeferredOverflow(); } private void DeferAlarmQuality(AlarmQualityUpdate msg) @@ -1105,7 +1149,12 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers var alarms = 0; foreach (var alarm in _deferred.Alarms) { - if (!scope.Conditions.Contains((alarm.Realm, alarm.AlarmNodeId))) continue; + 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); } catch (Exception ex) { _log.Warning(ex, "OpcUaPublish: replaying a deferred alarm write threw for {Node}", alarm.AlarmNodeId); } @@ -1120,6 +1169,31 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers 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 in _deferred.Marks) + { + if (_deferred.SourceLost(mark.Source)) + { + discarded++; + continue; + } + + marks++; + ApplyMark(mark); + } + + if (discarded > 0) + { + OtOpcUaTelemetry.DataConnConditionMarksDiscarded.Add(discarded); + _log.Info( + "OpcUaPublish: discarded {Count} deferred condition-known mark(s) whose source lost a deferred alarm projection; those conditions stay unknown until the source signals again", + discarded); + } + _log.Debug( "OpcUaPublish: replayed {Values} value, {Statuses} status, {Alarms} alarm-state and {Qualities} alarm-quality writes (of {Held} held; {Unfit} not fitting a re-shaped node) deferred during a rebuild plan", values.Count, statuses.Count, alarms, qualities, _deferred.Count, unfit); @@ -1146,13 +1220,34 @@ 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 _marks = new(); + private readonly HashSet _lossySources = new(StringComparer.Ordinal); + private bool _unattributedLoss; public int Capacity { get; } = capacity; public long Dropped { get; private set; } public int Count => _variables.Count + _alarms.Count + _qualities.Count; - public bool IsEmpty => Count == 0; + public bool IsEmpty => Count == 0 && _marks.Count == 0; public IEnumerable Alarms => _alarms.Values; public IEnumerable AlarmQualities => _qualities.Values; + public IReadOnlyList Marks => _marks; + + public void Mark(MarkConditionsKnown msg) + { + if (_marks.Count < Capacity) _marks.Add(msg); + } + + /// G3: a deferred projection of was dropped or skipped. An unattributed + /// loss (null source) discards every source's marks. + public void NoteAlarmLoss(string? source) + { + if (source is null) _unattributedLoss = true; + else _lossySources.Add(source); + } + + public bool SourceLost(string source) => _unattributedLoss || _lossySources.Contains(source); public bool Value(in ValueWrite write) { @@ -1218,6 +1313,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers _variables.Clear(); _alarms.Clear(); _qualities.Clear(); + _marks.Clear(); + _lossySources.Clear(); + _unattributedLoss = false; Dropped = 0; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs index d7e6aa0c0..27036999e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs @@ -482,7 +482,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor // A client reading Time/ReceiveTime after a rebuild should still see when the alarm went // active, not when the address space happened to be rebuilt. TimestampUtc: projection.Condition.LastTransitionUtc, - Realm: AddressSpaceRealm.Uns)); + Realm: AddressSpaceRealm.Uns, + Source: OpcUaPublishActor.ScriptedSource)); reasserted++; } @@ -582,7 +583,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor AlarmNodeId: e.AlarmId, State: ToSnapshot(e), TimestampUtc: e.TimestampUtc, - Realm: AddressSpaceRealm.Uns)); + Realm: AddressSpaceRealm.Uns, + Source: OpcUaPublishActor.ScriptedSource)); // Publish the transition to the cluster `alerts` topic — the single historization + live // fan-out path. The mediator was cached on the ACTOR thread in PreStart; we only Tell it here. 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 new file mode 100644 index 000000000..aaaa12bcd --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/OpcUa/OpcUaPublishActorConditionKnownTests.cs @@ -0,0 +1,229 @@ +using System.Text.Json; +using Akka.Actor; +using Microsoft.Extensions.Logging.Abstractions; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; +using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa; +using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; + +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. +/// +[Trait("Feature", "GrpcData")] +[Trait("Phase", "A1")] +[Trait("Category", "Unit")] +public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase +{ + private static readonly TimeSpan PlanBudget = TimeSpan.FromSeconds(30); + private const string Src = OpcUaPublishActor.ScriptedSource; + + private static readonly AlarmConditionSnapshot Active = + new(Active: true, Acknowledged: false, Confirmed: true, Enabled: true, AlarmShelvingKind.Unshelved, 500, "high"); + + [Fact] + public void Live_a_mark_applies_after_the_alarm_state_sent_before_it() + { + var sink = new OrderSink("al-1"); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, new AddressSpaceApplier(sink, NullLogger.Instance), new OpcUaPublishActor.TestHooks())); + + actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src)); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns)); + + AwaitAssert(() => sink.IsKnown("al-1").ShouldBeTrue(), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink.Log.ShouldBe(["alarm:al-1:True", "known:al-1"]); + } + + /// T2 (iv) at the publish actor: the apply is artificially delayed (the plan is held open); the alarm and + /// the mark both arrive during it; on replay the mark still lands after the Active projection. + [Fact] + public void During_a_plan_the_deferred_mark_replays_after_the_deferred_alarm() + { + var sink = new OrderSink(); + using var gate = new ManualResetEventSlim(false); + var actor = Spawn(sink, gate); + + actor.Tell(Rebuild()); + actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src)); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns)); + AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + sink.IsKnown("al-1").ShouldBeFalse(); // the condition does not exist yet + + gate.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + sink.IsKnown("al-1").ShouldBeTrue(); + sink.Log.IndexOf("known:al-1").ShouldBeGreaterThan(sink.Log.IndexOf("alarm:al-1:True")); + } + + /// T2 (x) G3 — overflow: the deferred alarm does not fit, so the same source's deferred mark is discarded + /// and the condition stays unknown until the next signal. + [Fact] + public void A_deferred_alarm_overflow_discards_the_sources_deferred_mark() + { + var sink = new OrderSink(); + 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()); + // Fill the one-key buffer, so the alarm state is dropped. + 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)); + AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-1"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + gate.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + sink.ConditionExists("al-1").ShouldBeTrue(); + sink.IsKnown("al-1").ShouldBeFalse("never known over a projection that did not land"); + + // The next signal (after its projection) makes it known. + actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-1", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src)); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns)); + AwaitAssert(() => sink.IsKnown("al-1").ShouldBeTrue(), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + /// T2 (x) G3 — out-of-scope skip: a deferred projection of the source is skipped on replay (its condition is + /// not in the applied scope), so the source's mark is discarded even for a condition that does exist. + [Fact] + public void An_out_of_scope_skip_discards_the_sources_deferred_mark_but_not_another_sources() + { + var sink = new OrderSink(); + using var gate = new ManualResetEventSlim(false); + var actor = Spawn(sink, gate); + + actor.Tell(Rebuild()); + actor.Tell(new OpcUaPublishActor.AlarmStateUpdate("al-ghost", Active, DateTime.UtcNow, AddressSpaceRealm.Uns, Src)); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns)); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown("drv-1", ["al-1"], AddressSpaceRealm.Uns)); + AwaitAssert(() => sink.Skipped.ShouldContain("alarm:al-ghost"), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + gate.Set(); + ExpectMsg(PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + + sink.Marks.ShouldBe(["drv-1"]); // the scripted source's mark was discarded; the unrelated source's applied + } + + [Fact] + public void A_withdrawal_reaches_MarkConditionsUnknown() + { + var sink = new OrderSink("al-1"); + var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink, new AddressSpaceApplier(sink, NullLogger.Instance), new OpcUaPublishActor.TestHooks())); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns)); + actor.Tell(new OpcUaPublishActor.MarkConditionsKnown(Src, ["al-1"], AddressSpaceRealm.Uns, Known: false)); + AwaitAssert(() => sink.Log.ShouldBe(["known:al-1", "unknown:al-1"]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) => + Sys.ActorOf(OpcUaPublishActor.PropsForTests( + sink, new AddressSpaceApplier(sink, NullLogger.Instance), + new OpcUaPublishActor.TestHooks { BeforePlan = () => gate.Wait() })); + + private static OpcUaPublishActor.RebuildAddressSpace Rebuild() => + new(CorrelationId.NewId(), DeploymentId.NewId(), ScriptedAlarmArtifact(), ReportOutcome: true); + + private static byte[] ScriptedAlarmArtifact() => + JsonSerializer.SerializeToUtf8Bytes(new + { + UnsAreas = new[] { new { UnsAreaId = "area-1", ClusterId = "c1", Name = "Area" } }, + UnsLines = new[] { new { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "Line" } }, + Equipment = new[] { new { EquipmentId = "eq-1", DriverInstanceId = (string?)null, UnsLineId = "line-1", Name = "Eq", MachineCode = "EQ-1" } }, + RawFolders = Array.Empty(), + DriverInstances = Array.Empty(), + Devices = Array.Empty(), + TagGroups = Array.Empty(), + Tags = Array.Empty(), + ScriptedAlarms = new[] + { + new + { + ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "High", AlarmType = "AlarmCondition", + Severity = 500, MessageTemplate = "high", PredicateScriptId = "s-1", HistorizeToAveva = false, + Retain = true, Enabled = true, + }, + }, + Scripts = new[] { new { ScriptId = "s-1", SourceCode = "return false;" } }, + }); + + /// Records the order alarm states and marks land in; like the node manager, both are no-ops for a + /// condition that does not exist. + private sealed class OrderSink : IOpcUaAddressSpaceSink + { + private readonly object _gate = new(); + private readonly HashSet _conditions = new(); + private readonly HashSet _known = new(); + private readonly List _log = new(); + private readonly List _skipped = new(); + private readonly List _marks = new(); + + public OrderSink(params string[] existing) => _conditions.UnionWith(existing); + + public List Log { get { lock (_gate) return [.. _log]; } } + public List Skipped { get { lock (_gate) return [.. _skipped]; } } + public List Marks { get { lock (_gate) return [.. _marks]; } } + public bool IsKnown(string id) { lock (_gate) return _known.Contains(id); } + public bool ConditionExists(string id) { lock (_gate) return _conditions.Contains(id); } + + public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime ts, AddressSpaceRealm realm) + { + lock (_gate) + { + if (!_conditions.Contains(alarmNodeId)) { _skipped.Add("alarm:" + alarmNodeId); return; } + _log.Add($"alarm:{alarmNodeId}:{state.Active}"); + _known.Add(alarmNodeId); + } + } + + public void MarkConditionsKnown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + { + lock (_gate) + { + foreach (var id in conditionIds.Where(_conditions.Contains)) + { + _log.Add("known:" + id); + _marks.Add(source); + _known.Add(id); + } + } + } + + public void MarkConditionsUnknown(string source, IReadOnlyList conditionIds, AddressSpaceRealm realm) + { + lock (_gate) + { + foreach (var id in conditionIds.Where(_conditions.Contains)) + { + _log.Add("unknown:" + id); + _known.Remove(id); + } + } + } + + public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) + { + lock (_gate) _conditions.Add(alarmNodeId); + } + + public void RebuildAddressSpace() + { + lock (_gate) { _conditions.Clear(); _known.Clear(); } + } + + public void WriteValue(string nodeId, object? value, uint statusCode, DateTime ts, AddressSpaceRealm realm) { } + public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime ts, AddressSpaceRealm realm) { } + public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { } + public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { } + public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { } + public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { } + public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { } + } +}