diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs index 5e678114c..35faeb8a7 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -1401,12 +1401,20 @@ public sealed class GalaxyDriver /// : a teardown bumps it and clears the registry, /// and a Rebind landing after that would resurrect dead handles into the next runtime. /// + /// + /// True when hold handles the CURRENT gateway session issued (the replay-gap + /// re-snapshot): those are still advised, so every handle a re-advise supersedes is released (#991 G-6 — + /// each gap used to double the gateway's advise count), and a tag whose re-advise fails keeps its live + /// handle. False for the reconnect replay, whose handles died with the old session and whose numbers the + /// new session reuses — they are never sent. + /// /// Cancellation token. /// The number of tag references re-subscribed. private async Task ResubscribeAllAsync( IReadOnlyList<(long SubscriptionId, IReadOnlyList Bindings)> entries, int generation, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + bool sameSession = false) { var tagCount = 0; // M-b: the session this pass belongs to, read ONCE. Any later change fences the rest of the @@ -1425,44 +1433,106 @@ public sealed class GalaxyDriver { // The probe watcher owns its handles: it re-subscribes its platforms, records the // fresh handles and rebinds the reserved registry entry itself, so ScanState host - // status keeps updating after a reconnect (it used to go permanently deaf). + // status keeps updating after a reconnect (it used to go permanently deaf). It releases + // same-session handles it supersedes on its own (#991 G-6). tagCount += await probeWatcher.ResubscribeAsync(cancellationToken).ConfigureAwait(false); continue; } - var refs = oldBindings - .Select(b => b.FullReference) - .Distinct(StringComparer.OrdinalIgnoreCase) - .ToArray(); - if (refs.Length == 0) continue; + var (keepGoing, count) = await ReadviseSubscriptionAsync( + subscriptionId, oldBindings, only: null, session, generation, sameSession, cancellationToken).ConfigureAwait(false); + tagCount += count; + if (!keepGoing) return tagCount; + } - // #859: the re-issued handles' initial values (the whole point of a re-snapshot) can - // overtake this SubscribeBulk reply; park them until the Rebind below promotes them. - // Scoped to this one iteration (the using is disposed at the end of the loop body): a - // window held across all N round-trips would park every unrelated unknown-handle event - // for the whole replay and could exhaust the bound before the genuine early values. - using var earlyEventWindow = _subscriptions.BeginPendingSubscribe(); - var results = await _subscriber! + return tagCount; + } + + /// + /// Re-advise one subscription's tags — all of them ( null) or just the named references — + /// and rebind the registry to the fresh handles. MXAccess answers every advise with the attribute's current + /// value, which is what makes this the re-snapshot primitive for the reconnect replay, the replay-gap + /// re-snapshot and the dropped-event resync (#991 G-4). + /// + /// The subscription. + /// Its bindings as snapshotted. + /// The references to re-advise (case-insensitive); null = every reference. + /// The registry session this pass runs under. + /// The runtime generation this pass belongs to. + /// See . + /// Cancellation token. + /// Whether the caller may continue with further subscriptions, and the references re-advised. + private async Task<(bool KeepGoing, int Count)> ReadviseSubscriptionAsync( + long subscriptionId, + IReadOnlyList oldBindings, + ISet? only, + int session, + int generation, + bool sameSession, + CancellationToken cancellationToken) + { + var refs = oldBindings + .Select(b => b.FullReference) + .Where(r => only is null || only.Contains(r)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + if (refs.Length == 0) return (true, 0); + + // #859: the re-issued handles' initial values (the whole point of a re-snapshot) can + // overtake this SubscribeBulk reply; park them until the Rebind below promotes them. + // Scoped to this one subscription: a window held across all N round-trips would park every + // unrelated unknown-handle event for the whole replay and could exhaust the bound before the + // genuine early values. + IReadOnlyList results; + using (_subscriptions.BeginPendingSubscribe()) + { + results = await _subscriber! .SubscribeBulkAsync(refs, _options.MxAccess.PublishingIntervalMs, cancellationToken) .ConfigureAwait(false); var byAddress = BuildResultIndex(results); - var newBindings = new List(refs.Length); - foreach (var fullRef in refs) + List newBindings; + var superseded = new HashSet(); + if (!sameSession) { - var itemHandle = byAddress.TryGetValue(fullRef, out var match) && match.WasSuccessful - ? match.ItemHandle - : 0; - newBindings.Add(new TagBinding(fullRef, itemHandle)); + // Reconnect replay: the old handles are dead — the bindings become exactly the re-advised refs. + newBindings = new List(refs.Length); + foreach (var fullRef in refs) + { + var itemHandle = byAddress.TryGetValue(fullRef, out var match) && match.WasSuccessful + ? match.ItemHandle + : 0; + newBindings.Add(new TagBinding(fullRef, itemHandle)); + } + } + else + { + // Same session: replace each re-advised binding whose advise succeeded and release the handle it + // held; a binding not re-advised, or whose re-advise failed, keeps its (still live) handle. + newBindings = new List(oldBindings.Count); + foreach (var binding in oldBindings) + { + if ((only is null || only.Contains(binding.FullReference)) + && byAddress.TryGetValue(binding.FullReference, out var match) && match.WasSuccessful + && match.ItemHandle > 0) + { + newBindings.Add(new TagBinding(binding.FullReference, match.ItemHandle)); + if (binding.ItemHandle > 0 && binding.ItemHandle != match.ItemHandle) superseded.Add(binding.ItemHandle); + } + else + { + newBindings.Add(binding); + } + } } - // Rebind so the EventPump fan-out reverse map points at the post-reconnect - // handles; otherwise events on the new handles miss every subscription. Not after a - // teardown: the fresh handles belong to a subscriber that is already being released. + // Rebind so the EventPump fan-out reverse map points at the fresh handles; otherwise events + // on the new handles miss every subscription. Not after a teardown: the fresh handles belong + // to a subscriber that is already being released. SubscriptionRegistry.BindOutcome outcome; lock (_registryGate) { - if (Volatile.Read(ref _runtimeGeneration) != generation) return tagCount; + if (Volatile.Read(ref _runtimeGeneration) != generation) return (false, 0); outcome = _subscriptions.TryRebind(subscriptionId, newBindings, session); } @@ -1473,32 +1543,39 @@ public sealed class GalaxyDriver _logger.LogDebug( "GalaxyDriver {InstanceId} re-subscribe abandoned — the gateway session changed again.", _driverInstanceId); - return tagCount; + return (false, 0); } if (outcome == SubscriptionRegistry.BindOutcome.UnknownId) { // M-a: the subscription (or a subscribe-once read) was removed while its SubscribeBulk // was in flight. Nothing will ever unsubscribe what was just advised — release it now. - var orphaned = newBindings.Where(b => b.ItemHandle > 0).Select(b => b.ItemHandle).ToArray(); - if (orphaned.Length > 0) - { - try - { - await UnsubscribeAndPurgeAsync(_subscriber!, orphaned, CancellationToken.None).ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.LogWarning(ex, - "GalaxyDriver {InstanceId} could not release {Count} handle(s) re-subscribed for a subscription removed during the pass.", - _driverInstanceId, orphaned.Length); - } - } - continue; + var orphaned = results.Where(r => r.WasSuccessful && r.ItemHandle > 0).Select(r => r.ItemHandle).ToArray(); + await ReleaseHandlesAsync(orphaned, + "re-subscribed for a subscription removed during the pass").ConfigureAwait(false); + return (true, 0); } - tagCount += refs.Length; - } - return tagCount; + if (superseded.Count > 0) + { + await ReleaseHandlesAsync([.. superseded], "superseded by a same-session re-advise").ConfigureAwait(false); + } + } + return (true, refs.Length); + } + + private async Task ReleaseHandlesAsync(IReadOnlyList handles, string why) + { + if (handles.Count == 0) return; + try + { + await UnsubscribeAndPurgeAsync(_subscriber!, handles, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "GalaxyDriver {InstanceId} could not release {Count} handle(s) {Why}.", + _driverInstanceId, handles.Count, why); + } } /// @@ -2371,7 +2448,8 @@ public sealed class GalaxyDriver channelCapacity: _options.MxAccess.EventPumpChannelCapacity, clientName: _options.MxAccess.ClientName, onStreamFault: cause => OnEventPumpStreamFault(created, cause), - onReplayGap: OnEventPumpReplayGap); + onReplayGap: OnEventPumpReplayGap, + onEventsDropped: handles => OnEventPumpEventsDropped(created, handles)); _eventPump = created; _eventPump.OnDataChange += OnPumpDataChange; _eventPump.Start(); @@ -2662,12 +2740,17 @@ public sealed class GalaxyDriver var generation = Volatile.Read(ref _runtimeGeneration); _ = Task.Run(async () => { + await _resnapshotGate.WaitAsync().ConfigureAwait(false); try { - var entries = _subscriptions.SnapshotEntries(); + // Only subscriptions whose handles this session issued: they are still advised, so the re-advise + // releases the ones it supersedes (#991 G-6). One still holding an older session's handles is the + // reconnect replay's to re-subscribe. + var entries = _subscriptions.SnapshotEntriesIn(_subscriptions.CurrentSession); if (entries.Count == 0) return; - var tagCount = await ResubscribeAllAsync(entries, generation, CancellationToken.None).ConfigureAwait(false); + var tagCount = await ResubscribeAllAsync( + entries, generation, CancellationToken.None, sameSession: true).ConfigureAwait(false); _logger.LogInformation( "GalaxyDriver {InstanceId} replay-gap re-snapshot completed — {SubCount} subscriptions, {TagCount} tags re-subscribed", _driverInstanceId, entries.Count, tagCount); @@ -2683,11 +2766,139 @@ public sealed class GalaxyDriver } finally { + _resnapshotGate.Release(); Interlocked.Exchange(ref _resnapshotInFlight, 0); } }); } + // #991 G-4: item handles whose data-change events the pump's full channel dropped, waiting for a re-advise. + // Keyed by the session that issued them; guarded by _droppedLock. + private readonly Lock _droppedLock = new(); + private readonly HashSet _droppedPending = []; + private int _droppedSession; + private int _dropResyncRunning; + + // Serialises the same-session re-advise passes (replay-gap re-snapshot, dropped-event resync): both rebind a + // subscription from a snapshot of its bindings, so two interleaved passes could rebind over each other and + // release handles the other one bound. + private readonly SemaphoreSlim _resnapshotGate = new(1, 1); + + /// + /// #991 G-4 — the pump dropped data-change events for because its channel was + /// full (raised once the channel drained). MXAccess sends a value only when it changes, so each of those tags + /// would otherwise keep its previous value, Good, until the attribute happens to change again. Queue them for + /// a re-advise — MXAccess answers an advise with the current value — on one coalescing background worker. + /// Runs on the pump's dispatch thread: must not block. + /// + private void OnEventPumpEventsDropped(EventPump? source, IReadOnlyCollection itemHandles) + { + if (_runtimeStopping || _subscriber is null || source is null || itemHandles.Count == 0) return; + var session = source.Session; + // A pump of an older session: the reconnect replay re-advises everything on the new session anyway. + if (session != _subscriptions.CurrentSession) return; + + lock (_droppedLock) + { + if (_droppedSession != session) + { + _droppedPending.Clear(); + _droppedSession = session; + } + _droppedPending.UnionWith(itemHandles); + } + if (Interlocked.Exchange(ref _dropResyncRunning, 1) == 1) return; // the running worker picks them up + + _ = Task.Run(async () => + { + while (true) + { + int[] batch; + int batchSession; + lock (_droppedLock) + { + if (_droppedPending.Count == 0 || _runtimeStopping) + { + _droppedPending.Clear(); + Volatile.Write(ref _dropResyncRunning, 0); // under the lock: a later add starts a new worker + return; + } + batch = [.. _droppedPending]; + _droppedPending.Clear(); + batchSession = _droppedSession; + } + + try + { + await ResyncDroppedHandlesAsync(batch, batchSession).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "GalaxyDriver {InstanceId} could not re-read {Count} tag(s) whose changes were dropped — they may stay stale until they next change.", + _driverInstanceId, batch.Length); + } + } + }); + } + + /// + /// Re-advise exactly the tags bound to (still issued by ) + /// and release the handles they replace. A handle no subscription holds any more needs nothing. + /// + private async Task ResyncDroppedHandlesAsync(IReadOnlyCollection itemHandles, int session) + { + await _resnapshotGate.WaitAsync().ConfigureAwait(false); + try + { + var generation = Volatile.Read(ref _runtimeGeneration); + if (_runtimeStopping || _subscriber is null || _subscriptions.CurrentSession != session) return; + + var dropped = itemHandles.ToHashSet(); + var probeAffected = false; + var tagCount = 0; + foreach (var (subscriptionId, bindings) in _subscriptions.SnapshotEntriesIn(session)) + { + HashSet? affected = null; + foreach (var binding in bindings) + { + if (binding.ItemHandle <= 0 || !dropped.Contains(binding.ItemHandle)) continue; + (affected ??= new HashSet(StringComparer.OrdinalIgnoreCase)).Add(binding.FullReference); + } + if (affected is null) continue; + + if (subscriptionId == SubscriptionRegistry.ProbeSubscriptionId) + { + probeAffected = true; // the watcher owns its handles + continue; + } + + var (keepGoing, count) = await ReadviseSubscriptionAsync( + subscriptionId, bindings, affected, session, generation, sameSession: true, CancellationToken.None) + .ConfigureAwait(false); + tagCount += count; + if (!keepGoing) return; + } + + if (probeAffected && _probeWatcher is { } probeWatcher + && Volatile.Read(ref _runtimeGeneration) == generation && _subscriptions.CurrentSession == session) + { + tagCount += await probeWatcher.ResubscribeAsync(CancellationToken.None).ConfigureAwait(false); + } + + if (tagCount > 0) + { + _logger.LogInformation( + "GalaxyDriver {InstanceId} re-advised {TagCount} tag(s) whose changes the event channel dropped.", + _driverInstanceId, tagCount); + } + } + finally + { + _resnapshotGate.Release(); + } + } + /// /// Stream-fault callback for the . The gw StreamEvents /// stream faulted (transient gateway drop, network blip, gw restart). Forward diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Health/PerPlatformProbeWatcher.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Health/PerPlatformProbeWatcher.cs index fc84e59b1..9fe3dde03 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Health/PerPlatformProbeWatcher.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Health/PerPlatformProbeWatcher.cs @@ -241,6 +241,10 @@ public sealed class PerPlatformProbeWatcher : IDisposable // ran while SubscribeBulk was in flight already cleared the map and the registry entry, so // recording now would resurrect the probe entry into the next runtime's registry. bool stopped; + // #991 G-6: handles this subscribe replaces that the SAME session issued are still advised on the gateway + // (the replay-gap re-snapshot) and are released below. A previous session's handles are dead and their + // numbers reused by the current session, so they are never sent. + var superseded = new List(); lock (_syncLock) { stopped = _disposed; @@ -253,11 +257,32 @@ public sealed class PerPlatformProbeWatcher : IDisposable return false; } foreach (var (platform, itemHandle, _) in acquired) + { + if (_itemHandlesByPlatform.TryGetValue(platform, out var previous) + && previous.Session == session && previous.ItemHandle > 0 && previous.ItemHandle != itemHandle) + { + superseded.Add(previous.ItemHandle); + } _itemHandlesByPlatform[platform] = new ProbeHandle(itemHandle, session); + } if (!PublishBindingsLocked(session)) return false; } } + if (!stopped && superseded.Count > 0) + { + try { await _subscriber.UnsubscribeBulkAsync(superseded, CancellationToken.None).ConfigureAwait(false); } + catch (Exception ex) + { + _logger.LogWarning(ex, + "PerPlatformProbeWatcher could not release {Count} superseded probe handle(s)", superseded.Count); + } + finally + { + _registry?.PurgeParked(superseded, session); + } + } + if (stopped) { var orphans = acquired.Where(a => a.ItemHandle > 0).Select(a => a.ItemHandle).ToArray(); 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 d9f39049d..05681c20d 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 @@ -73,6 +73,13 @@ internal sealed class EventPump : IAsyncDisposable private readonly Func _handleFactory; private readonly Action? _onStreamFault; private readonly Action? _onReplayGap; + private readonly Action>? _onEventsDropped; + + // #991 G-4: item handles whose data-change events were dropped since the last flush. Written by the read loop, + // drained by the dispatch loop once the channel is empty. + private readonly Lock _droppedLock = new(); + private readonly HashSet _droppedHandles = []; + private volatile bool _dropsPending; private readonly Channel _channel; private readonly KeyValuePair _clientTag; private readonly CancellationTokenSource _cts = new(); @@ -103,6 +110,12 @@ internal sealed class EventPump : IAsyncDisposable /// Optional callback invoked when the gateway reports a replay gap. The contract /// obliges the client to re-snapshot; see . /// + /// + /// #991 G-4 — optional callback receiving the item handles whose data-change events the full channel + /// dropped, raised on the dispatch thread once the channel has drained (so a resync is not swallowed by + /// the same congestion). MXAccess sends a value only on change, so each such tag is stale until re-read. + /// Must not block. + /// public EventPump( IGalaxySubscriber subscriber, SubscriptionRegistry registry, @@ -111,7 +124,8 @@ internal sealed class EventPump : IAsyncDisposable int channelCapacity = DefaultChannelCapacity, string? clientName = null, Action? onStreamFault = null, - Action? onReplayGap = null) + Action? onReplayGap = null, + Action>? onEventsDropped = null) { _subscriber = subscriber ?? throw new ArgumentNullException(nameof(subscriber)); _registry = registry ?? throw new ArgumentNullException(nameof(registry)); @@ -119,6 +133,7 @@ internal sealed class EventPump : IAsyncDisposable _handleFactory = handleFactory ?? (id => new GalaxySubscriptionHandle(id)); _onStreamFault = onStreamFault; _onReplayGap = onReplayGap; + _onEventsDropped = onEventsDropped; if (channelCapacity < 1) { @@ -158,6 +173,11 @@ internal sealed class EventPump : IAsyncDisposable /// internal int Session => _session; + private long _droppedCount; + + /// Test seam: events this pump dropped because its bounded channel was full. + internal long DroppedCountForTests => Interlocked.Read(ref _droppedCount); + /// True once the stream loop has exited (faulted, completed by the gateway, or disposed). internal bool HasEnded => Volatile.Read(ref _ended); @@ -298,6 +318,8 @@ internal sealed class EventPump : IAsyncDisposable if (!_channel.Writer.TryWrite(ev)) { EventsDropped.Add(1, _clientTag); + Interlocked.Increment(ref _droppedCount); + RecordDrop(ev); } } @@ -451,10 +473,13 @@ internal sealed class EventPump : IAsyncDisposable if (ReferenceEquals(ev, WakeSentinel)) { DispatchReadyEvents(); - continue; } - Dispatch(ev); - EventsDispatched.Add(1, _clientTag); + else + { + Dispatch(ev); + EventsDispatched.Add(1, _clientTag); + } + if (_dropsPending && _channel.Reader.Count == 0) FlushDrops(); } } catch (Exception) when (ct.IsCancellationRequested) @@ -473,6 +498,43 @@ internal sealed class EventPump : IAsyncDisposable } } + /// + /// #991 G-4 — remember the item handle of a dropped data-change event, then wake the dispatch loop. The wake + /// usually fails (the channel is full — the loop is busy and checks after each item); it succeeds exactly when + /// the loop drained the channel between this drop and now, and would otherwise sleep with the drop unflushed. + /// + private void RecordDrop(MxEvent ev) + { + if (_onEventsDropped is null || ev.Family != MxEventFamily.OnDataChange || ev.ItemHandle <= 0) return; + lock (_droppedLock) + { + _droppedHandles.Add(ev.ItemHandle); + _dropsPending = true; + } + _channel.Writer.TryWrite(WakeSentinel); + } + + /// Hand every recorded dropped handle to the owner (dispatch thread, channel drained). + private void FlushDrops() + { + int[] handles; + lock (_droppedLock) + { + handles = [.. _droppedHandles]; + _droppedHandles.Clear(); + _dropsPending = false; + } + if (handles.Length == 0 || _onEventsDropped is null) return; + _logger.LogWarning( + "Galaxy EventPump dropped data changes for {Count} item(s) while its channel was full — re-reading them.", + handles.Length); + try { _onEventsDropped(handles); } + catch (Exception ex) + { + _logger.LogWarning(ex, "Galaxy EventPump dropped-events callback threw — those values may stay stale."); + } + } + private void Dispatch(MxEvent ev) { switch (ev.Family) 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 5f4aaf82f..f4203fa54 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 @@ -650,6 +650,17 @@ internal sealed class SubscriptionRegistry public IReadOnlyList<(long SubscriptionId, IReadOnlyList Bindings)> SnapshotEntriesNotIn(int session) => [.. _bySubscriptionId.Values.Where(e => e.Session != session).Select(e => (e.SubscriptionId, e.Bindings))]; + /// + /// limited to subscriptions whose handles WERE issued by + /// — the same-session re-advise work list (#991: replay-gap re-snapshot, dropped-event resync). Their handles + /// are live, so a re-advise must release the ones it supersedes; a subscription still holding an older + /// session's handles belongs to the reconnect replay instead. + /// + /// The current session. + /// The current-session subscriptions with their bindings. + public IReadOnlyList<(long SubscriptionId, IReadOnlyList Bindings)> SnapshotEntriesIn(int session) => + [.. _bySubscriptionId.Values.Where(e => e.Session == session).Select(e => (e.SubscriptionId, e.Bindings))]; + /// /// Per-subscription bookkeeping. is an index /// over keyed by item handle so ResolveSubscribers diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Health/PerPlatformProbeWatcherRegistryTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Health/PerPlatformProbeWatcherRegistryTests.cs index 511bb6967..4981aab86 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Health/PerPlatformProbeWatcherRegistryTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Health/PerPlatformProbeWatcherRegistryTests.cs @@ -82,6 +82,44 @@ public sealed class PerPlatformProbeWatcherRegistryTests registry.TrackedSubscriptionCount.ShouldBe(1); } + /// + /// #991 G-6: a same-session resubscribe (the replay-gap re-snapshot) releases the handles it superseded — they + /// are still advised on the gateway, and keeping them doubled the advise count per gap. + /// + [Fact] + public async Task A_same_session_resubscribe_releases_the_superseded_handles() + { + var registry = new SubscriptionRegistry(); + var subscriber = new FakeSubscriber(); + using var watcher = new PerPlatformProbeWatcher(subscriber, new HostStatusAggregator(), registry); + await watcher.SyncPlatformsAsync(["A", "B"], CancellationToken.None); + var old = watcher.CurrentBindings.Select(b => b.ItemHandle).OrderBy(h => h).ToArray(); + + await watcher.ResubscribeAsync(CancellationToken.None); + + subscriber.Unsubscribes.ShouldHaveSingleItem().OrderBy(h => h).ShouldBe(old); + watcher.CurrentBindings.Select(b => b.ItemHandle).ShouldAllBe(h => !old.Contains(h)); + } + + /// + /// A resubscribe after a reconnect must NOT release the superseded handles: they belong to the dead session + /// and the new session reuses the numbers, so an unsubscribe would unadvise some other live item. + /// + [Fact] + public async Task A_resubscribe_after_a_session_change_never_releases_dead_session_handles() + { + var registry = new SubscriptionRegistry(); + var subscriber = new FakeSubscriber(); + using var watcher = new PerPlatformProbeWatcher(subscriber, new HostStatusAggregator(), registry); + await watcher.SyncPlatformsAsync(["A"], CancellationToken.None); + + registry.StartNewSession(); + await watcher.ResubscribeAsync(CancellationToken.None); + + subscriber.Unsubscribes.ShouldBeEmpty(); + watcher.CurrentBindings.ShouldHaveSingleItem().ItemHandle.ShouldBeGreaterThan(0, "positive control: rebound"); + } + /// StopAsync unsubscribes the live handles and removes the reserved entry. [Fact] public async Task StopAsync_unsubscribes_and_removes_the_reserved_entry() diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/DroppedEventResyncTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/DroppedEventResyncTests.cs new file mode 100644 index 000000000..fa55fa1f9 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/DroppedEventResyncTests.cs @@ -0,0 +1,219 @@ +using System.Collections.Concurrent; +using System.Runtime.CompilerServices; +using System.Threading.Channels; +using Google.Protobuf.WellKnownTypes; +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.Config; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime; + +/// +/// #991 G-4 / G-6 — the two re-advise paths of the event stream. +/// +/// G-4: MXAccess sends a value only when it changes, so a data-change event the full bounded +/// channel drops (newest-dropped) left its tag at the previous value, Good, until the +/// attribute happened to change again. The pump now records the dropped item handles and, once the channel +/// has drained, the driver re-advises exactly those tags — MXAccess answers an advise with the current +/// value — and releases the superseded handles. +/// G-6: the replay-gap re-snapshot re-advised every tag on the SAME gateway session without +/// releasing the previous handles, doubling the gateway's advise count per gap. It now releases them (only +/// same-session handles — a dead session's numbers are reused by the next one and must never be sent). +/// +/// +public sealed class DroppedEventResyncTests +{ + private static GalaxyDriverOptions Opts(int capacity) => new( + new GalaxyGatewayOptions("https://mxgw.test:5001", "key"), + new GalaxyMxAccessOptions("OtOpcUa-A", EventPumpChannelCapacity: capacity), + new GalaxyRepositoryOptions(WatchDeployEvents: false), + new GalaxyReconnectOptions()); + + private static GalaxyDriver NewDriver(AdvisingSubscriber subscriber, int capacity = 64) => + new("g", Opts(capacity), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber); + + /// + /// Capacity-1 pump, handler wedged: the last two changes of a burst are dropped. Before the fix the tag ended + /// at the last value that made it through the channel (2.0) — Good, and wrong — indefinitely. Now it ends at + /// the real current value (4.0), and the handle the drop affected is released once its replacement is bound. + /// + [Fact] + public async Task A_value_dropped_by_a_full_event_channel_is_resynced_once_the_channel_drains() + { + var subscriber = new AdvisingSubscriber(); + subscriber.Current["Tank.SP"] = 0.0; + using var driver = NewDriver(subscriber, capacity: 1); + + var values = new ConcurrentQueue(); + using var gate = new ManualResetEventSlim(true); + using var blocked = new SemaphoreSlim(0); + driver.OnDataChange += (_, e) => + { + if (e.Snapshot.Value is double d) values.Enqueue(d); + if (!gate.IsSet) + { + blocked.Release(); + gate.Wait(TimeSpan.FromSeconds(20)); + } + }; + + await driver.SubscribeAsync(["Tank.SP"], TimeSpan.Zero, TestContext.Current.CancellationToken); + await TestWait.UntilAsync(() => values.Contains(0.0), "the initial value must be published"); + var firstHandle = subscriber.LiveHandlesFor("Tank.SP").ShouldHaveSingleItem(); + + gate.Reset(); + subscriber.Set("Tank.SP", 1.0); + (await blocked.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken)) + .ShouldBeTrue("the dispatch thread must be wedged in the handler on 1.0"); + + subscriber.Set("Tank.SP", 2.0); + subscriber.Set("Tank.SP", 3.0); + subscriber.Set("Tank.SP", 4.0); + var pump = (EventPump)driver.EventPumpInstanceForTests.ShouldNotBeNull(); + await TestWait.UntilAsync(() => pump.DroppedCountForTests >= 2, + "with one slot and the dispatcher wedged, the burst's tail must be dropped"); + + gate.Set(); + + await TestWait.UntilAsync(() => values.LastOrDefault() == 4.0, + "a dropped change must be resynced — the tag must not stay at the last value that fit in the channel", + () => $"published=[{string.Join(", ", values)}] subscribes={subscriber.SubscribeCalls}"); + await TestWait.UntilAsync(() => subscriber.Unsubscribed.Contains(firstHandle), + "the handle superseded by the re-advise must be released, not leaked on the gateway"); + subscriber.LiveHandlesFor("Tank.SP").ShouldHaveSingleItem().ShouldNotBe(firstHandle); + + // Positive control: the re-advised tag keeps receiving live changes on its new handle. + subscriber.Set("Tank.SP", 5.0); + await TestWait.UntilAsync(() => values.LastOrDefault() == 5.0, "live data must keep flowing after the resync"); + } + + /// + /// No drop, no re-advise: an unwedged pump delivers every change and the subscriber sees exactly one + /// SubscribeBulk. Guards the resync against firing on ordinary traffic. + /// + [Fact] + public async Task Without_a_drop_nothing_is_re_advised() + { + var subscriber = new AdvisingSubscriber(); + subscriber.Current["Tank.SP"] = 0.0; + using var driver = NewDriver(subscriber); + var values = new ConcurrentQueue(); + driver.OnDataChange += (_, e) => { if (e.Snapshot.Value is double d) values.Enqueue(d); }; + + await driver.SubscribeAsync(["Tank.SP"], TimeSpan.Zero, TestContext.Current.CancellationToken); + for (var i = 1; i <= 20; i++) subscriber.Set("Tank.SP", i); + await TestWait.UntilAsync(() => values.LastOrDefault() == 20.0, "every change must be delivered"); + + subscriber.SubscribeCalls.ShouldBe(1); + subscriber.Unsubscribed.ShouldBeEmpty(); + } + + /// + /// G-6: a replay gap re-advises every tag on the same session; the pre-gap handles are released once the + /// fresh ones are bound, and data keeps flowing on the fresh handles (positive control). + /// + [Fact] + public async Task A_replay_gap_resnapshot_releases_the_pre_gap_handles() + { + var subscriber = new AdvisingSubscriber(); + subscriber.Current["Tank.A"] = 1.0; + subscriber.Current["Tank.B"] = 2.0; + using var driver = NewDriver(subscriber); + var values = new ConcurrentQueue<(string Ref, double Value)>(); + driver.OnDataChange += (_, e) => { if (e.Snapshot.Value is double d) values.Enqueue((e.FullReference, d)); }; + + await driver.SubscribeAsync(["Tank.A", "Tank.B"], TimeSpan.Zero, TestContext.Current.CancellationToken); + var preGap = subscriber.LiveHandles.ToArray(); + preGap.Length.ShouldBe(2); + + subscriber.EmitGap(); + + await TestWait.UntilAsync(() => subscriber.SubscribeCalls >= 2, "the replay gap must trigger a re-snapshot"); + await TestWait.UntilAsync(() => preGap.All(subscriber.Unsubscribed.Contains), + "the re-snapshot must release the pre-gap handles — the session is the same, so they are still advised", + () => $"unsubscribed=[{string.Join(", ", subscriber.Unsubscribed)}] preGap=[{string.Join(", ", preGap)}]"); + subscriber.LiveHandles.Count.ShouldBe(2, "exactly one advise per tag after the gap"); + + subscriber.Set("Tank.B", 9.0); + await TestWait.UntilAsync(() => values.Contains(("Tank.B", 9.0)), "data must flow on the post-gap handles"); + } + + /// + /// Behaves like the gateway + MXAccess for the parts these tests need: every SubscribeBulk issues fresh item + /// handles and pushes each one's current value (an advise's initial value), a change is pushed on every live + /// handle advising that reference, and UnsubscribeBulk retires handles. + /// + private sealed class AdvisingSubscriber : IGalaxySubscriber + { + private readonly Channel _events = Channel.CreateUnbounded(); + private readonly ConcurrentDictionary _live = new(); + private int _nextHandle = 100; + private int _subscribeCalls; + + public ConcurrentDictionary Current { get; } = new(StringComparer.OrdinalIgnoreCase); + + public ConcurrentQueue Unsubscribed { get; } = new(); + + public int SubscribeCalls => Volatile.Read(ref _subscribeCalls); + + public ICollection LiveHandles => _live.Keys; + + public int[] LiveHandlesFor(string fullRef) => + [.. _live.Where(kv => string.Equals(kv.Value, fullRef, StringComparison.OrdinalIgnoreCase)).Select(kv => kv.Key)]; + + public void Set(string fullRef, double value) + { + Current[fullRef] = value; + foreach (var handle in LiveHandlesFor(fullRef)) Emit(handle, value); + } + + public void EmitGap() => _events.Writer.TryWrite(new MxEvent + { + Family = MxEventFamily.Unspecified, + ReplayGap = new ReplayGap { RequestedAfterSequence = 1, OldestAvailableSequence = 2 }, + }).ShouldBeTrue(); + + private void Emit(int handle, double value) => _events.Writer.TryWrite(new MxEvent + { + Family = MxEventFamily.OnDataChange, + ItemHandle = handle, + Value = new MxValue { DoubleValue = value }, + Quality = 192, + SourceTimestamp = Timestamp.FromDateTime(DateTime.UtcNow), + }).ShouldBeTrue(); + + public Task> SubscribeBulkAsync( + IReadOnlyList fullReferences, int bufferedUpdateIntervalMs, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _subscribeCalls); + var results = new List(fullReferences.Count); + foreach (var r in fullReferences) + { + var handle = Interlocked.Increment(ref _nextHandle); + _live[handle] = r; + results.Add(new SubscribeResult { TagAddress = r, ItemHandle = handle, WasSuccessful = true }); + if (Current.TryGetValue(r, out var v)) Emit(handle, v); // the advise's initial value + } + return Task.FromResult>(results); + } + + public Task UnsubscribeBulkAsync(IReadOnlyList itemHandles, CancellationToken cancellationToken) + { + foreach (var h in itemHandles) + { + Unsubscribed.Enqueue(h); + _live.TryRemove(h, out _); + } + return Task.CompletedTask; + } + + public async IAsyncEnumerable StreamEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await foreach (var ev in _events.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) + yield return ev; + } + } +}