diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
index 06b4ed634..1c339d8f2 100644
--- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
+++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs
@@ -320,6 +320,21 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// Raised for every emission the Part9StateMachine produces that the engine should publish.
public event EventHandler? OnEvent;
+ ///
+ /// A1 (grpc-data plan §5.1 T2): an alarm's read cache went from holding a never-pushed input
+ /// () to holding none — its condition state is now ESTABLISHED — or back
+ /// ( false: an input reverted to never-pushed, e.g. a tag
+ /// re-created by a deploy). Raised the first time after each and on every flip.
+ /// Ordering (F2): queued as the LAST item of the evaluation's pending emissions, so it fires only
+ /// after that evaluation's own emissions were dispatched, on the same thread.
+ /// This is a new predicate: filters never-pushed values out.
+ ///
+ public event EventHandler? OnInputsEstablished;
+
+ // A1: per alarm, whether its inputs were established at its last evaluation. Only touched under _evalGate;
+ // cleared by every LoadAsync so a reload (a rebuild re-materialised the conditions unknown) re-raises it.
+ private readonly Dictionary _inputsEstablished = new(StringComparer.Ordinal);
+
/// Gets the collection of loaded alarm identifiers.
public IReadOnlyCollection LoadedAlarmIds => _alarms.Keys.ToArray();
@@ -338,10 +353,11 @@ public sealed class ScriptedAlarmEngine : IDisposable
if (_disposed) throw new ObjectDisposedException(nameof(ScriptedAlarmEngine));
if (definitions is null) throw new ArgumentNullException(nameof(definitions));
- var pending = new List(0);
+ var pending = new PendingEmissions();
await _evalGate.WaitAsync(ct).ConfigureAwait(false);
try
{
+ _inputsEstablished.Clear();
// Stop the prior shelving timer BEFORE clearing _alarms so no in-progress
// tick can observe a half-cleared dictionary. Moving the dispose here also
// means a failed reload (compile errors, store failures) stops the timer
@@ -499,7 +515,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
// Fire any emissions collected during startup recovery OUTSIDE the gate so
// subscribers can re-enter the engine safely.
- foreach (var evt in pending) FireEvent(evt);
+ FirePending(pending);
}
///
@@ -819,7 +835,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
private async Task ReevaluateAsync(IReadOnlyList alarmIds, CancellationToken ct)
{
- var pending = new List(0);
+ var pending = new PendingEmissions();
try
{
await _evalGate.WaitAsync(ct).ConfigureAwait(false);
@@ -866,7 +882,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
}
// Fire emissions OUTSIDE _evalGate so subscriber callbacks can re-enter
// the engine without deadlocking.
- foreach (var evt in pending) FireEvent(evt);
+ FirePending(pending);
}
///
@@ -893,6 +909,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
state.Definition.AlarmId,
_ => new AlarmScratch(state.Inputs, state.Logger, _clock));
RefillReadCache(scratch.ReadCache, state.Inputs);
+ NoteInputsEstablishment(state.Definition.AlarmId, scratch.ReadCache, pendingEmissions);
var captured = CaptureInputs(state, scratch.ReadCache);
scratch.HasProjectedInputs = captured.Evidence is not null;
if (captured.Evidence is { IsValid: false }) return seed;
@@ -1051,6 +1068,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
var scratch = scratches[i] = _scratchByAlarmId.GetOrAdd(
state.Definition.AlarmId, _ => new AlarmScratch(state.Inputs, state.Logger, _clock));
RefillReadCache(scratch.ReadCache, state.Inputs);
+ NoteInputsEstablishment(state.Definition.AlarmId, scratch.ReadCache, pendingEmissions);
var captured = capturedInputs[i] = CaptureInputs(state, scratch.ReadCache);
worst[i] = WorstInputStatus(scratch.ReadCache);
if (!AreInputsReady(scratch.ReadCache) || captured.Evidence is { IsValid: false })
@@ -1367,6 +1385,45 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// that re-enters the engine (e.g. calls AcknowledgeAsync) would
/// deadlock against the non-reentrant SemaphoreSlim.
///
+ /// A1: record an established/reverted flip of 's inputs into the caller's pending
+ /// list (fired after every emission in it). Only called under _evalGate.
+ private void NoteInputsEstablishment(string alarmId, IReadOnlyDictionary cache,
+ List pendingEmissions)
+ {
+ var established = true;
+ foreach (var v in cache.Values)
+ {
+ if (v is null || v.StatusCode == StatusNeverPushed) { established = false; break; }
+ }
+
+ var had = _inputsEstablished.TryGetValue(alarmId, out var prior);
+ _inputsEstablished[alarmId] = established;
+ // First evaluation after a load: raise only "established" (an unknown condition is already unknown).
+ if (had ? prior == established : !established) return;
+ if (pendingEmissions is PendingEmissions pending) pending.Establishments.Add((alarmId, established));
+ }
+
+ /// Fire a caller's pending emissions, then (A1 F2) its input-establishment flips — last.
+ private void FirePending(List pending)
+ {
+ foreach (var evt in pending) FireEvent(evt);
+ if (pending is not PendingEmissions { Establishments.Count: > 0 } withFlips) return;
+ foreach (var (alarmId, established) in withFlips.Establishments)
+ {
+ try { OnInputsEstablished?.Invoke(this, new ScriptedAlarmInputsEventArgs(alarmId, established)); }
+ catch (Exception ex)
+ {
+ _engineLogger.Warning(ex, "ScriptedAlarmEngine OnInputsEstablished subscriber threw for {AlarmId}", alarmId);
+ }
+ }
+ }
+
+ /// A caller's pending emissions plus the input-establishment flips its evaluations found (A1).
+ private sealed class PendingEmissions : List
+ {
+ public List<(string AlarmId, bool Established)> Establishments { get; } = new();
+ }
+
private void FireEvent(ScriptedAlarmEvent evt)
{
if (evt.InputEvidence is { IsValid: false }) return;
@@ -1553,7 +1610,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
private async Task ShelvingCheckAsync(IReadOnlyList alarmIds, CancellationToken ct)
{
- var pending = new List(0);
+ var pending = new PendingEmissions();
try
{
await _evalGate.WaitAsync(ct).ConfigureAwait(false);
@@ -1596,7 +1653,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
return;
}
// Fire emissions OUTSIDE _evalGate.
- foreach (var evt in pending) FireEvent(evt);
+ FirePending(pending);
}
private void UnsubscribeFromUpstream()
@@ -1806,3 +1863,8 @@ public interface ITagUpstreamSource
/// A subscription handle that removes the observer when disposed.
IDisposable SubscribeTag(string path, Action observer);
}
+
+/// Payload of (A1, grpc-data plan §5.1).
+/// The alarm (= its condition node id).
+/// True: no input is never-pushed any more; false: an input reverted to never-pushed.
+public sealed record ScriptedAlarmInputsEventArgs(string AlarmId, bool Established);
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 27036999e..a30374476 100644
--- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs
+++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmHostActor.cs
@@ -131,6 +131,17 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
private readonly ILoggingAdapter _log = Context.GetLogger();
private readonly CancellationTokenSource _cts = new();
private readonly EventHandler _onEngineEvent;
+ private readonly EventHandler _onInputsEstablished;
+
+ /// A1 (grpc-data §5.1 T2/F2): an engine input-establishment flip, marshaled onto the actor thread on the
+ /// SAME mailbox as (the engine raises it after that evaluation's emissions).
+ private sealed record EngineInputsEstablished(string AlarmId, bool Established);
+
+ // Flips that arrive while a load is in flight wait for that load's re-assert (OnAlarmsLoaded): a LoadAsync fires
+ // its flips before the AlarmsLoaded pipe-back, and marking a re-materialised node known before the re-assert of
+ // its persisted non-normal state lands would be a falsely-normal known (T2). Latest flip per alarm wins.
+ private readonly Dictionary _heldEstablishments = new(StringComparer.Ordinal);
+ private int _loadedGeneration;
private readonly TimeSpan _commandTimeout;
/// True when THIS incarnation built its engine (factory Props) and therefore disposes it on
@@ -306,6 +317,8 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
var self = Self;
_onEngineEvent = (_, e) => self.Tell(new EngineEmission(e));
_engine.OnEvent += _onEngineEvent;
+ _onInputsEstablished = (_, e) => self.Tell(new EngineInputsEstablished(e.AlarmId, e.Established));
+ _engine.OnInputsEstablished += _onInputsEstablished;
Receive(OnApply);
Receive(OnAlarmsLoaded);
@@ -316,6 +329,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
Receive(OnDependencyBatch);
Receive(wake => wake.Consume(items => OnDependencyBatch(new(items))));
Receive(OnEngineEmission);
+ Receive(OnEngineInputsEstablished);
// Cluster redundancy snapshots (published on the `redundancy-state` topic, subscribed in PreStart)
// cache this node's role so OnEngineEmission can gate the cluster-wide alerts publish to the Primary.
Receive(OnRedundancyStateChanged);
@@ -348,6 +362,9 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// applies kick off concurrent LoadAsyncs whose continuations may complete out of order; tagging
// each with its generation lets OnAlarmsLoaded discard any but the latest.
var gen = ++_loadGeneration;
+ // The new load clears the engine's established set and re-raises every flip; any held from the load this one
+ // supersedes would describe that load, not this one.
+ _heldEstablishments.Clear();
// Skip disabled plans entirely — the engine has no Enabled flag, so a disabled alarm is simply
// not loaded (no predicate, no upstream subscription, no events).
@@ -412,8 +429,30 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
msg.DepRefs.Count, dropped);
ReassertConditionNodes();
+
+ // A1: the re-assert above is queued to the publish actor first, so a held "known" lands after it.
+ _loadedGeneration = msg.Generation;
+ foreach (var (alarmId, established) in _heldEstablishments) SendEstablishment(alarmId, established);
+ _heldEstablishments.Clear();
}
+ private void OnEngineInputsEstablished(EngineInputsEstablished msg)
+ {
+ if (_loadedGeneration != _loadGeneration)
+ {
+ _heldEstablishments[msg.AlarmId] = msg.Established;
+ return;
+ }
+
+ SendEstablishment(msg.AlarmId, msg.Established);
+ }
+
+ /// Same actor → publish-actor chain as the s, so the mark is
+ /// applied after every projection this host sent before it (F2). Scripted conditions live in the UNS realm.
+ private void SendEstablishment(string alarmId, bool established) =>
+ _publishActor.Tell(new OpcUaPublishActor.MarkConditionsKnown(
+ OpcUaPublishActor.ScriptedSource, [alarmId], AddressSpaceRealm.Uns, established));
+
///
/// re-project every loaded alarm that is NOT in the Part 9 "no-event" position back onto
/// its condition node, right after a (re)load.
@@ -836,6 +875,7 @@ public sealed class ScriptedAlarmHostActor : ReceiveActor
// re-attach to (R02:H1).
_cts.Cancel();
_engine.OnEvent -= _onEngineEvent;
+ _engine.OnInputsEstablished -= _onInputsEstablished;
if (_ownsEngine || !_restarting) _engine.Dispose();
_cts.Dispose();
base.PostStop();
diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineInputsEstablishedTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineInputsEstablishedTests.cs
new file mode 100644
index 000000000..a5f58cf00
--- /dev/null
+++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineInputsEstablishedTests.cs
@@ -0,0 +1,115 @@
+using System.Collections.Concurrent;
+using Serilog;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
+using ZB.MOM.WW.OtOpcUa.Core.Scripting;
+
+namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests;
+
+///
+/// A1 (grpc-data plan §5.1 T2/F2): — a scripted condition is
+/// known only when none of its inputs is still never-pushed, the flip fires after that evaluation's own emission,
+/// and an input reverting to never-pushed withdraws it.
+///
+[Trait("Feature", "GrpcData")]
+[Trait("Phase", "A1")]
+[Trait("Category", "Unit")]
+public sealed class ScriptedAlarmEngineInputsEstablishedTests
+{
+ private const string Predicate = """return (int)ctx.GetTag("Temp").Value > 100;""";
+ private static CancellationToken Ct => TestContext.Current.CancellationToken;
+
+ private static (ScriptedAlarmEngine Engine, ConcurrentQueue Log) Build(FakeUpstream up)
+ {
+ var logger = new LoggerConfiguration().CreateLogger();
+ var engine = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
+ var log = new ConcurrentQueue();
+ engine.OnEvent += (_, e) => log.Enqueue($"emit:{e.AlarmId}:{e.Emission}");
+ engine.OnInputsEstablished += (_, e) => log.Enqueue($"inputs:{e.AlarmId}:{e.Established}");
+ return (engine, log);
+ }
+
+ private static ScriptedAlarmDefinition Alarm(string id) => new(
+ AlarmId: id, EquipmentPath: "Plant/Line1/Reactor", AlarmName: id, Kind: AlarmKind.AlarmCondition,
+ Severity: AlarmSeverity.High, MessageTemplate: "hot", PredicateScriptSource: Predicate);
+
+ /// T2 (i): a standing alarm whose input arrives late ⇒ nothing says "established" before the first real
+ /// evaluation, and the flip follows that evaluation's Active emission.
+ [Fact]
+ public async Task A_late_input_is_established_only_after_the_first_real_evaluation_and_after_its_emission()
+ {
+ var up = new FakeUpstream();
+ var (engine, log) = Build(up);
+ using var _ = engine;
+ await engine.LoadAsync([Alarm("a1")], Ct);
+ log.ShouldBeEmpty(); // input never pushed: no known-inactive
+
+ up.Push("Temp", 150);
+ await WaitForAsync(() => log.Count >= 2);
+
+ log.ShouldBe(["emit:a1:Activated", "inputs:a1:True"]);
+ }
+
+ [Fact]
+ public async Task An_input_seeded_at_load_is_established_at_load_after_the_load_emission()
+ {
+ var up = new FakeUpstream();
+ up.Set("Temp", 150);
+ var (engine, log) = Build(up);
+ using var _ = engine;
+ await engine.LoadAsync([Alarm("a1")], Ct);
+
+ log.Last().ShouldBe("inputs:a1:True");
+ log.Count(l => l.StartsWith("inputs:", StringComparison.Ordinal)).ShouldBe(1);
+ }
+
+ /// An input reverting to never-pushed (a tag re-created by a deploy) makes the condition unknown again; its
+ /// next real value re-establishes it.
+ [Fact]
+ public async Task An_input_reverting_to_never_pushed_withdraws_and_a_new_value_reestablishes()
+ {
+ var up = new FakeUpstream();
+ up.Set("Temp", 50);
+ var (engine, log) = Build(up);
+ using var _ = engine;
+ await engine.LoadAsync([Alarm("a1")], Ct);
+ log.ShouldBe(["inputs:a1:True"]);
+
+ up.Push("Temp", null, FakeUpstream.StatusNeverPushed);
+ await WaitForAsync(() => log.Count >= 2);
+ log.Last().ShouldBe("inputs:a1:False");
+
+ up.Push("Temp", 60);
+ await WaitForAsync(() => log.Count >= 3);
+ log.Last().ShouldBe("inputs:a1:True");
+
+ // Repeats are silent: another value with inputs still established raises nothing new.
+ up.Push("Temp", 70);
+ await Task.Delay(200, Ct);
+ log.Count.ShouldBe(3);
+ }
+
+ [Fact]
+ public async Task A_reload_reraises_the_flip_for_every_established_alarm()
+ {
+ var up = new FakeUpstream();
+ up.Set("Temp", 50);
+ var (engine, log) = Build(up);
+ using var _ = engine;
+ await engine.LoadAsync([Alarm("a1")], Ct);
+ await engine.LoadAsync([Alarm("a1")], Ct);
+
+ log.Count(l => l == "inputs:a1:True").ShouldBe(2);
+ }
+
+ private static async Task WaitForAsync(Func cond, int timeoutMs = 3000)
+ {
+ var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);
+ while (!cond())
+ {
+ if (DateTime.UtcNow > deadline) throw new TimeoutException("condition not met");
+ await Task.Delay(10, Ct);
+ }
+ }
+}
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
new file mode 100644
index 000000000..bc0d6a1a4
--- /dev/null
+++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ScriptedAlarms/ScriptedAlarmHostInputsEstablishedTests.cs
@@ -0,0 +1,88 @@
+using Akka.Actor;
+using Akka.TestKit;
+using Serilog;
+using Shouldly;
+using Xunit;
+using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
+using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
+using ZB.MOM.WW.OtOpcUa.Core.Scripting;
+using ZB.MOM.WW.OtOpcUa.OpcUaServer;
+using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
+using ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms;
+using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
+using ZB.MOM.WW.OtOpcUa.Runtime.VirtualTags;
+
+namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.ScriptedAlarms;
+
+///
+/// A1 (grpc-data plan §5.1 T2/F2): reaches the publish actor as
+/// on the same chain as the host's
+/// s — after the projection it summarises, and after the post-load
+/// re-assert when it was raised by a (re)load.
+///
+[Trait("Feature", "GrpcData")]
+[Trait("Phase", "A1")]
+[Trait("Category", "Unit")]
+public sealed class ScriptedAlarmHostInputsEstablishedTests : RuntimeActorTestBase
+{
+ private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
+ private static CancellationToken Ct => TestContext.Current.CancellationToken;
+
+ private static EquipmentScriptedAlarmPlan Plan() => new(
+ ScriptedAlarmId: "alm-1", EquipmentId: "Plant/Line1/M", Name: "HighTemp", AlarmType: "AlarmCondition",
+ Severity: 800, MessageTemplate: "condition", PredicateScriptId: "alm-1-script",
+ 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)
+ {
+ var upstream = new DependencyMuxTagUpstreamSource();
+ var logger = new LoggerConfiguration().CreateLogger();
+ var engine = new ScriptedAlarmEngine(upstream, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger);
+ return Sys.ActorOf(ScriptedAlarmHostActor.Props(publish.Ref, mux.Ref, upstream, engine, null));
+ }
+
+ /// T2 (i) at the host: the input arrives late ⇒ no mark before the first real evaluation; then the Active
+ /// projection, then the mark.
+ [Fact]
+ public void A_late_input_marks_the_condition_known_after_its_Active_projection()
+ {
+ var publish = CreateTestProbe();
+ var mux = CreateTestProbe();
+ var host = Spawn(publish, mux);
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()]));
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+ publish.ExpectNoMsg(TimeSpan.FromMilliseconds(300), Ct); // never-pushed input: no known-inactive
+
+ host.Tell(new VirtualTagActor.DependencyValueChanged("M.T", 99, DateTime.UtcNow));
+
+ publish.ExpectMsg(Timeout, cancellationToken: Ct).State.Active.ShouldBeTrue();
+ var mark = publish.ExpectMsg(Timeout, cancellationToken: Ct);
+ mark.ConditionIds.ShouldBe(["alm-1"]);
+ mark.Realm.ShouldBe(AddressSpaceRealm.Uns);
+ mark.Source.ShouldBe(OpcUaPublishActor.ScriptedSource);
+ mark.Known.ShouldBeTrue();
+ }
+
+ /// T2 (iv), scripted: a reload (what follows a rebuild that re-created the condition unknown) re-raises the
+ /// flip from inside LoadAsync — before the load pipes back — but the mark is held until the post-load re-assert of
+ /// the still-active condition has been sent, so it never lands on the freshly materialised (inactive) node.
+ [Fact]
+ public void A_reload_holds_the_mark_until_after_the_reassert()
+ {
+ var publish = CreateTestProbe();
+ var mux = CreateTestProbe();
+ var host = Spawn(publish, mux);
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()]));
+ mux.ExpectMsg(Timeout, cancellationToken: Ct);
+ host.Tell(new VirtualTagActor.DependencyValueChanged("M.T", 99, DateTime.UtcNow));
+ publish.ExpectMsg(Timeout, cancellationToken: Ct);
+ publish.ExpectMsg(Timeout, cancellationToken: Ct);
+
+ host.Tell(new ScriptedAlarmHostActor.ApplyScriptedAlarms([Plan()]));
+
+ var reassert = publish.ExpectMsg(Timeout, cancellationToken: Ct);
+ reassert.State.Active.ShouldBeTrue();
+ publish.ExpectMsg(Timeout, cancellationToken: Ct).ConditionIds.ShouldBe(["alm-1"]);
+ }
+}