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:
@@ -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
|
||||
|
||||
@@ -44,6 +44,7 @@ public sealed class CompiledScriptCache<TContext, TResult> : IDisposable
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, Lazy<ScriptEvaluator<TContext, TResult>>> _cache = new();
|
||||
private bool _disposed;
|
||||
private long _compiles;
|
||||
|
||||
/// <summary>
|
||||
/// Return the compiled evaluator for <paramref name="scriptSource"/>, compiling
|
||||
@@ -61,7 +62,11 @@ public sealed class CompiledScriptCache<TContext, TResult> : IDisposable
|
||||
|
||||
var key = HashSource(scriptSource);
|
||||
var lazy = _cache.GetOrAdd(key, _ => new Lazy<ScriptEvaluator<TContext, TResult>>(
|
||||
() => ScriptEvaluator<TContext, TResult>.Compile(scriptSource),
|
||||
() =>
|
||||
{
|
||||
Interlocked.Increment(ref _compiles);
|
||||
return ScriptEvaluator<TContext, TResult>.Compile(scriptSource);
|
||||
},
|
||||
LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
|
||||
try
|
||||
@@ -84,6 +89,41 @@ public sealed class CompiledScriptCache<TContext, TResult> : IDisposable
|
||||
/// <summary>Current entry count. Exposed for Admin UI diagnostics / tests.</summary>
|
||||
public int Count => _cache.Count;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public long CompileCount => Interlocked.Read(ref _compiles);
|
||||
|
||||
/// <summary>
|
||||
/// #995 K-3: drop (and dispose) every cached compile whose source is NOT in <paramref name="keep"/>, leaving the
|
||||
/// kept entries — and their loaded evaluators — untouched. This is the publish-replace path for an engine that
|
||||
/// reuses unchanged scripts across deploys: <see cref="Clear"/> would throw away every compile and force the
|
||||
/// next generation to recompile sources it already had.
|
||||
/// </summary>
|
||||
/// <param name="keep">The sources the new generation references.</param>
|
||||
/// <returns>How many entries were removed.</returns>
|
||||
public int RetainOnly(IEnumerable<string> keep)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(keep);
|
||||
var keepKeys = new HashSet<string>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drop every cached compile. Used on config generation publish + tests.
|
||||
/// Disposes each materialised evaluator before removing it so its collectible
|
||||
|
||||
Reference in New Issue
Block a user