diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 8ccc45efe..4d0e0520c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -1419,10 +1419,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // WireMethodTransitionReporting) equals the node's current state → no delta → suppress, so // the transition is reported exactly once. ReportConditionEvent // stamps a fresh EventId, ClearChangeMasks, and ReportEvent — all still under this lock. - // A1 (§5.1): a projected snapshot IS an established state. The record is raised by - // ReportConditionEvent when the gate fires, otherwise here as a state-only record (ConditionClass and - // the other silent fields). - _conditionStateKnown.Add(key); + // A1 (§5.1): a NATIVE driver transition IS an established state. A SCRIPTED projection is not: the + // engine's Active is not persisted, so a post-load re-assert (or a projection after an operator + // ack/shelve/disable before the inputs arrived) can carry Active=false that no predicate decided — + // scripted known-ness comes ONLY from MarkConditionsKnown (the engine's inputs-established flip). + // The record is raised by ReportConditionEvent when the gate fires, otherwise here as a state-only + // record (ConditionClass and the other silent fields). + if (_nativeAlarmNodeIds.Contains(key)) _conditionStateKnown.Add(key); if (fire) { ReportConditionEvent(condition, sourceTimestampUtc); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs index ebe4b28de..a561f439f 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/ConditionStateNodeManagerTests.cs @@ -208,6 +208,28 @@ public sealed class ConditionStateNodeManagerTests : IDisposable await host.DisposeAsync(); } + /// Review B1: a scripted projection (a post-restart re-assert of a restored unacked alarm, or the + /// re-projection of an early operator ack) is not an established state — only MarkConditionsKnown makes a + /// scripted condition known. A native transition still is one. + [Fact] + public async Task B1_A_scripted_projection_never_marks_known_a_native_one_does() + { + var (host, nm, sink) = await BootAsync(); + MaterialiseAll(nm); + nm.CompleteAddressSpaceApply(); + + nm.WriteAlarmCondition(Scripted, State(false, false), DateTime.UtcNow, AddressSpaceRealm.Uns); // restored unacked + nm.WriteAlarmCondition(Scripted, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Uns); // early ack + nm.IsConditionStateKnown(Scripted, AddressSpaceRealm.Uns).ShouldBeFalse(); + sink.Records.ShouldNotContain(r => r.ConditionId == Scripted && r.StateKnown); + + nm.MarkConditionsKnown("scripted", [Scripted], AddressSpaceRealm.Uns).ShouldBe(1); + nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); + nm.IsConditionStateKnown(Native, AddressSpaceRealm.Raw).ShouldBeTrue(); + AssertParity(nm, sink); + await host.DisposeAsync(); + } + [Fact] public async Task T3_The_marker_moves_only_on_a_new_occurrence() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostInputsEstablishedTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostInputsEstablishedTests.cs index bc0d6a1a4..92db6c697 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostInputsEstablishedTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostInputsEstablishedTests.cs @@ -25,6 +25,8 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms; [Trait("Category", "Unit")] public sealed class ScriptedAlarmHostInputsEstablishedTests : RuntimeActorTestBase { + private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-a1host-{Guid.NewGuid():N}"); + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); private static CancellationToken Ct => TestContext.Current.CancellationToken; @@ -34,14 +36,111 @@ public sealed class ScriptedAlarmHostInputsEstablishedTests : RuntimeActorTestBa PredicateSource: "return (int)ctx.GetTag(\"M.T\").Value > 90;", DependencyRefs: ["M.T"], HistorizeToAveva: false, Retain: true, Enabled: true); - private IActorRef Spawn(TestProbe publish, TestProbe mux) + private IActorRef Spawn(TestProbe publish, TestProbe mux) => Spawn(publish, mux, new InMemoryAlarmStateStore(), out _); + + private IActorRef Spawn(TestProbe publish, TestProbe mux, IAlarmStateStore store, out ScriptedAlarmEngine engine) { var upstream = new DependencyMuxTagUpstreamSource(); var logger = new LoggerConfiguration().CreateLogger(); - var engine = new ScriptedAlarmEngine(upstream, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger); + engine = new ScriptedAlarmEngine(upstream, store, new ScriptLoggerFactory(logger), logger); return Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, upstream, engine, null)); } + /// + /// Review B1 (T2 case i): a restart restores a persisted UNACKED alarm (Active is not persisted). The post-load + /// re-assert projects it Active=false while its input is still never-pushed, and an operator ack before the input + /// arrives projects it again. Neither projection may make the condition known — that would be a + /// known=true, Active=false record no predicate decided. Known comes only from the engine's flip after the + /// first real evaluation. The host's publish-probe traffic is applied to a real node manager + hub. + /// + [Fact] + public async Task A_restored_unacked_alarm_is_not_known_through_its_reassert_or_an_early_ack() + { + var store = new InMemoryAlarmStateStore(); + await store.SaveAsync(AlarmConditionState.Fresh("alm-1", DateTime.UtcNow) with { Acked = AlarmAckedState.Unacknowledged }, Ct); + var (opcHost, nm) = await BootNodeManagerAsync(); + var hub = new ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionStateHub(); + nm.ConditionStateSink = hub; + nm.EnsureFolder("Plant/Line1/M", null, "M", AddressSpaceRealm.Uns); + nm.MaterialiseAlarmCondition("alm-1", "Plant/Line1/M", "HighTemp", "AlarmCondition", 800, AddressSpaceRealm.Uns); + nm.CompleteAddressSpaceApply(); + + var publish = CreateTestProbe(); + var mux = CreateTestProbe(); + var host = Spawn(publish, mux, store, out var engine); + host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()])); + mux.ExpectMsg(Timeout, cancellationToken: Ct); + + // The post-load re-assert of the restored unacked state, input still never-pushed. + var reassert = publish.ExpectMsg(Timeout, cancellationToken: Ct); + reassert.State.Active.ShouldBeFalse(); + reassert.State.Acknowledged.ShouldBeFalse(); + Apply(nm, reassert); + nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeFalse(); + + // An operator ack before the input arrives. + await engine.AcknowledgeAsync("alm-1", "op", null, Ct); + var ack = publish.ExpectMsg(Timeout, cancellationToken: Ct); + ack.State.Acknowledged.ShouldBeTrue(); + Apply(nm, ack); + nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeFalse(); + publish.ExpectNoMsg(TimeSpan.FromMilliseconds(300), Ct); + hub.ReadAll(0)!.ShouldNotContain(r => r.ConditionId == "alm-1" && r.StateKnown); + + // The late input: the first real evaluation marks it known. + host.Tell(new VirtualTagActor.DependencyValueChanged("M.T", 50, DateTime.UtcNow)); + var mark = publish.FishForMessage(m => m is OpcUaPublishActor.MarkConditionsKnown, Timeout, cancellationToken: Ct); + Apply(nm, mark); + nm.IsConditionStateKnown("alm-1", AddressSpaceRealm.Uns).ShouldBeTrue(); + hub.ReadAll(0)!.Last(r => r.ConditionId == "alm-1").ShouldSatisfyAllConditions( + r => r.StateKnown.ShouldBeTrue(), r => r.Active.ShouldBeFalse()); + await opcHost.DisposeAsync(); + } + + private static void Apply(OtOpcUaNodeManager nm, object message) + { + switch (message) + { + case OpcUaPublishActor.AlarmStateUpdate u: + nm.WriteAlarmCondition(u.AlarmNodeId, u.State, u.TimestampUtc, u.Realm); + break; + case OpcUaPublishActor.MarkConditionsKnown m when m.Known: + nm.MarkConditionsKnown(m.Source, m.ConditionIds, m.Realm); + break; + case OpcUaPublishActor.MarkConditionsKnown m: + nm.MarkConditionsUnknown(m.Source, m.ConditionIds, m.Realm); + break; + } + } + + private async Task<(OpcUaApplicationHost Host, OtOpcUaNodeManager Nm)> BootNodeManagerAsync() + { + var started = await OpcUaHostStart.StartAsync( + port => new OpcUaApplicationHost( + new OpcUaApplicationHostOptions + { + ApplicationName = "OtOpcUa.A1HostTest", + ApplicationUri = $"urn:OtOpcUa.A1HostTest:{Guid.NewGuid():N}", + OpcUaPort = port, + PublicHostname = "localhost", + PkiStoreRoot = _pkiRoot, + }, + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance), + () => new OtOpcUaSdkServer(), Ct); + return (started.Host, started.Server.NodeManager!); + } + + /// Cleans up the PKI root directory. + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing && Directory.Exists(_pkiRoot)) + { + try { Directory.Delete(_pkiRoot, recursive: true); } + catch { /* best-effort cleanup */ } + } + } + /// T2 (i) at the host: the input arrives late ⇒ no mark before the first real evaluation; then the Active /// projection, then the mark. [Fact]