diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs index f75a02274..77afb3695 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/DataProtoMapper.cs @@ -153,6 +153,17 @@ public static class DataProtoMapper { ArgumentNullException.ThrowIfNull(x); var serving = DecodeServing(x.Serving); + serving.Validate(requireEpochs: true); + return DecodeSampleCore(x, serving, maxElements, maxBytes, preflighted: false); + } + + /// + /// A sample whose identity is already decoded and validated; with + /// its value's size was already bounded by the frame preflight (K-11). + /// + private static DataSample DecodeSampleCore( + W.Sample x, ServingIdentity serving, int maxElements, int maxBytes, bool preflighted) + { var source = x.SourceTimestamp is null ? (DateTimeOffset?)null : TypedValueCodec.DecodeTimestamp(x.SourceTimestamp); @@ -161,9 +172,10 @@ public static class DataProtoMapper : TypedValueCodec.DecodeTimestamp(x.ServerTimestamp); if (x.Version <= 0) throw new ArgumentException("Invalid sample version."); - serving.Validate(requireEpochs: true); return new( - TypedValueCodec.Decode(x.Value, maxElements, maxBytes), + preflighted + ? TypedValueCodec.DecodePreflighted(x.Value, maxElements, maxBytes) + : TypedValueCodec.Decode(x.Value, maxElements, maxBytes), x.StatusCode, source, server, @@ -459,20 +471,9 @@ public static class DataProtoMapper new DataDecodeLimits(maxItems, maxBytes, maxElements), batch.Items.Select(i => i.Value) ); - if ( - maxItems <= 0 - || maxBytes <= 0 - || batch.Items.Count > maxItems - || frame.CalculateSize() > maxBytes - ) - throw new ArgumentException("Frame exceeds budget."); - long decodedBytes = 0; - foreach (var update in batch.Items) - { - decodedBytes += TypedValueCodec.DecodedBytes(update.Value, maxBytes - decodedBytes); - if (decodedBytes > maxBytes) - throw new ArgumentException("Decoded frame exceeds budget."); - } + // #999 / review K-11: no second sizing pass. Preflight already refused a non-positive limit, more than maxItems + // items, an encoded frame over maxBytes, and a decoded total over maxBytes (from a HIGHER starting estimate than a + // plain per-value sum) — re-sizing the frame and every value here could never reject anything it accepted. var serving = DecodeServing(batch.Serving); serving.Validate(requireEpochs: true); if (serving != expectedServing) @@ -507,7 +508,7 @@ public static class DataProtoMapper var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness, update.HasOriginAgeTicks, update.OriginAgeTicks, update.HasReadiness, update.Readiness); var sample = new DataSample( - TypedValueCodec.Decode(update.Value, maxElements, maxBytes), + TypedValueCodec.DecodePreflighted(update.Value, maxElements, maxBytes), update.HasStatusCode ? update.StatusCode : batch.DefaultStatusCode, sourceTime, serverTime, @@ -642,25 +643,16 @@ public static class DataProtoMapper || maxItems <= 0 || maxBytes <= 0 || frame.Values.Items.Count > maxItems - || frame.CalculateSize() > maxBytes ) throw new ArgumentException("Invalid or oversized values frame."); + // #999 / review K-11: Preflight is the one sizing pass (encoded frame + every value's decoded size, against the + // same limits); the frame and each value used to be sized again here and once more per value inside Decode. Preflight( frame, frame.Values.Items.Count, new DataDecodeLimits(maxItems, maxBytes, maxElements), frame.Values.Items.Select(i => i.Sample.Value) ); - long decodedBytes = 0; - foreach (var update in frame.Values.Items) - { - decodedBytes += TypedValueCodec.DecodedBytes( - update.Sample.Value, - maxBytes - decodedBytes - ); - if (decodedBytes > maxBytes) - throw new ArgumentException("Decoded frame exceeds budget."); - } var items = new List(frame.Values.Items.Count); try { @@ -674,11 +666,14 @@ public static class DataProtoMapper || expected != handle ) throw new ArgumentException("Unknown or stale handle."); - if (DecodeServing(item.Sample.Serving) != expectedServing) + // K-11: Serving is decoded once per item (it was decoded here and again inside DecodeSample); equal to + // the already-validated expected identity, it needs no second validation either. + var serving = DecodeServing(item.Sample.Serving); + if (serving != expectedServing) throw new ArgumentException("Unexpected serving identity."); var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness, item.HasOriginAgeTicks, item.OriginAgeTicks, item.HasReadiness, item.Readiness); - items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes), ageBounds, readiness, + items.Add(new(handle, DecodeSampleCore(item.Sample, expectedServing, maxElements, maxBytes, preflighted: true), ageBounds, readiness, subscriptionAgeReadiness && item.HasFreshnessChallengeId && item.FreshnessChallengeId.Length <= 32 ? item.FreshnessChallengeId : null)); } return new( diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs index c9d05ef9c..633ca9920 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/DataConnections/TypedValueCodec.cs @@ -100,6 +100,20 @@ public static class TypedValueCodec throw new ArgumentOutOfRangeException(nameof(maxElements)); if (value.CalculateSize() > maxBytes || DecodedBytes(value, maxBytes) > maxBytes) throw new ArgumentException("Decoded value exceeds budget."); + return DecodePreflighted(value, maxElements, maxBytes); + } + + /// + /// without re-sizing the value (#999 / review K-11): for a caller whose frame preflight has + /// already bounded every value's encoded and decoded size against the same — sizing + /// each value a third time per received frame was pure overhead on the gRPC hot path. Shape/element limits and + /// every validation still apply. + /// + internal static DataValue DecodePreflighted(Wire.TypedValue value, int maxElements, int maxBytes) + { + ArgumentNullException.ThrowIfNull(value); + if (maxElements <= 0 || maxBytes <= 0) + throw new ArgumentOutOfRangeException(nameof(maxElements)); try { return DecodeCore(value, maxElements, maxBytes); 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 306a6816f..cc465b4be 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 @@ -278,11 +278,18 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp /// The shard index. internal static int ShardIndex(string scopedKey, int shardCount) { + // FNV-1a over the key's UTF-8 bytes — encoded rune by rune into a stack buffer (#999 / review K-11): the same + // bytes, so the same placement as before, without a byte[] per evaluation. var hash = 2166136261u; - foreach (var b in Encoding.UTF8.GetBytes(scopedKey)) + Span utf8 = stackalloc byte[4]; + foreach (var rune in scopedKey.EnumerateRunes()) { - hash ^= b; - hash *= 16777619u; + var n = rune.EncodeToUtf8(utf8); + for (var i = 0; i < n; i++) + { + hash ^= utf8[i]; + hash *= 16777619u; + } } return (int)(hash % (uint)shardCount); } @@ -391,7 +398,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp var handedOff = false; SemaphoreSlim? gate = null; - var shard = state.Suspect ? _isolation : _shards[ShardIndex(key, _shards.Length)]; + var shard = state.Suspect ? _isolation : _shards[state.ShardIndexFor(key, _shards.Length)]; WorkerConnection? connection = null; try { @@ -540,7 +547,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp var state = Admit(key, invocation.Kind, invocation.Source); if (state.QuarantineReason is not null || _compileFailures.ContainsKey(state.FailureKey)) return BatchPreparation.Full; - var shard = state.Suspect ? _isolation : _shards[ShardIndex(key, _shards.Length)]; + var shard = state.Suspect ? _isolation : _shards[state.ShardIndexFor(key, _shards.Length)]; if (shard.IsolationGate is not null || shard.Current is not { } connection) return BatchPreparation.Full; if (connection.TryGetLoaded(key, state.ShaHex, SlotOrder(state, invocation.Inputs)) is not { } entry) return BatchPreparation.Full; @@ -757,7 +764,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp /// The shard a key's NEXT evaluation goes to (attribution may just have made it a suspect). private WorkerShard RouteFor(string key, KeyState state) - => state.Suspect ? _isolation : _shards[ShardIndex(key, _shards.Length)]; + => state.Suspect ? _isolation : _shards[state.ShardIndexFor(key, _shards.Length)]; private static ScriptRunOutcome Unavailable(string reason, WorkerShard shard, WorkerConnection? failed) => ScriptRunOutcome.Unavailable(reason) with { Recovery = shard.WhenRecoveredAsync(failed) }; @@ -1044,6 +1051,20 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp /// The negative compile cache's key for this source (kind-scoped). public string FailureKey => _failureKey ??= InProcessScriptRunner.ScopedKey(Kind, ShaHex); + private int _shardIndex = -1; + + /// + /// The key's (non-suspect) shard, hashed once per key state instead of per evaluation (#999 / review K-11). The + /// state is per scoped key and the shard count is fixed for the runner's life, so it never changes; a benign + /// race hashes the same value twice. + /// + public int ShardIndexFor(string scopedKey, int shardCount) + { + var index = Volatile.Read(ref _shardIndex); + if (index < 0) Volatile.Write(ref _shardIndex, index = ShardIndex(scopedKey, shardCount)); + return index; + } + /// The slot order last used for this key (see ). public string[]? Paths; public readonly List KillStrikes = []; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs index 9cbc7767b..06b50dbd8 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/ProtocolTests.cs @@ -452,4 +452,26 @@ public sealed class ProtocolTests spread.Distinct().Count().ShouldBe(4); OutOfProcessScriptRunner.ShardIndex("abc", 1000).ShouldBe((int)(0x1A47E90Bu % 1000)); } + + /// + /// #999 / review K-11: the shard hash is computed without a per-call byte[] — and over exactly the bytes the old + /// Encoding.UTF8.GetBytes form hashed (non-ASCII and lone surrogates included), so placement is unchanged. + /// + [Fact] + public void Shard_hash_allocates_nothing_and_keeps_the_utf8_placement() + { + static int Reference(string key, int count) + { + var hash = 2166136261u; + foreach (var b in System.Text.Encoding.UTF8.GetBytes(key)) { hash ^= b; hash *= 16777619u; } + return (int)(hash % (uint)count); + } + foreach (var key in new[] { "1:vt-1", "2:Plant/Linie Ä/Füllstand", "1:€𝄞", "1:\ud800x", "" }) + OutOfProcessScriptRunner.ShardIndex(key, 7919).ShouldBe(Reference(key, 7919), key); + + OutOfProcessScriptRunner.ShardIndex("1:warm", 4); + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 10_000; i++) OutOfProcessScriptRunner.ShardIndex("1:Plant/Area/Line/Equipment/vt-42", 4); + (GC.GetAllocatedBytesForCurrentThread() - before).ShouldBe(0); + } }