perf(script-runner): #1052 K-11 remainder — scoped keys cached per (kind, key); in-process compile-failure cache keyed by (kind, source) tuple

Every evaluation through the in-process, shadow and out-of-process runners built its
"{kind}:{key}" string afresh, and InProcessScriptRunner also concatenated the WHOLE script
source into its negative-cache key per evaluation. ScopedKeys.For returns a cached string
(bounded 65,536 keys per kind, cleared on overflow); the compile-failure map is keyed by a
(kind, source) tuple.

Measured: 10,000 scoped-key lookups 1,520,000 B -> 0 B (ScopedKeyCacheTests);
InProcessScriptRunner.RunAsync with a ~2 KB source 9,161 -> ~4,900-5,000 B per evaluation.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 15:11:57 -05:00
parent 2a8bac5bf5
commit a24071405a
5 changed files with 128 additions and 9 deletions
@@ -382,7 +382,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
{
if (Volatile.Read(ref _disposed) != 0) return ScriptRunOutcome.Unavailable(ScriptRunOutcome.RunnerUnavailableReason);
var key = InProcessScriptRunner.ScopedKey(invocation.Kind, invocation.Key);
var key = ScopedKeys.For(invocation.Kind, invocation.Key);
var state = Admit(key, invocation.Kind, invocation.Source);
if (state.QuarantineReason is { } quarantined) return ScriptRunOutcome.Failed(quarantined);
@@ -543,7 +543,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
answered = null;
if (Volatile.Read(ref _disposed) != 0) return BatchPreparation.Full;
var key = InProcessScriptRunner.ScopedKey(invocation.Kind, invocation.Key);
var key = ScopedKeys.For(invocation.Kind, invocation.Key);
var state = Admit(key, invocation.Kind, invocation.Source);
if (state.QuarantineReason is not null || _compileFailures.ContainsKey(state.FailureKey)) return BatchPreparation.Full;
@@ -22,7 +22,9 @@ public sealed class InProcessScriptRunner : IPhysicalScriptRunner, IDisposable
{
private readonly CompiledScriptCache<VirtualTagContext, object?> _valueCache = new();
private readonly CompiledScriptCache<AlarmPredicateContext, bool> _predicateCache = new();
private readonly ConcurrentDictionary<string, string> _compileFailures = new(StringComparer.Ordinal);
// Keyed by (kind, source): the source is the failure's identity. A tuple key instead of a "{kind}:{source}" string, which
// copied the whole script source on every evaluation (lmxopcua#1052, K-11 remainder).
private readonly ConcurrentDictionary<(ScriptContextKind Kind, string Source), string> _compileFailures = new();
private readonly ScriptRunGuard _guard;
/// <summary>Initializes the runner.</summary>
@@ -47,8 +49,8 @@ public sealed class InProcessScriptRunner : IPhysicalScriptRunner, IDisposable
private async Task<ScriptRunOutcome> RunOwnedAsync(ScriptInvocation invocation, PhysicalLeaseOwnership ownership, CancellationToken ct)
{
var key = ScopedKey(invocation.Kind, invocation.Key);
var failureKey = ScopedKey(invocation.Kind, invocation.Source);
var key = ScopedKeys.For(invocation.Kind, invocation.Key);
var failureKey = (invocation.Kind, invocation.Source);
if (_compileFailures.TryGetValue(failureKey, out var known)) return ScriptRunOutcome.Failed(known);
var logger = invocation.ScriptLogger ?? Logger.None;
@@ -112,7 +114,7 @@ public sealed class InProcessScriptRunner : IPhysicalScriptRunner, IDisposable
{
var prefix = ScopedKey(kind, string.Empty);
foreach (var k in _compileFailures.Keys)
if (k.StartsWith(prefix, StringComparison.Ordinal)) _compileFailures.TryRemove(k, out _);
if (k.Kind == kind) _compileFailures.TryRemove(k, out _);
foreach (var k in _guard.QuarantinedKeys)
if (k.StartsWith(prefix, StringComparison.Ordinal)) _guard.Reset(k);
}
@@ -140,7 +142,7 @@ public sealed class InProcessScriptRunner : IPhysicalScriptRunner, IDisposable
/// <returns>The namespaced key.</returns>
public static string ScopedKey(ScriptContextKind kind, string key) => $"{(int)kind}:{key}";
private ScriptRunOutcome RememberCompileFailure(string failureKey, string reason)
private ScriptRunOutcome RememberCompileFailure((ScriptContextKind Kind, string Source) failureKey, string reason)
{
_compileFailures.TryAdd(failureKey, reason);
return ScriptRunOutcome.Failed(reason);
@@ -0,0 +1,49 @@
using System.Collections.Concurrent;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// <summary>
/// Cached runner-internal keys (<c>{kind}:{key}</c>, the form <see cref="InProcessScriptRunner.ScopedKey"/> builds) so a
/// per-evaluation lookup does not allocate (lmxopcua#1052, #999 review K-11 remainder). A script's key is constant for its
/// life, but every evaluation through the in-process, shadow and out-of-process runners used to concatenate it afresh.
/// </summary>
/// <remarks>
/// One map per <see cref="ScriptContextKind"/>, keyed by the seam's own key string, so a warm lookup is a hash probe and
/// no allocation. Bounded: a map that reaches <see cref="CapacityPerKind"/> distinct keys is cleared and refilled from
/// the live keys (the count is only consulted on a miss). Shared by every runner in the process — the value is a pure
/// function of its inputs, and the strings are the same ones the seams already hold.
/// </remarks>
public static class ScopedKeys
{
/// <summary>Distinct keys held per kind before the map is cleared (far above any deployed script count).</summary>
public const int CapacityPerKind = 65_536;
// Indexed by (int)kind; the defined kinds are 1..3. Index 0 is unused.
private static readonly ConcurrentDictionary<string, string>[] Maps =
Enumerable.Range(0, 4).Select(_ => new ConcurrentDictionary<string, string>(StringComparer.Ordinal)).ToArray();
/// <summary>The scoped key for <paramref name="key"/> under <paramref name="kind"/>, allocation-free once cached.</summary>
/// <param name="kind">The context kind.</param>
/// <param name="key">The seam's key.</param>
/// <returns>A string equal to <see cref="InProcessScriptRunner.ScopedKey"/>(<paramref name="kind"/>, <paramref name="key"/>).</returns>
public static string For(ScriptContextKind kind, string key)
{
var index = (int)kind;
if ((uint)index >= (uint)Maps.Length || index == 0) return InProcessScriptRunner.ScopedKey(kind, key);
var map = Maps[index];
if (map.TryGetValue(key, out var scoped)) return scoped;
scoped = InProcessScriptRunner.ScopedKey(kind, key);
if (map.Count >= CapacityPerKind) map.Clear();
return map.GetOrAdd(key, scoped);
}
/// <summary>Entries currently cached for <paramref name="kind"/> (diagnostics / tests).</summary>
/// <param name="kind">The context kind.</param>
/// <returns>The entry count; 0 for an unknown kind.</returns>
public static int CountFor(ScriptContextKind kind)
{
var index = (int)kind;
return index > 0 && index < Maps.Length ? Maps[index].Count : 0;
}
}
@@ -219,7 +219,7 @@ public sealed class ShadowScriptRunner : IScriptRunner, IScriptShadow, IDisposab
public void Mirror(ScriptInvocation invocation, ScriptRunOutcome published)
{
if (invocation is null || published is null || Volatile.Read(ref _disposed) != 0) return;
var scoped = InProcessScriptRunner.ScopedKey(invocation.Kind, invocation.Key);
var scoped = ScopedKeys.For(invocation.Kind, invocation.Key);
if (!_busy.TryAdd(scoped, 0))
{
Drop(invocation.Kind, "key_busy", ref _droppedBusy);
@@ -403,7 +403,7 @@ public sealed class ShadowScriptRunner : IScriptRunner, IScriptShadow, IDisposab
new KeyValuePair<string, object?>("reason", reason),
new KeyValuePair<string, object?>("script", invocation.Key));
var scoped = InProcessScriptRunner.ScopedKey(invocation.Kind, invocation.Key);
var scoped = ScopedKeys.For(invocation.Kind, invocation.Key);
_mismatches.AddOrUpdate(scoped,
_ => new ScriptShadowMismatch(invocation.Kind, invocation.Key, 1, reason, comparison.Summary),
(_, prior) => prior with { Count = prior.Count + 1, LastReason = reason, LastSummary = comparison.Summary });
@@ -0,0 +1,68 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
/// <summary>
/// lmxopcua#1052 (#999 review K-11 remainder): every evaluation through the in-process, shadow and out-of-process runners
/// used to build its runner-internal <c>{kind}:{key}</c> string afresh, although the key is constant for a script.
/// <see cref="ScopedKeys.For"/> hands back the same cached string with no allocation once warm.
/// </summary>
public sealed class ScopedKeyCacheTests
{
private const int Evaluations = 10_000;
[Fact]
public void Warm_lookups_do_not_allocate_while_the_uncached_form_allocates_per_call()
{
var keys = Enumerable.Range(0, 100).Select(i => $"Plant/Line{i}/Equipment/Speed-{Guid.NewGuid():N}").ToArray();
foreach (var key in keys) ScopedKeys.For(ScriptContextKind.VirtualTag, key); // warm
// Positive control: the measurement sees the per-call string of the old form.
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < Evaluations; i++) _ = InProcessScriptRunner.ScopedKey(ScriptContextKind.VirtualTag, keys[i % keys.Length]);
var uncached = GC.GetAllocatedBytesForCurrentThread() - before;
before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < Evaluations; i++) _ = ScopedKeys.For(ScriptContextKind.VirtualTag, keys[i % keys.Length]);
var cached = GC.GetAllocatedBytesForCurrentThread() - before;
TestContext.Current.TestOutputHelper?.WriteLine($"{Evaluations} scoped keys: uncached {uncached} B, cached {cached} B");
uncached.ShouldBeGreaterThan(Evaluations * 64L, "positive control: the old form allocates a string per call");
cached.ShouldBeLessThan(1024, "a warm scoped-key lookup must not allocate");
}
[Theory]
[InlineData(ScriptContextKind.VirtualTag, "vt-1")]
[InlineData(ScriptContextKind.Calculation, "Plant/Modbus/dev1/Speed")]
[InlineData(ScriptContextKind.AlarmPredicate, "")]
public void Cached_key_is_the_scoped_key_and_the_same_instance_each_time(ScriptContextKind kind, string key)
{
var first = ScopedKeys.For(kind, key);
first.ShouldBe(InProcessScriptRunner.ScopedKey(kind, key));
ReferenceEquals(first, ScopedKeys.For(kind, key)).ShouldBeTrue();
}
[Fact]
public void Kinds_do_not_share_entries()
{
var key = Guid.NewGuid().ToString("N");
ScopedKeys.For(ScriptContextKind.VirtualTag, key).ShouldNotBe(ScopedKeys.For(ScriptContextKind.Calculation, key));
}
[Fact]
public void An_unknown_kind_still_answers_the_scoped_key()
{
ScopedKeys.For((ScriptContextKind)99, "x").ShouldBe("99:x");
}
[Fact]
public void The_cache_is_bounded()
{
for (var i = 0; i < ScopedKeys.CapacityPerKind + 50; i++) ScopedKeys.For(ScriptContextKind.AlarmPredicate, $"bounded-{i}");
ScopedKeys.CountFor(ScriptContextKind.AlarmPredicate).ShouldBeLessThanOrEqualTo(ScopedKeys.CapacityPerKind);
// Still correct after a reset.
ScopedKeys.For(ScriptContextKind.AlarmPredicate, "after").ShouldBe("3:after");
}
}