From a24071405a4d53b54c1aa3eb628beac7d335126d Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:11:57 -0500 Subject: [PATCH] =?UTF-8?q?perf(script-runner):=20#1052=20K-11=20remainder?= =?UTF-8?q?=20=E2=80=94=20scoped=20keys=20cached=20per=20(kind,=20key);=20?= =?UTF-8?q?in-process=20compile-failure=20cache=20keyed=20by=20(kind,=20so?= =?UTF-8?q?urce)=20tuple?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../OutOfProcessScriptRunner.cs | 4 +- .../InProcessScriptRunner.cs | 12 ++-- .../ScopedKeys.cs | 49 +++++++++++++ .../ShadowScriptRunner.cs | 4 +- .../ScopedKeyCacheTests.cs | 68 +++++++++++++++++++ 5 files changed, 128 insertions(+), 9 deletions(-) create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScopedKeys.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScopedKeyCacheTests.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs index cc465b4be..da6b3a2e9 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs @@ -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; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/InProcessScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/InProcessScriptRunner.cs index 6368aa259..685df8c30 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/InProcessScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/InProcessScriptRunner.cs @@ -22,7 +22,9 @@ public sealed class InProcessScriptRunner : IPhysicalScriptRunner, IDisposable { private readonly CompiledScriptCache _valueCache = new(); private readonly CompiledScriptCache _predicateCache = new(); - private readonly ConcurrentDictionary _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; /// Initializes the runner. @@ -47,8 +49,8 @@ public sealed class InProcessScriptRunner : IPhysicalScriptRunner, IDisposable private async Task 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 /// The namespaced key. 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); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScopedKeys.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScopedKeys.cs new file mode 100644 index 000000000..5affbf37c --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScopedKeys.cs @@ -0,0 +1,49 @@ +using System.Collections.Concurrent; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; + +/// +/// Cached runner-internal keys ({kind}:{key}, the form 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. +/// +/// +/// One map per , keyed by the seam's own key string, so a warm lookup is a hash probe and +/// no allocation. Bounded: a map that reaches 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. +/// +public static class ScopedKeys +{ + /// Distinct keys held per kind before the map is cleared (far above any deployed script count). + public const int CapacityPerKind = 65_536; + + // Indexed by (int)kind; the defined kinds are 1..3. Index 0 is unused. + private static readonly ConcurrentDictionary[] Maps = + Enumerable.Range(0, 4).Select(_ => new ConcurrentDictionary(StringComparer.Ordinal)).ToArray(); + + /// The scoped key for under , allocation-free once cached. + /// The context kind. + /// The seam's key. + /// A string equal to (, ). + 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); + } + + /// Entries currently cached for (diagnostics / tests). + /// The context kind. + /// The entry count; 0 for an unknown kind. + public static int CountFor(ScriptContextKind kind) + { + var index = (int)kind; + return index > 0 && index < Maps.Length ? Maps[index].Count : 0; + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ShadowScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ShadowScriptRunner.cs index 647e76432..f36c95feb 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ShadowScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ShadowScriptRunner.cs @@ -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("reason", reason), new KeyValuePair("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 }); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScopedKeyCacheTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScopedKeyCacheTests.cs new file mode 100644 index 000000000..e5159a76f --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScopedKeyCacheTests.cs @@ -0,0 +1,68 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; + +/// +/// 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 {kind}:{key} string afresh, although the key is constant for a script. +/// hands back the same cached string with no allocation once warm. +/// +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"); + } +}