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]); } }