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 1c339d8f2..d66c3a117 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs @@ -322,18 +322,20 @@ public sealed class ScriptedAlarmEngine : IDisposable /// /// 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. + /// () to its FIRST COMPLETED predicate evaluation — its condition state is now + /// ESTABLISHED — or back ( false: an input reverted to + /// never-pushed, e.g. a tag re-created by a deploy). "Established" is raised only after a predicate actually + /// completed (review S1): never while an input is Bad, the runner is not up, or the predicate timed out, was + /// refused or threw. Raised the first time after each / revert, 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; + // A1: the alarms whose state is established (a predicate completed since the last load / revert). 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); + private readonly HashSet _inputsEstablished = new(StringComparer.Ordinal); /// Gets the collection of loaded alarm identifiers. public IReadOnlyCollection LoadedAlarmIds => _alarms.Keys.ToArray(); @@ -909,7 +911,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); + NoteInputsReverted(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; @@ -978,6 +980,7 @@ public sealed class ScriptedAlarmEngine : IDisposable if (captured.Evidence is { IsValid: false }) return seed; MirrorPredicate(state, scratch, ScriptRunOutcome.Ok(predicateTrue)); scratch.LastNonCompletion = null; + NoteEvaluationCompleted(state.Definition.AlarmId, pendingEmissions); // Track the bucket only once the predicate has COMPLETED (I3). The tracked bucket is the last // bucket this alarm was annotated with; tracking the input bucket before the attempt flipped it to @@ -1068,7 +1071,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); + NoteInputsReverted(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 }) @@ -1157,6 +1160,7 @@ public sealed class ScriptedAlarmEngine : IDisposable return seed; } scratch.LastNonCompletion = null; + NoteEvaluationCompleted(state.Definition.AlarmId, pendingEmissions); // From here on, identical to the serial path: the bucket is tracked only once the predicate completed (I3). var qualityBucketChanged = TrackQualityBucket(state.Definition.AlarmId, worstStatus); @@ -1385,22 +1389,30 @@ 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, + /// A1 (review S1): withdraw "established" from when one of its inputs reverted to + /// never-pushed (e.g. a tag re-created by a deploy). Only called under _evalGate; the flip is fired after every + /// emission in the caller's pending list. + private void NoteInputsReverted(string alarmId, IReadOnlyDictionary cache, List pendingEmissions) { - var established = true; + if (!_inputsEstablished.Contains(alarmId)) return; // not established: an unknown condition is already unknown foreach (var v in cache.Values) { - if (v is null || v.StatusCode == StatusNeverPushed) { established = false; break; } + if (v is not null && v.StatusCode != StatusNeverPushed) continue; + _inputsEstablished.Remove(alarmId); + if (pendingEmissions is PendingEmissions pending) pending.Establishments.Add((alarmId, false)); + return; } + } - 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)); + /// A1 (review S1): a predicate evaluation of COMPLETED — its inputs were ready + /// (none never-pushed, none Bad), its evidence valid and its predicate returned a bool — so the condition's state is + /// established. Raised once per load / revert, never on a Bad input, a refused or timed-out predicate or a runner + /// that was not up. Only called under _evalGate. + private void NoteEvaluationCompleted(string alarmId, List pendingEmissions) + { + if (!_inputsEstablished.Add(alarmId)) return; + if (pendingEmissions is PendingEmissions pending) pending.Establishments.Add((alarmId, true)); } /// Fire a caller's pending emissions, then (A1 F2) its input-establishment flips — last. 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 index a5f58cf00..0700c671d 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineInputsEstablishedTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineInputsEstablishedTests.cs @@ -103,6 +103,79 @@ public sealed class ScriptedAlarmEngineInputsEstablishedTests log.Count(l => l == "inputs:a1:True").ShouldBe(2); } + // ---------------------------------------------------------------- review S1: established = a COMPLETED predicate + + private const uint StatusBad = 0x80000000u; + + /// Review S1: an input that is pushed but Bad (driver down) holds the condition; no predicate ran, so the + /// state is not established. The first Good value runs the predicate and only then establishes it. + [Fact] + public async Task A_Bad_input_never_establishes_and_the_first_good_evaluation_does() + { + var up = new FakeUpstream(); + up.Set("Temp", 150, StatusBad); + var (engine, log) = Build(up); + using var _ = engine; + await engine.LoadAsync([Alarm("a1")], Ct); + up.Push("Temp", 150, StatusBad); + await Task.Delay(200, Ct); + log.ShouldNotContain(l => l.StartsWith("inputs:", StringComparison.Ordinal)); + + up.Push("Temp", 150); + await WaitForAsync(() => log.Contains("inputs:a1:True")); + log.Last().ShouldBe("inputs:a1:True"); + log.ShouldContain("emit:a1:Activated"); + } + + /// Review S1: a predicate that times out (or a runner that is not up) never completed, so nothing is + /// established; the first evaluation that completes establishes it. + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_predicate_timeout_or_an_unavailable_runner_never_establishes(bool timeout) + { + var up = new FakeUpstream(); + up.Set("Temp", 150); + var runner = new AnsweringRunner + { + Answer = timeout + ? ScriptRunOutcome.Failed($"{ZB.MOM.WW.OtOpcUa.Commons.Engines.ScriptEvalFailureReasons.TimedOutPrefix}0.2s") + : ScriptRunOutcome.Unavailable(ScriptRunOutcome.WorkerRestartedReason), + }; + var logger = new LoggerConfiguration().CreateLogger(); + using var engine = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, + scriptTimeout: TimeSpan.FromMilliseconds(250), scriptRunner: runner); + var log = new ConcurrentQueue(); + engine.OnEvent += (_, e) => log.Enqueue($"emit:{e.AlarmId}:{e.Emission}"); + engine.OnInputsEstablished += (_, e) => log.Enqueue($"inputs:{e.AlarmId}:{e.Established}"); + + await engine.LoadAsync([Alarm("a1")], Ct); + up.Push("Temp", 160); + await Task.Delay(200, Ct); + log.ShouldNotContain(l => l.StartsWith("inputs:", StringComparison.Ordinal)); + + runner.Answer = ScriptRunOutcome.Ok(true); + up.Push("Temp", 170); + await WaitForAsync(() => log.Contains("inputs:a1:True")); + log.Last().ShouldBe("inputs:a1:True"); + } + + /// A runner that answers every predicate with . + private sealed class AnsweringRunner : IScriptRunner + { + public volatile ScriptRunOutcome Answer = ScriptRunOutcome.Ok(false); + + public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) => + Task.FromResult(Answer); + + public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default) => + invocations.Select(_ => Task.FromResult(Answer)).ToArray(); + + public void Reset(ScriptContextKind kind) { } + + public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; + } + private static async Task WaitForAsync(Func cond, int timeoutMs = 3000) { var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs);