fix(scripted-alarms): #995 K-3 a deploy reuses unchanged alarm predicates and compiles new ones outside the engine gate

Every LoadAsync cleared the compile cache and recompiled every predicate serially while holding _evalGate
(and, uncontended, on the ScriptedAlarmHostActor thread). Now the compile phase runs first on the thread
pool (bounded parallelism) without the gate, reusing source-hash-cached compiles; only the swap holds the
gate, and CompiledScriptCache.RetainOnly disposes just the retired predicates' ALCs. Out of process the
host's validation compile is remembered per source too.

Measured, 500 alarms (distinct predicates, in process, Release): reload of unchanged defs 1303 ms -> 15 ms;
one edited 1040 -> 16 ms; all-new reload 1002 -> 748 ms; ack issued during that reload waited 800 -> 1 ms.
This commit is contained in:
Joseph Doherty
2026-12-03 10:54:10 -05:00
parent 6822fd3f5c
commit e99df14665
6 changed files with 437 additions and 19 deletions
@@ -0,0 +1,169 @@
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;
/// <summary>
/// #995 K-3 — every deploy runs <see cref="ScriptedAlarmEngine.LoadAsync"/>. 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.
/// </summary>
[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);
}
/// <summary>A reload of the same definitions compiles nothing; positive control: the first load compiled each.</summary>
[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);
}
/// <summary>An edited predicate compiles once; the retired source is dropped (its ALC released), the rest kept.</summary>
[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);
}
/// <summary>A compile failure still fails the load, and is retried (not remembered) on the next load.</summary>
[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<InvalidOperationException>(() => eng.LoadAsync([Alarm("a0", 1), bad], Ct));
var afterFirst = eng.PredicateCompileCount;
await Should.ThrowAsync<InvalidOperationException>(() => eng.LoadAsync([Alarm("a0", 1), bad], Ct));
// a0 reused, the bad source tried again.
(eng.PredicateCompileCount - afterFirst).ShouldBe(1);
}
/// <summary>
/// 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).
/// </summary>
[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);
}
/// <summary>Out of process the host validation compile is skipped for an unchanged predicate.</summary>
[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<InvalidOperationException>(() => eng.LoadAsync([.. edited, bad], Ct));
}
private sealed class FalseRunner : IScriptRunner
{
public Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
=> Task.FromResult(ScriptRunOutcome.Ok(false));
public void Reset(ScriptContextKind kind) { }
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
}
}