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;
///
/// #995 K-3 — every deploy runs . It used to clear the compile cache and
/// recompile every predicate one at a time while holding the engine gate, so a deploy that touched no alarm stalled
/// every evaluation and operator command for the whole compile. Now unchanged predicates are reused (keyed by source
/// hash), new ones compile outside the gate, and only the swap holds it.
///
[Trait("Category", "Unit")]
public sealed class ScriptedAlarmEngineCompileReuseTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static ScriptedAlarmDefinition Alarm(string id, int threshold) => new(
AlarmId: id, EquipmentPath: "Plant/Line1/Reactor", AlarmName: id, Kind: AlarmKind.AlarmCondition,
Severity: AlarmSeverity.High, MessageTemplate: "over",
PredicateScriptSource: $"return (int)ctx.GetTag(\"Temp\").Value > {threshold};");
private static ScriptedAlarmDefinition[] Defs(int n) =>
[.. Enumerable.Range(0, n).Select(i => Alarm($"a{i}", 100 + i))];
private static ScriptedAlarmEngine Build(FakeUpstream up, IScriptRunner? runner = null)
{
var logger = new LoggerConfiguration().CreateLogger();
return new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger,
scriptRunner: runner);
}
/// A reload of the same definitions compiles nothing; positive control: the first load compiled each.
[Fact]
public async Task Reload_of_unchanged_definitions_compiles_nothing()
{
var up = new FakeUpstream();
up.Set("Temp", 0);
using var eng = Build(up);
var defs = Defs(5);
await eng.LoadAsync(defs, Ct);
eng.PredicateCompileCount.ShouldBe(5); // positive control: the counter does count compiles
await eng.LoadAsync(defs, Ct);
await eng.LoadAsync(defs, Ct);
eng.PredicateCompileCount.ShouldBe(5);
eng.CachedPredicateCount.ShouldBe(5);
eng.LoadedAlarmIds.Count.ShouldBe(5);
}
/// An edited predicate compiles once; the retired source is dropped (its ALC released), the rest kept.
[Fact]
public async Task Edited_predicate_compiles_only_itself_and_retires_its_old_source()
{
var up = new FakeUpstream();
up.Set("Temp", 150);
using var eng = Build(up);
var defs = Defs(5);
await eng.LoadAsync(defs, Ct);
var edited = defs.ToArray();
edited[2] = Alarm("a2", 500);
await eng.LoadAsync(edited, Ct);
eng.PredicateCompileCount.ShouldBe(6);
eng.CachedPredicateCount.ShouldBe(5);
// The new predicate is the one that runs: 150 > 500 is false, the others (100..104) are true.
eng.GetState("a2")!.Active.ShouldBe(AlarmActiveState.Inactive);
eng.GetState("a1")!.Active.ShouldBe(AlarmActiveState.Active);
// Removing alarms drops their compiles.
await eng.LoadAsync(edited.Take(2).ToArray(), Ct);
eng.CachedPredicateCount.ShouldBe(2);
eng.PredicateCompileCount.ShouldBe(6);
}
/// A compile failure still fails the load, and is retried (not remembered) on the next load.
[Fact]
public async Task Compile_failure_still_fails_the_load_and_is_retried()
{
var up = new FakeUpstream();
using var eng = Build(up);
var bad = new ScriptedAlarmDefinition("bad", "P", "bad", AlarmKind.AlarmCondition, AlarmSeverity.High, "m",
"return nope;");
await Should.ThrowAsync(() => eng.LoadAsync([Alarm("a0", 1), bad], Ct));
var afterFirst = eng.PredicateCompileCount;
await Should.ThrowAsync(() => eng.LoadAsync([Alarm("a0", 1), bad], Ct));
// a0 reused, the bad source tried again.
(eng.PredicateCompileCount - afterFirst).ShouldBe(1);
}
///
/// An operator acknowledge issued while a reload is compiling completes without waiting for the compile, and
/// its effect survives the swap (carried over like any other survivor state).
///
[Fact]
public async Task Acknowledge_completes_while_a_reload_is_compiling()
{
var up = new FakeUpstream();
up.Set("Temp", 150);
using var eng = Build(up);
await eng.LoadAsync([Alarm("a0", 100)], Ct);
eng.GetState("a0")!.Active.ShouldBe(AlarmActiveState.Active);
eng.GetState("a0")!.Acked.ShouldBe(AlarmAckedState.Unacknowledged);
using var entered = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
eng.CompilePhaseHookForTests = () =>
{
entered.Set();
release.Wait(TimeSpan.FromSeconds(30));
};
var reload = Task.Run(() => eng.LoadAsync([Alarm("a0", 100), Alarm("a1", 120)], Ct), Ct);
entered.Wait(TimeSpan.FromSeconds(10), Ct).ShouldBeTrue();
var ack = eng.AcknowledgeAsync("a0", "op", null, Ct);
var finished = await Task.WhenAny(ack, Task.Delay(TimeSpan.FromSeconds(5), Ct));
finished.ShouldBe(ack, "the ack must not queue behind the reload's compile phase");
await ack;
reload.IsCompleted.ShouldBeFalse();
release.Set();
await reload;
eng.LoadedAlarmIds.ShouldContain("a1");
eng.GetState("a0")!.Acked.ShouldBe(AlarmAckedState.Acknowledged);
}
/// Out of process the host validation compile is skipped for an unchanged predicate.
[Fact]
public async Task Out_of_process_validation_compile_is_not_repeated_for_unchanged_predicates()
{
var up = new FakeUpstream();
up.Set("Temp", 0);
using var eng = Build(up, new FalseRunner());
var defs = Defs(3);
await eng.LoadAsync(defs, Ct);
eng.HostValidationCompileCount.ShouldBe(3);
await eng.LoadAsync(defs, Ct);
eng.HostValidationCompileCount.ShouldBe(3);
var edited = defs.ToArray();
edited[0] = Alarm("a0", 999);
await eng.LoadAsync(edited, Ct);
eng.HostValidationCompileCount.ShouldBe(4);
eng.PredicateCompileCount.ShouldBe(0); // nothing is loaded into the host out of process
// A broken predicate still fails the load out of process.
var bad = new ScriptedAlarmDefinition("bad", "P", "bad", AlarmKind.AlarmCondition, AlarmSeverity.High, "m",
"return nope;");
await Should.ThrowAsync(() => eng.LoadAsync([.. edited, bad], Ct));
}
private sealed class FalseRunner : IScriptRunner
{
public Task RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
=> Task.FromResult(ScriptRunOutcome.Ok(false));
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection QuarantinedKeys(ScriptContextKind kind) => [];
}
}