diff --git a/docs/ScriptedAlarms.md b/docs/ScriptedAlarms.md index 32e04c1ac..c1d969520 100644 --- a/docs/ScriptedAlarms.md +++ b/docs/ScriptedAlarms.md @@ -587,7 +587,7 @@ In the v2 actor system, scripted-alarm engine composition is owned by the driver 1. The host reads the generation's `ScriptedAlarm` + `Script` rows and resolves each row's `PredicateScriptId` to produce a `ScriptedAlarmDefinition` list. Unknown or disabled scripts fail fast — the DB publish guarantees referential integrity but this is a belt-and-braces check. 2. A `ScriptedAlarmEngine` is constructed with the upstream-tag source, an `IAlarmStateStore` (production: `LocalDbAlarmConditionStateStore`), a shared `ScriptLoggerFactory` keyed to `scripts-*.log`, and the root Serilog logger. 3. `alarmEngine.OnEvent` is wired to the historian sink. Fire-and-forget — the SQLite store-and-forward sink is already non-blocking. -4. `LoadAsync(alarmDefs)` runs on startup and on every deploy: it compiles every predicate, subscribes to the union of predicate inputs and message-template tokens, seeds the value cache, seeds each alarm's condition (`previous ?? persisted ?? Fresh`, #935), re-derives `ActiveState` from a fresh predicate evaluation, and starts the 5s shelving timer. Compile failures are aggregated into one `InvalidOperationException` so operators see every bad predicate in one startup log line rather than one at a time. +4. `LoadAsync(alarmDefs)` runs on startup and on every deploy: it compiles every predicate whose source it does not already hold (#995 K-3 — the compile cache is keyed by source hash and kept across deploys; a reload drops only the compiles no definition references any more, releasing their collectible ALCs; out of process the host's validation compile is remembered the same way), then subscribes to the union of predicate inputs and message-template tokens, seeds the value cache, seeds each alarm's condition (`previous ?? persisted ?? Fresh`, #935), re-derives `ActiveState` from a fresh predicate evaluation, and starts the 5s shelving timer. Compile failures are aggregated into one `InvalidOperationException` so operators see every bad predicate in one startup log line rather than one at a time. **Compiling runs before the engine gate is taken** (on the thread pool, bounded parallelism), so operator commands and re-evaluations keep running against the live generation while the new one compiles and only the swap holds the gate; a command that lands in that window is carried over by the swap like any other survivor state. Measured (500 alarms, distinct predicates, in process): a reload of unchanged definitions went from ~1.3 s under the gate to ~15 ms, and an acknowledge issued during an all-new reload waited ~1 ms instead of ~0.8 s. 5. A `ScriptedAlarmSource` is created for the event stream. The v2 `ScriptedAlarmActor` (`src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ScriptedAlarms/ScriptedAlarmActor.cs`) owns the active-state surface for OPC UA variable reads on the alarm's condition-state node — unknown alarm ids return `BadNodeIdUnknown` rather than silently reading `false`. Both engine and source are disposed on server shutdown via the driver-role host teardown path. 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..0d73c0ae8 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms/ScriptedAlarmEngine.cs @@ -132,15 +132,26 @@ public sealed class ScriptedAlarmEngine : IDisposable /// calls through the /// cache so the collectible /// each compile produces is actually disposed on the publish-replace path: - /// the cache's - /// disposes every materialised evaluator before dropping its dictionary entry, - /// so a config-publish releases the prior generation's ALCs and the per-publish - /// accretion the prior fix targeted is actually freed in production. + /// the cache's + /// disposes every materialised evaluator no definition of the new generation + /// references before dropping its dictionary entry, so a config-publish releases + /// the retired predicates' ALCs while an unchanged predicate keeps its compile + /// across deploys (#995 K-3 — the cache used to be cleared, so every deploy + /// recompiled every predicate under the gate). /// Pre-fix the engine called ScriptEvaluator.Compile directly, which left /// the ALCs rooted until the process exited — defeating -008 on the real path. /// private readonly CompiledScriptCache _compileCache = new(); + /// + /// #995 K-3, out of process only: predicate sources the host has already validated (compiled to a PE image and + /// dropped), so a deploy that did not edit a predicate does not re-emit it. Pruned to the live definitions on + /// every load. + /// + private readonly ConcurrentDictionary _validatedSources = new(StringComparer.Ordinal); + + private long _hostValidationCompiles; + /// /// Test-only diagnostic: returns the per-alarm scratch read-cache dictionary /// if one has been allocated, else null. Used by regression tests to assert @@ -363,6 +374,10 @@ public sealed class ScriptedAlarmEngine : IDisposable /// compile failures into one , subscribes /// to upstream input tags, seeds the value cache, seeds each alarm's condition, and /// recomputes ActiveState from the current predicate (startup recovery). + /// #995 K-3: compiling happens first, on the thread pool and WITHOUT the engine gate; only the swap + /// (everything below) holds it. A predicate whose source is unchanged since the last load is reused, not + /// recompiled. While the new generation compiles, operator commands and re-evaluations run against the live + /// generation — the swap then carries their result over like any other survivor state (#935). /// #935: the seed is previous ?? persisted ?? Fresh. An alarm id that was loaded in the /// last completed generation of THIS engine incarnation (a redeploy) keeps its in-memory condition, so a /// still-true predicate is a restatement (no emission, Ack/Confirm/LastTransitionUtc unchanged, and no @@ -379,10 +394,18 @@ public sealed class ScriptedAlarmEngine : IDisposable if (_disposed) throw new ObjectDisposedException(nameof(ScriptedAlarmEngine)); if (definitions is null) throw new ArgumentNullException(nameof(definitions)); + // #995 K-3: the compile phase runs OUTSIDE _evalGate and off the caller's thread (the host actor calls this + // straight from its mailbox). Only the swap below takes the gate, so operator commands and evaluations keep + // running against the live generation while the new one compiles, and a reload of unchanged predicates + // compiles nothing (the cache is keyed by source hash and is no longer cleared per load). + var prepared = await Task.Run(() => PreparePredicates(definitions, ct), ct).ConfigureAwait(false); + var pending = new PendingEmissions(); await _evalGate.WaitAsync(ct).ConfigureAwait(false); try { + // A Dispose that ran while this load compiled must not be undone by the swap. + if (_disposed) throw new ObjectDisposedException(nameof(ScriptedAlarmEngine)); _inputsEstablished.Clear(); // Stop the prior shelving timer BEFORE clearing _alarms so no in-progress // tick can observe a half-cleared dictionary. Moving the dispose here also @@ -421,10 +444,6 @@ public sealed class ScriptedAlarmEngine : IDisposable // unsafe. _scratchByAlarmId.Clear(); _lastQualityBucketByAlarmId.Clear(); - // Dispose every compiled-predicate ALC from the prior generation BEFORE we - // recompile this one. Skipping this is what made the earlier fix a - // no-op in production. - _compileCache.Clear(); // A (re)load is a deploy: lift every run-guard quarantine (an edited predicate already lifts // its own through the guard's source identity; this covers "redeployed to retry"). _guard.ResetAll(); @@ -433,17 +452,17 @@ public sealed class ScriptedAlarmEngine : IDisposable lock (_dirtyLock) _recoveryArmed.Clear(); var compileFailures = new List(); - foreach (var def in definitions) + foreach (var prep in prepared) { + var def = prep.Definition; + if (prep.Failure is not null) + { + compileFailures.Add(prep.Failure); + continue; + } try { - var extraction = DependencyExtractor.Extract(def.PredicateScriptSource); - if (!extraction.IsValid) - { - var joined = string.Join("; ", extraction.Rejections.Select(r => r.Message)); - compileFailures.Add($"{def.AlarmId}: dependency extraction rejected — {joined}"); - continue; - } + var extraction = prep.Extraction!; // Route through CompiledScriptCache so the emitted assembly's // collectible ALC participates in publish-replace cleanup. @@ -454,9 +473,13 @@ public sealed class ScriptedAlarmEngine : IDisposable // Out of process (lmxopcua#780) the worker compiles and runs the predicate; here the source is only // compiled to PE bytes and dropped — same Roslyn, sandbox and diagnostics, so a broken predicate still // fails the load exactly as in process — and no assembly is loaded into the host. + // + // #995 K-3: PreparePredicates already compiled (or validated) every source outside the gate, so + // this is a cache hit. It only compiles here when a concurrent load's swap evicted the entry in + // between — correct, just slower for that one race. ScriptEvaluator? evaluator = null; if (_runner is null) evaluator = _compileCache.GetOrCompile(def.PredicateScriptSource); - else _ = ScriptEvaluator.CompileToImage(def.PredicateScriptSource); + else if (!_validatedSources.ContainsKey(def.PredicateScriptSource)) ValidateForWorker(def.PredicateScriptSource); var logger = _loggerFactory.Create(def.AlarmId); var templateTokens = MessageTemplate.ExtractTokenPaths(def.MessageTemplate); @@ -479,6 +502,15 @@ public sealed class ScriptedAlarmEngine : IDisposable } } + // #995 K-3: publish-replace — dispose only the prior generation's compiles that no definition of this one + // references (their collectible ALCs unload) and keep the rest for reuse. _alarms was cleared above, so + // nothing still holds a dropped evaluator. Before the failure throw, so a failed load releases them too. + var liveSources = new HashSet(StringComparer.Ordinal); + foreach (var def in definitions) liveSources.Add(def.PredicateScriptSource); + _compileCache.RetainOnly(liveSources); + foreach (var source in _validatedSources.Keys) + if (!liveSources.Contains(source)) _validatedSources.TryRemove(source, out _); + if (compileFailures.Count > 0) { throw new InvalidOperationException( @@ -564,6 +596,75 @@ public sealed class ScriptedAlarmEngine : IDisposable FirePending(pending); } + /// One definition after the compile phase: its dependency extraction, or why it cannot load. + private sealed record PreparedPredicate( + ScriptedAlarmDefinition Definition, DependencyExtractionResult? Extraction, string? Failure); + + /// + /// #995 K-3: the compile phase of , run OUTSIDE on the thread + /// pool with bounded parallelism. Extracts each predicate's dependencies and compiles it into + /// (in process) or validates it to a PE image (out of process, remembered in + /// so an unchanged predicate is not re-emitted on the next deploy). A source the + /// cache already holds costs a hash and a lookup. Touches no generation state, so it is safe concurrently with + /// evaluations and commands; the result is in definition order. + /// + private PreparedPredicate[] PreparePredicates(IReadOnlyList definitions, CancellationToken ct) + { + CompilePhaseHookForTests?.Invoke(); + var result = new PreparedPredicate[definitions.Count]; + var options = new ParallelOptions + { + CancellationToken = ct, + MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount / 2, 1, 4), + }; + Parallel.For(0, definitions.Count, options, i => + { + var def = definitions[i]; + try + { + var extraction = DependencyExtractor.Extract(def.PredicateScriptSource); + if (!extraction.IsValid) + { + var joined = string.Join("; ", extraction.Rejections.Select(r => r.Message)); + result[i] = new(def, null, $"{def.AlarmId}: dependency extraction rejected — {joined}"); + return; + } + if (_runner is null) _ = _compileCache.GetOrCompile(def.PredicateScriptSource); + else if (!_validatedSources.ContainsKey(def.PredicateScriptSource)) ValidateForWorker(def.PredicateScriptSource); + result[i] = new(def, extraction, null); + } + catch (Exception ex) + { + result[i] = new(def, null, $"{def.AlarmId}: {ex.Message}"); + } + }); + return result; + } + + /// + /// Out of process (lmxopcua#780) the worker compiles and runs the predicate; the host only compiles it to PE bytes + /// and drops them — same Roslyn, sandbox and diagnostics, so a broken predicate still fails the load exactly as in + /// process. A source that validated is remembered (#995 K-3) until a load no longer references it. + /// + private void ValidateForWorker(string source) + { + Interlocked.Increment(ref _hostValidationCompiles); + _ = ScriptEvaluator.CompileToImage(source); + _validatedSources.TryAdd(source, 0); + } + + /// Test/diagnostic: Roslyn compiles this engine has run for predicates in process (cache misses). + internal long PredicateCompileCount => _compileCache.CompileCount; + + /// Test/diagnostic: out-of-process validation compiles (PE images emitted and dropped) this engine ran. + internal long HostValidationCompileCount => Interlocked.Read(ref _hostValidationCompiles); + + /// Test/diagnostic: compiled predicates currently cached (in process). + internal int CachedPredicateCount => _compileCache.Count; + + /// Test seam: runs at the start of a load's compile phase (outside the gate, on the thread pool). + internal Action? CompilePhaseHookForTests { get; set; } + /// /// #935: the state a loaded alarm starts its first evaluation from — previous ?? persisted ?? Fresh. /// The previous generation's in-memory condition wins for a surviving alarm id: it is exactly what this node diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/CompiledScriptCache.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/CompiledScriptCache.cs index b287e84b8..bb1b493b8 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/CompiledScriptCache.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/CompiledScriptCache.cs @@ -44,6 +44,7 @@ public sealed class CompiledScriptCache : IDisposable { private readonly ConcurrentDictionary>> _cache = new(); private bool _disposed; + private long _compiles; /// /// Return the compiled evaluator for , compiling @@ -61,7 +62,11 @@ public sealed class CompiledScriptCache : IDisposable var key = HashSource(scriptSource); var lazy = _cache.GetOrAdd(key, _ => new Lazy>( - () => ScriptEvaluator.Compile(scriptSource), + () => + { + Interlocked.Increment(ref _compiles); + return ScriptEvaluator.Compile(scriptSource); + }, LazyThreadSafetyMode.ExecutionAndPublication)); try @@ -84,6 +89,41 @@ public sealed class CompiledScriptCache : IDisposable /// Current entry count. Exposed for Admin UI diagnostics / tests. public int Count => _cache.Count; + /// + /// Number of Roslyn compiles this cache has started (cache misses, failed compiles included). Exposed for + /// diagnostics and tests — #995 K-3 pins that a reload of unchanged sources compiles nothing. + /// + public long CompileCount => Interlocked.Read(ref _compiles); + + /// + /// #995 K-3: drop (and dispose) every cached compile whose source is NOT in , leaving the + /// kept entries — and their loaded evaluators — untouched. This is the publish-replace path for an engine that + /// reuses unchanged scripts across deploys: would throw away every compile and force the + /// next generation to recompile sources it already had. + /// + /// The sources the new generation references. + /// How many entries were removed. + public int RetainOnly(IEnumerable keep) + { + ArgumentNullException.ThrowIfNull(keep); + var keepKeys = new HashSet(StringComparer.Ordinal); + foreach (var source in keep) + if (source is not null) keepKeys.Add(HashSource(source)); + + var removed = 0; + // Value-scoped removal, as in Clear: a concurrent GetOrCompile that re-added the key keeps its fresh entry. + foreach (var entry in _cache.ToArray()) + { + if (keepKeys.Contains(entry.Key)) continue; + if (_cache.TryRemove(entry)) + { + DisposeLazyIfMaterialised(entry.Value); + removed++; + } + } + return removed; + } + /// /// Drop every cached compile. Used on config generation publish + tests. /// Disposes each materialised evaluator before removing it so its collectible diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineCompileReuseTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineCompileReuseTests.cs new file mode 100644 index 000000000..365749fe9 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineCompileReuseTests.cs @@ -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; + +/// +/// #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) => []; + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadPerfTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadPerfTests.cs new file mode 100644 index 000000000..ed7a76fa2 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests/ScriptedAlarmEngineReloadPerfTests.cs @@ -0,0 +1,86 @@ +using System.Diagnostics; +using System.Text; +using Serilog; +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 measurement: a deploy with scripted alarms. Opt-in and never part of a default +/// run — skips unless OTOPCUA_SCRIPT_PERF=1. Reports the first load, a reload of the SAME definitions (what +/// every deploy that did not touch an alarm does), a reload with one predicate edited, and how long an operator +/// acknowledge issued just after a reload started waits for the engine gate. +/// +/// +/// Run: OTOPCUA_SCRIPT_PERF=1 dotnet test tests/Core/ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.Tests -c Release +/// --filter Category=Perf --logger "console;verbosity=detailed". +/// +[Trait("Category", "Perf")] +public sealed class ScriptedAlarmEngineReloadPerfTests +{ + private const int AlarmCount = 500; + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static ScriptedAlarmDefinition Alarm(int i, int threshold) => new( + AlarmId: $"A{i}", + EquipmentPath: "Plant/Line1/Reactor", + AlarmName: $"A{i}", + Kind: AlarmKind.AlarmCondition, + Severity: AlarmSeverity.High, + MessageTemplate: "over", + PredicateScriptSource: $"return (int)ctx.GetTag(\"T{i % 50}\").Value > {threshold};"); + + /// Measures load / reload / ack-during-reload for 500 alarms with distinct predicates. + [Fact] + public async Task Reload_of_500_alarms() + { + if (Environment.GetEnvironmentVariable("OTOPCUA_SCRIPT_PERF") != "1") + Assert.Skip("perf harness: set OTOPCUA_SCRIPT_PERF=1 to run"); + + var up = new FakeUpstream(); + for (var t = 0; t < 50; t++) up.Set($"T{t}", 0); + var logger = new LoggerConfiguration().CreateLogger(); + using var eng = new ScriptedAlarmEngine(up, new InMemoryAlarmStateStore(), new ScriptLoggerFactory(logger), logger); + + var defs = Enumerable.Range(0, AlarmCount).Select(i => Alarm(i, 1000 + i)).ToArray(); + + var sw = Stopwatch.StartNew(); + await eng.LoadAsync(defs, Ct); + var first = sw.Elapsed; + + sw.Restart(); + await eng.LoadAsync(defs, Ct); + var same = sw.Elapsed; + + var edited = defs.ToArray(); + edited[7] = Alarm(7, 4242); + sw.Restart(); + await eng.LoadAsync(edited, Ct); + var oneEdited = sw.Elapsed; + + // Ack latency while a reload that must compile everything is in progress (a fresh set of sources). + var fresh = Enumerable.Range(0, AlarmCount).Select(i => Alarm(i, 9000 + i)).ToArray(); + sw.Restart(); + var reload = Task.Run(() => eng.LoadAsync(fresh, Ct), Ct); + await Task.Delay(200, Ct); + var ackStart = sw.Elapsed; + await eng.AcknowledgeAsync("A1", "op", null, Ct); + var ackWait = sw.Elapsed - ackStart; + await reload; + var freshReload = sw.Elapsed; + + var report = new StringBuilder() + .AppendLine($"K-3 scripted-alarm reload, {AlarmCount} alarms (distinct predicates):") + .AppendLine($" first load {first.TotalMilliseconds,10:F0} ms") + .AppendLine($" reload, same defs {same.TotalMilliseconds,10:F0} ms") + .AppendLine($" reload, one edited {oneEdited.TotalMilliseconds,10:F0} ms") + .AppendLine($" reload, all new {freshReload.TotalMilliseconds,10:F0} ms") + .AppendLine($" ack wait during that {ackWait.TotalMilliseconds,10:F0} ms") + .ToString(); + TestContext.Current.TestOutputHelper?.WriteLine(report); + if (Environment.GetEnvironmentVariable("OTOPCUA_SCRIPT_PERF_OUT") is { Length: > 0 } path) + await File.AppendAllTextAsync(path, report, Ct); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/CompiledScriptCacheTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/CompiledScriptCacheTests.cs index c7c280c17..556ff846f 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/CompiledScriptCacheTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/CompiledScriptCacheTests.cs @@ -401,4 +401,26 @@ public sealed class CompiledScriptCacheTests cache.Dispose(); Should.Throw(() => cache.GetOrCompile("""return 2;""")); } + + /// + /// #995 K-3: RetainOnly keeps (and does not recompile) the kept sources, and disposes + drops the rest. + /// + [Fact] + public async Task RetainOnly_keeps_kept_entries_and_disposes_the_rest() + { + var cache = new CompiledScriptCache(); + var kept = cache.GetOrCompile("""return 1;"""); + var dropped = cache.GetOrCompile("""return 2;"""); + cache.CompileCount.ShouldBe(2); + + cache.RetainOnly(["""return 1;""", """return 3;"""]).ShouldBe(1); + + cache.Count.ShouldBe(1); + cache.Contains("""return 1;""").ShouldBeTrue(); + cache.GetOrCompile("""return 1;""").ShouldBeSameAs(kept); + cache.CompileCount.ShouldBe(2); + (await kept.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken)).ShouldBe(1); + await Should.ThrowAsync( + () => dropped.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken)); + } }