From 626d0b33c525de3c762808f3787fd2e7bec0bd19 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:39:17 -0500 Subject: [PATCH] fix(alarms): #999 K-4 a timed shelve expiring on a predicate evaluation emits Unshelved + AutoUnshelve audit --- docs/ScriptedAlarms.md | 2 +- .../Part9StateMachine.cs | 18 ++- .../ScriptedAlarmEngine.cs | 26 ++-- .../Part9StateMachineTests.cs | 12 ++ ...riptedAlarmEngineTimedShelveExpiryTests.cs | 115 ++++++++++++++++++ 5 files changed, 154 insertions(+), 19 deletions(-) create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTimedShelveExpiryTests.cs diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index 531281c6a..8189f87c3 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -122,7 +122,7 @@ rationale is recorded in the engine's class doc so it is not re-proposed: - `ApplyOneShotShelve` / `ApplyTimedShelve(unshelveAtUtc)` / `ApplyUnshelve` — shelving transitions. `Timed` requires `unshelveAtUtc > nowUtc`. - `ApplyEnable` / `ApplyDisable` — operator enable/disable. Disabled alarms ignore predicate results until re-enabled; on enable, `ActiveState` is re-derived from the next evaluation. - `ApplyAddComment(text)` — append-only audit entry, no state change. -- `ApplyShelvingCheck(nowUtc)` — called by the 5s timer; promotes expired `Timed` shelving to `Unshelved` with a `system / AutoUnshelve` audit entry. The sole owner of timed-shelve expiry — the OPC UA node's own SDK timer does nothing. +- `ApplyShelvingCheck(nowUtc)` — called by the 5s timer **and by the engine before every completed predicate evaluation** (serial and out-of-process batch paths, and at load); promotes expired `Timed` shelving to `Unshelved` with a `system / AutoUnshelve` audit entry and an `Unshelved` emission queued ahead of the predicate's own transition. The sole owner of timed-shelve expiry — the OPC UA node's own SDK timer does nothing, and `ApplyPredicate` no longer expires a timed shelve itself (#999 / review K-4: an input push that crossed the deadline before the timer used to unshelve the alarm silently — no event, no audit, the node stuck at TimedShelved). - `ApplyAcknowledge` on an already-acknowledged alarm is a no-op **unless it carries a comment**, which is recorded as an `AddComment` (emission `CommentAdded`; `LastAck*` untouched) — the OPC UA node reports a commented re-ack, so the system of record must hold the comment too. Two invariants the machine enforces: diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs index 10678f1ca..0f2bc981c 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/Part9StateMachine.cs @@ -22,7 +22,8 @@ namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; /// (2) Shelved alarms (OneShot / Timed) don't fire active transitions to /// subscribers, but the state record still advances so that when shelving /// expires the ActiveState reflects current reality. OneShot expires on the -/// next clear; Timed expires at . +/// next clear; Timed expires at , and only through +/// (#999 / K-4) — never inside . /// /// public static class Part9StateMachine @@ -44,8 +45,10 @@ public static class Part9StateMachine if (current.Enabled == AlarmEnabledState.Disabled) return TransitionResult.NoOp(current, "disabled — predicate result ignored"); - // Expire timed shelving if the configured clock has passed. - var shelving = MaybeExpireShelving(current.Shelving, nowUtc); + // #999 / review K-4: a timed shelve is NOT expired here. Expiry belongs to ApplyShelvingCheck alone (it carries + // the AutoUnshelve audit comment and the Unshelved emission); the engine runs it before this call. Expiring it + // here returned EmissionKind.None — the alarm unshelved with no event and no audit. + var shelving = current.Shelving; var stateWithShelving = current with { Shelving = shelving }; // Shelved alarms still update state but skip event emission. @@ -84,8 +87,7 @@ public static class Part9StateMachine return new TransitionResult(next, shelved ? EmissionKind.Suppressed : EmissionKind.Cleared); } - // Predicate matches current Active — no state change beyond possible shelving - // expiry. + // Predicate matches current Active — no state change. return new TransitionResult(stateWithShelving, EmissionKind.None); } @@ -325,12 +327,6 @@ public static class Part9StateMachine return TransitionResult.None(current); } - private static ShelvingState MaybeExpireShelving(ShelvingState s, DateTime nowUtc) - { - if (s.Kind != ShelvingKind.Timed) return s; - return s.UnshelveAtUtc is DateTime t && nowUtc >= t ? ShelvingState.Unshelved : s; - } - private static ImmutableList AppendComment( ImmutableList existing, DateTime ts, string user, string kind, string? text) => existing.Add(new AlarmComment(ts, user, kind, text ?? string.Empty)); 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 557141ddc..2e65df07a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs @@ -508,7 +508,7 @@ public sealed class ScriptedAlarmEngine : IDisposable foreach (var (alarmId, state) in _alarms) { var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false); - var evalSeed = ExpireTimedShelveAtLoad(state, seed.State, pending); + var evalSeed = ExpireTimedShelve(state, seed.State, _clock(), pending); var afterPredicate = await EvaluatePredicateToStateAsync(state, evalSeed, nowUtc: _clock(), ct, pending) .ConfigureAwait(false); await SaveLoadedAsync(seed, afterPredicate, ct).ConfigureAwait(false); @@ -525,7 +525,7 @@ public sealed class ScriptedAlarmEngine : IDisposable { var seed = await SeedAsync(alarmId, state, carryOver, ct).ConfigureAwait(false); sources.Add(seed); - seeds.Add((state, ExpireTimedShelveAtLoad(state, seed.State, pending))); + seeds.Add((state, ExpireTimedShelve(state, seed.State, _clock(), pending))); } var after = await EvaluatePredicateBatchToStatesAsync(seeds, _clock(), ct, pending).ConfigureAwait(false); for (var i = 0; i < seeds.Count; i++) @@ -605,10 +605,16 @@ public sealed class ScriptedAlarmEngine : IDisposable /// predicate runs. Otherwise 's own expiry silently unshelved it /// (no audit entry, no event) and the shelving timer found nothing left to expire. /// - private AlarmConditionState ExpireTimedShelveAtLoad( - AlarmState state, AlarmConditionState seed, List pendingEmissions) + /// + /// #999 / review K-4: the same expiry runs before every completed predicate evaluation (serial and batch paths), + /// not only at load — a push that crossed the deadline before the 5 s shelving timer otherwise unshelved the alarm + /// silently and the OPC UA node stayed TimedShelved. no longer + /// expires a timed shelve itself, so the shelving check is the only place one expires. + /// + private AlarmConditionState ExpireTimedShelve( + AlarmState state, AlarmConditionState seed, DateTime nowUtc, List pendingEmissions) { - var check = Part9StateMachine.ApplyShelvingCheck(seed, _clock()); + var check = Part9StateMachine.ApplyShelvingCheck(seed, nowUtc); if (check.Emission == EmissionKind.None) return seed; var evt = BuildEmission(state, check.State, check.Emission, LastWorstStatus(state.Definition.AlarmId)); if (evt is not null) pendingEmissions.Add(evt); @@ -1109,7 +1115,10 @@ public sealed class ScriptedAlarmEngine : IDisposable // QualityChanged on every push instead of once per real bucket change. var qualityBucketChanged = TrackQualityBucket(state.Definition.AlarmId, worstStatus); - var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc); + // #999 / K-4: an expired timed shelve is unshelved by the shelving check (Unshelved event + AutoUnshelve audit), + // queued BEFORE the predicate's own transition, never silently inside ApplyPredicate. + var result = Part9StateMachine.ApplyPredicate( + ExpireTimedShelve(state, seed, nowUtc, pendingEmissions), predicateTrue, nowUtc); var transition = result.Emission != EmissionKind.None ? BuildEmission(state, result.State, result.Emission, worstStatus, captured) : null; @@ -1285,7 +1294,10 @@ public sealed class ScriptedAlarmEngine : IDisposable // 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); - var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc); + // #999 / K-4: an expired timed shelve is unshelved by the shelving check (Unshelved event + AutoUnshelve audit), + // queued BEFORE the predicate's own transition, never silently inside ApplyPredicate. + var result = Part9StateMachine.ApplyPredicate( + ExpireTimedShelve(state, seed, nowUtc, pendingEmissions), predicateTrue, nowUtc); var transition = result.Emission != EmissionKind.None ? BuildEmission(state, result.State, result.Emission, worstStatus, captured) : null; diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/Part9StateMachineTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/Part9StateMachineTests.cs index dd8ea3b7f..3c86346aa 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/Part9StateMachineTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/Part9StateMachineTests.cs @@ -174,6 +174,18 @@ public sealed class Part9StateMachineTests after.State.Comments.Any(c => c.Kind == "AutoUnshelve").ShouldBeTrue(); } + /// #999 / K-4: ApplyPredicate never expires a timed shelve itself — that would unshelve silently. + [Fact] + public void ApplyPredicate_does_not_expire_a_timed_shelve() + { + var active = Part9StateMachine.ApplyPredicate(Fresh(), true, T0.AddSeconds(1)).State; + var shelved = Part9StateMachine.ApplyTimedShelve(active, "alice", T0.AddMinutes(5), T0.AddSeconds(2)).State; + + var r = Part9StateMachine.ApplyPredicate(shelved, true, T0.AddMinutes(6)); + r.State.Shelving.Kind.ShouldBe(ShelvingKind.Timed, "expiry is ApplyShelvingCheck's alone"); + r.Emission.ShouldBe(EmissionKind.None); + } + /// Verifies that unshelving an unshelved alarm is a no-op. [Fact] public void Unshelve_from_unshelved_is_noop() diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTimedShelveExpiryTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTimedShelveExpiryTests.cs new file mode 100644 index 000000000..829610ba4 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineTimedShelveExpiryTests.cs @@ -0,0 +1,115 @@ +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; + +/// +/// #999 / review K-4 — a timed shelve whose deadline passes is unshelved by a predicate evaluation that +/// arrives before the 5 s shelving timer. It must be the shelving check that expires it, so the evaluation emits +/// exactly one and records exactly one AutoUnshelve audit comment +/// (before the fix ApplyPredicate unshelved it silently: no event, no audit, the OPC UA node stayed +/// TimedShelved). Covered on both the in-process path and the batch path. +/// +[Trait("Category", "Unit")] +public sealed class ScriptedAlarmEngineTimedShelveExpiryTests +{ + private sealed class ThresholdRunner : IScriptRunner + { + private static ScriptRunOutcome Answer(ScriptInvocation i) => ScriptRunOutcome.Ok((int)i.Inputs["Temp"].Value! > 100); + + public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default) + => Task.FromResult(Answer(invocation)); + + public IReadOnlyList> RunBatch(IReadOnlyList invocations, CancellationToken ct = default) + => invocations.Select(i => Task.FromResult(Answer(i))).ToArray(); + + public void Reset(ScriptContextKind kind) { } + + public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => []; + } + + private static async Task WaitFor(Func probe, string what) + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (DateTime.UtcNow < deadline) + { + if (probe()) return; + await Task.Delay(10); + } + throw new TimeoutException(what); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_predicate_evaluation_after_the_deadline_emits_Unshelved_and_audits_AutoUnshelve(bool outOfProcess) + { + var ct = TestContext.Current.CancellationToken; + var now = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc); + var up = new FakeUpstream(); + up.Set("Temp", 150); + var logger = new LoggerConfiguration().CreateLogger(); + using var eng = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, + clock: () => now, scriptRunner: outOfProcess ? new ThresholdRunner() : null); + await eng.LoadAsync( + [new ScriptedAlarmDefinition("HighTemp", "Plant/Line1/Reactor", "HighTemp", AlarmKind.AlarmCondition, + AlarmSeverity.High, "condition", """return (int)ctx.GetTag("Temp").Value > 100;""")], + ct); + eng.GetState("HighTemp")!.Active.ShouldBe(AlarmActiveState.Active); + + await eng.TimedShelveAsync("HighTemp", "alice", now.AddMinutes(10), ct); + var events = new List(); + eng.OnEvent += (_, e) => { lock (events) events.Add(e); }; + + // Past the deadline; the input moves but the predicate stays true, so the only possible transition is the + // expiry. The shelving check is NOT run — the evaluation alone has to surface it. + now = now.AddMinutes(11); + up.Push("Temp", 160); + + await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Unshelved); }, + "the evaluation that crossed the deadline emitted Unshelved"); + var state = eng.GetState("HighTemp")!; + state.Shelving.Kind.ShouldBe(ShelvingKind.Unshelved); + state.Active.ShouldBe(AlarmActiveState.Active); + state.Comments.Count(c => c.Kind == "AutoUnshelve").ShouldBe(1); + + // The shelving timer, running afterwards, finds nothing left to expire: still exactly one event. + eng.RunShelvingCheckForTest(); + await WaitFor(() => eng.InFlightCountForTest == 0, "shelving check finished"); + // Positive control: a later clear does arrive, so an absent second Unshelved is not just "not processed yet". + up.Push("Temp", 50); + await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Cleared); }, "clear arrives"); + lock (events) events.Count(e => e.Emission == EmissionKind.Unshelved).ShouldBe(1); + eng.GetState("HighTemp")!.Comments.Count(c => c.Kind == "AutoUnshelve").ShouldBe(1); + } + + [Fact] + public async Task An_activation_that_crosses_the_deadline_emits_Unshelved_then_Activated() + { + var ct = TestContext.Current.CancellationToken; + var now = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc); + var up = new FakeUpstream(); + up.Set("Temp", 50); + var logger = new LoggerConfiguration().CreateLogger(); + using var eng = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger, + clock: () => now); + await eng.LoadAsync( + [new ScriptedAlarmDefinition("HighTemp", "Plant/Line1/Reactor", "HighTemp", AlarmKind.AlarmCondition, + AlarmSeverity.High, "condition", """return (int)ctx.GetTag("Temp").Value > 100;""")], + ct); + await eng.TimedShelveAsync("HighTemp", "alice", now.AddMinutes(10), ct); + var events = new List(); + eng.OnEvent += (_, e) => { lock (events) events.Add(e); }; + + now = now.AddMinutes(11); + up.Push("Temp", 150); + + await WaitFor(() => { lock (events) return events.Any(e => e.Emission == EmissionKind.Activated); }, + "activation after expiry is not suppressed"); + lock (events) + events.Select(e => e.Emission).ShouldBe([EmissionKind.Unshelved, EmissionKind.Activated]); + } +}