Merge #995: alarm predicates compiled once outside the gate, node-indexed stood-down items, kept drivers not re-subscribed, artifact parsed once, VirtualTag/Calculation evaluation coalesced

This commit is contained in:
Joseph Doherty
2026-12-03 11:16:21 -05:00
28 changed files with 2034 additions and 217 deletions
@@ -132,15 +132,26 @@ public sealed class ScriptedAlarmEngine : IDisposable
/// <see cref="ScriptEvaluator{TContext, TResult}.Compile"/> calls through the
/// cache so the collectible <see cref="System.Runtime.Loader.AssemblyLoadContext"/>
/// each compile produces is actually disposed on the publish-replace path:
/// the cache's <see cref="CompiledScriptCache{TContext, TResult}.Clear"/>
/// 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 <see cref="CompiledScriptCache{TContext, TResult}.RetainOnly"/>
/// 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 <c>ScriptEvaluator.Compile</c> directly, which left
/// the ALCs rooted until the process exited — defeating -008 on the real path.
/// </summary>
private readonly CompiledScriptCache<AlarmPredicateContext, bool> _compileCache = new();
/// <summary>
/// #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.
/// </summary>
private readonly ConcurrentDictionary<string, byte> _validatedSources = new(StringComparer.Ordinal);
private long _hostValidationCompiles;
/// <summary>
/// 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 <see cref="InvalidOperationException"/>, subscribes
/// to upstream input tags, seeds the value cache, seeds each alarm's condition, and
/// recomputes ActiveState from the current predicate (startup recovery).
/// <para>#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).</para>
/// <para>#935: the seed is <c>previous ?? persisted ?? Fresh</c>. 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<string>();
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<AlarmPredicateContext, bool>? evaluator = null;
if (_runner is null) evaluator = _compileCache.GetOrCompile(def.PredicateScriptSource);
else _ = ScriptEvaluator<AlarmPredicateContext, bool>.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<string>(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);
}
/// <summary>One definition after the compile phase: its dependency extraction, or why it cannot load.</summary>
private sealed record PreparedPredicate(
ScriptedAlarmDefinition Definition, DependencyExtractionResult? Extraction, string? Failure);
/// <summary>
/// #995 K-3: the compile phase of <see cref="LoadAsync"/>, run OUTSIDE <see cref="_evalGate"/> on the thread
/// pool with bounded parallelism. Extracts each predicate's dependencies and compiles it into
/// <see cref="_compileCache"/> (in process) or validates it to a PE image (out of process, remembered in
/// <see cref="_validatedSources"/> 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.
/// </summary>
private PreparedPredicate[] PreparePredicates(IReadOnlyList<ScriptedAlarmDefinition> 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;
}
/// <summary>
/// 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.
/// </summary>
private void ValidateForWorker(string source)
{
Interlocked.Increment(ref _hostValidationCompiles);
_ = ScriptEvaluator<AlarmPredicateContext, bool>.CompileToImage(source);
_validatedSources.TryAdd(source, 0);
}
/// <summary>Test/diagnostic: Roslyn compiles this engine has run for predicates in process (cache misses).</summary>
internal long PredicateCompileCount => _compileCache.CompileCount;
/// <summary>Test/diagnostic: out-of-process validation compiles (PE images emitted and dropped) this engine ran.</summary>
internal long HostValidationCompileCount => Interlocked.Read(ref _hostValidationCompiles);
/// <summary>Test/diagnostic: compiled predicates currently cached (in process).</summary>
internal int CachedPredicateCount => _compileCache.Count;
/// <summary>Test seam: runs at the start of a load's compile phase (outside the gate, on the thread pool).</summary>
internal Action? CompilePhaseHookForTests { get; set; }
/// <summary>
/// #935: the state a loaded alarm starts its first evaluation from — <c>previous ?? persisted ?? Fresh</c>.
/// The previous generation's in-memory condition wins for a surviving alarm id: it is exactly what this node