diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/EventPump.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/EventPump.cs index 05681c20d..a1e34c63f 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/EventPump.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/EventPump.cs @@ -608,7 +608,7 @@ internal sealed class EventPump : IAsyncDisposable var snapshot = ToSnapshot(ev); foreach (var (subscriptionId, fullReference) in subscribers) { - var handle = _handleFactory(subscriptionId); + var handle = HandleFor(subscriptionId); try { OnDataChange?.Invoke(this, new DataChangeEventArgs(handle, fullReference, snapshot)); @@ -622,6 +622,21 @@ internal sealed class EventPump : IAsyncDisposable } } + // #991 G-5: one handle object per subscription instead of one per subscriber per event. Touched only by the + // dispatch thread (every FanOut runs there), so it needs no lock. Subscription ids are never reused, and + // subscribe-once reads mint one each, so the cache is simply dropped when it grows past the bound. + private readonly Dictionary _handleCache = []; + private const int HandleCacheBound = 4_096; + + private ISubscriptionHandle HandleFor(long subscriptionId) + { + if (_handleCache.TryGetValue(subscriptionId, out var cached)) return cached; + if (_handleCache.Count >= HandleCacheBound) _handleCache.Clear(); + var created = _handleFactory(subscriptionId); + _handleCache[subscriptionId] = created; + return created; + } + private DataValueSnapshot ToSnapshot(MxEvent ev) { if (!MxValueDecoder.TryDecode(ev.Value, out var value)) diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/SubscriptionRegistry.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/SubscriptionRegistry.cs index f4203fa54..7a522e6fd 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/SubscriptionRegistry.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/SubscriptionRegistry.cs @@ -1,5 +1,4 @@ using System.Collections.Concurrent; -using System.Collections.Immutable; using ZB.MOM.WW.MxGateway.Contracts.Proto; namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; @@ -31,7 +30,10 @@ internal sealed class SubscriptionRegistry public const long ProbeSubscriptionId = -1; private readonly ConcurrentDictionary _bySubscriptionId = new(); - private readonly ConcurrentDictionary> _subscribersByItemHandle = new(); + // #991 G-5: each item handle's subscribers as a pre-built, never-mutated array — rebuilt (copy-on-write, under + // _parkGate) only when a subscription binds or unbinds, so the per-event lookup on the dispatch thread hands the + // array out as-is instead of allocating a list, a LINQ Distinct and a boxed set enumerator per event. + private readonly ConcurrentDictionary _subscribersByItemHandle = new(); private long _nextSubscriptionId; /// True when is currently registered. @@ -154,14 +156,15 @@ internal sealed class SubscriptionRegistry return BindOutcome.UnknownId; } - _bySubscriptionId[subscriptionId] = new SubscriptionEntry(subscriptionId, bindings, _session); - foreach (var binding in bindings) + var entry = new SubscriptionEntry(subscriptionId, bindings, _session); + _bySubscriptionId[subscriptionId] = entry; + // The entry's index holds each positive handle once (failed gw subscribes — handle <= 0 — expect no + // events), with the subscription's reference for it. + foreach (var (itemHandle, fullRef) in entry.FullRefByItemHandle) { - if (binding.ItemHandle <= 0) continue; // failed gw subscribe — no events expected - _subscribersByItemHandle.AddOrUpdate( - binding.ItemHandle, - _ => [subscriptionId], - (_, set) => set.Add(subscriptionId)); + _subscribersByItemHandle[itemHandle] = _subscribersByItemHandle.TryGetValue(itemHandle, out var current) + ? WithSubscriber(current, subscriptionId, fullRef) + : [(subscriptionId, fullRef)]; } AfterMapWriteForTests?.Invoke(); promoted = PromoteParkedEventsLocked(bindings); @@ -172,19 +175,32 @@ internal sealed class SubscriptionRegistry private void RemoveFromReverseMap(SubscriptionEntry entry) { - foreach (var binding in entry.Bindings) + foreach (var itemHandle in entry.FullRefByItemHandle.Keys) { - if (binding.ItemHandle <= 0) continue; - if (!_subscribersByItemHandle.TryGetValue(binding.ItemHandle, out var set)) continue; - var remaining = set.Remove(entry.SubscriptionId); - if (remaining.IsEmpty) - { - _subscribersByItemHandle.TryRemove(binding.ItemHandle, out _); - } - else _subscribersByItemHandle[binding.ItemHandle] = remaining; + if (!_subscribersByItemHandle.TryGetValue(itemHandle, out var current)) continue; + var remaining = Array.FindAll(current, s => s.SubscriptionId != entry.SubscriptionId); + if (remaining.Length == 0) _subscribersByItemHandle.TryRemove(itemHandle, out _); + else if (remaining.Length != current.Length) _subscribersByItemHandle[itemHandle] = remaining; } } + /// A copy of with set to . + private static (long SubscriptionId, string FullReference)[] WithSubscriber( + (long SubscriptionId, string FullReference)[] current, long subscriptionId, string fullRef) + { + var index = Array.FindIndex(current, s => s.SubscriptionId == subscriptionId); + if (index >= 0) + { + var replaced = ((long SubscriptionId, string FullReference)[])current.Clone(); + replaced[index] = (subscriptionId, fullRef); + return replaced; + } + var grown = new (long SubscriptionId, string FullReference)[current.Length + 1]; + current.CopyTo(grown, 0); + grown[^1] = (subscriptionId, fullRef); + return grown; + } + /// /// Remove a subscription. Returns the bindings the caller should pass to /// UnsubscribeBulkAsync; null when the id was never registered. @@ -220,21 +236,14 @@ internal sealed class SubscriptionRegistry /// /// The gateway item handle. /// A list of subscription and reference pairs for the item handle. - public IReadOnlyList<(long SubscriptionId, string FullReference)> ResolveSubscribers(int itemHandle) - { - if (!_subscribersByItemHandle.TryGetValue(itemHandle, out var bag)) return []; - - // Each subscription may include the tag once. Walk every active subscription that - // claims this handle and pull the full ref from its index in O(1). - var result = new List<(long, string)>(); - foreach (var subId in bag.Distinct()) - { - if (!_bySubscriptionId.TryGetValue(subId, out var entry)) continue; - if (entry.FullRefByItemHandle.TryGetValue(itemHandle, out var fullRef)) - result.Add((subId, fullRef)); - } - return result; - } + /// + /// Allocation-free (#991 G-5): returns the handle's pre-built subscriber array itself. It is never mutated — + /// a bind or unbind publishes a new array — so the caller may enumerate it while the map changes. + /// + public IReadOnlyList<(long SubscriptionId, string FullReference)> ResolveSubscribers(int itemHandle) => + _subscribersByItemHandle.TryGetValue(itemHandle, out var subscribers) + ? subscribers + : Array.Empty<(long SubscriptionId, string FullReference)>(); /// /// Drop every subscription and the whole reverse map. Used by the driver's runtime teardown: diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/FanOutAllocationTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/FanOutAllocationTests.cs new file mode 100644 index 000000000..b036069a6 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/FanOutAllocationTests.cs @@ -0,0 +1,106 @@ +using System.Runtime.CompilerServices; +using System.Threading.Channels; +using Shouldly; +using Xunit; +using ZB.MOM.WW.MxGateway.Contracts.Proto; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime; + +/// +/// #991 G-5 — every data-change event used to allocate, in the subscriber lookup alone, a result list, a LINQ +/// Distinct iterator with its own hash set, and a boxed immutable-set enumerator, plus a new subscription +/// handle per subscriber per event. The reverse map now stores each item handle's subscribers as a pre-built +/// array (lookup is allocation-free) and the pump reuses one handle object per subscription. +/// +public sealed class FanOutAllocationTests +{ + /// Resolving a handle's subscribers allocates nothing once the map is built. + [Fact] + public void ResolveSubscribers_does_not_allocate() + { + var registry = new SubscriptionRegistry(); + registry.Register(1, [new TagBinding("Tank.Level", 7)]); + registry.Register(2, [new TagBinding("Tank.Level", 7), new TagBinding("Tank.Temp", 8)]); + registry.ResolveSubscribers(7).Count.ShouldBe(2); // warm-up (JIT) + + var before = GC.GetAllocatedBytesForCurrentThread(); + var total = 0; + for (var i = 0; i < 1_000; i++) total += registry.ResolveSubscribers(7).Count; + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + total.ShouldBe(2_000); + allocated.ShouldBe(0L, "the per-event subscriber lookup must not allocate"); + } + + /// Semantics kept: one entry per subscription, the subscription's own reference, removals honoured. + [Fact] + public void ResolveSubscribers_keeps_its_semantics() + { + var registry = new SubscriptionRegistry(); + registry.Register(1, [new TagBinding("A.X", 5), new TagBinding("A.X", 5)]); // a duplicate binding stays one entry + registry.Register(2, [new TagBinding("B.X", 5)]); + + registry.ResolveSubscribers(5).OrderBy(s => s.SubscriptionId).ShouldBe([(1L, "A.X"), (2L, "B.X")]); + + registry.Rebind(1, [new TagBinding("A.X", 6)]); + registry.ResolveSubscribers(5).ShouldBe([(2L, "B.X")]); + registry.ResolveSubscribers(6).ShouldBe([(1L, "A.X")]); + + registry.Remove(2); + registry.ResolveSubscribers(5).ShouldBeEmpty(); + registry.TrackedItemHandleCount.ShouldBe(1); + } + + /// The pump hands every event of one subscription the same handle instance. + [Fact] + public async Task The_pump_reuses_one_handle_per_subscription() + { + var subscriber = new ChannelSubscriber(); + var registry = new SubscriptionRegistry(); + registry.Register(1, [new TagBinding("Tank.Level", 7)]); + var handles = new List(); + var twoSeen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await using var pump = new EventPump(subscriber, registry, channelCapacity: 8, clientName: "G5"); + pump.OnDataChange += (_, e) => + { + handles.Add(e.SubscriptionHandle); + if (handles.Count == 2) twoSeen.TrySetResult(); + }; + pump.Start(); + + await subscriber.EmitAsync(7, 1.0); + await subscriber.EmitAsync(7, 2.0); + await TestWait.ForAsync(twoSeen.Task, "both events must be dispatched"); + + handles[1].ShouldBeSameAs(handles[0]); + ((GalaxySubscriptionHandle)handles[0]).SubscriptionId.ShouldBe(1); + } + + private sealed class ChannelSubscriber : IGalaxySubscriber + { + private readonly Channel _events = Channel.CreateUnbounded(); + + public Task> SubscribeBulkAsync( + IReadOnlyList fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken) + => Task.FromResult>([]); + + public Task UnsubscribeBulkAsync(IReadOnlyList itemHandles, CancellationToken cancellationToken) => Task.CompletedTask; + + public async IAsyncEnumerable StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + yield return ev; + } + + public ValueTask EmitAsync(int handle, double value) => _events.Writer.WriteAsync(new MxEvent + { + Family = MxEventFamily.OnDataChange, + ItemHandle = handle, + Value = new MxValue { DoubleValue = value }, + Quality = 192, + }); + } +}