diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs index b20cc7981..780b53781 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedEventDelivery.cs @@ -455,11 +455,14 @@ internal sealed record ProjectedEventMarker(object? Identity, NodeId ConditionId } /// -/// A3 (§5.4): an carrying its . The SDK never clones a -/// queued list on its way to the wire (SDK 2.0.1: QueueEvent(EventFieldList) enqueues the instance, -/// Publish dequeues it, ConstructMessage places it, Republish returns the stored message), so -/// ProjectedNotificationRewriter sees this instance on every Publish and Republish and drops it when the re-check -/// fails. +/// A3 (§5.4): an carrying its . The rewriter does NOT see +/// the queued instance: SDK 2.0.1 SentMessageQueue stores the constructed message and returns a +/// CoreUtils.Clone of it on Publish and on Republish. The gate still works because +/// is MemberwiseClone, so every copy keeps this subclass, its +/// and its handle, and ProjectedNotificationRewriter drops the copy when the re-check fails. +/// That clone dependency is pinned by +/// ImportedConditionClassifierTests.Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker: +/// an SDK that cloned through the activator would turn it red. /// /// /// A3 review round 2 (root cause of the OI refresh failures): SDK 2.0.1 POOLS process-wide diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs index 6372e1341..75b4dd8af 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.Runner.cs @@ -143,7 +143,8 @@ public sealed partial class ProjectedConditionAccess private readonly CancellationTokenSource _stop = new(); private readonly object _statusGate = new(); private readonly object _staleGate = new(); - private readonly ConnectionRunner? _predecessor; + /// Verification r2 N1: dropped right after the hand-over, so runners never chain (R3 → R2 → R1 …). + private ConnectionRunner? _predecessor; private Task _loop = Task.CompletedTask; private Task _stopped = Task.CompletedTask; private MappingState[] _states = []; @@ -177,17 +178,27 @@ public sealed partial class ProjectedConditionAccess public void Start() => _loop = Task.Run(async () => { - if (_predecessor is { } previous) - { - // S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would - // otherwise race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation). - try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); } - _materialised = previous._materialised; - previous._materialised = new HashSet(StringComparer.Ordinal); - } + await HandOverAsync().ConfigureAwait(false); await RunAsync(_stop.Token).ConfigureAwait(false); }); + /// + /// S3/S4: never overlap the previous runner of this connection — its in-flight Publish or its removal would otherwise + /// race this runner's materialisation (an orphaned key, or a fresh key removed by the old continuation). The + /// materialised set moves over only after the predecessor stopped. Verification r2 N1: the predecessor reference is + /// dropped once the hand-over is done (its own method, so no hoisted local outlives it either) — otherwise every + /// linger expiry or mapping change would add a link to a chain that keeps each old runner reachable. + /// + private async Task HandOverAsync() + { + var previous = _predecessor; + if (previous is null) return; + try { await previous.Stopped.ConfigureAwait(false); } catch (Exception ex) { _owner._log.LogDebug(ex, "Imported conditions: predecessor stop faulted"); } + _materialised = previous._materialised; + previous._materialised = new HashSet(StringComparer.Ordinal); + _predecessor = null; + } + public void Stop(bool removeConditions) { _stop.Cancel(); @@ -195,6 +206,8 @@ public sealed partial class ProjectedConditionAccess lock (_staleGate) { _staleGeneration++; _stale?.Dispose(); _stale = null; } _stopped = _loop.ContinueWith(_ => { + // Verification r2 N1: a stopped runner keeps no stream's record sets (it may sit in _stopping until the next demand). + lock (_statusGate) _states = []; if (!removeConditions) return; var keys = _materialised.ToArray(); if (keys.Length > 0 && _owner._sink() is { } sink) sink.RemoveConditions(ConnectionId, keys); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs index 24b4176c2..b3a43ccda 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ProjectedConditionAccess.cs @@ -290,6 +290,13 @@ public sealed partial class ProjectedConditionAccess : IProjectedConditionAccess lock (_gate) return _runners.ContainsKey(connectionId); } + /// Test observation (verification r2 N1): a weak reference to the connection's current (or still stopping) runner. + public WeakReference? RunnerReference(string connectionId) + { + lock (_gate) + return _runners.TryGetValue(connectionId, out var runner) || _stopping.TryGetValue(connectionId, out runner) ? new WeakReference(runner) : null; + } + /// Test observation: snapshot barriers a connection completed. public int BarriersCompleted(string connectionId) { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs index 31265cb63..7625958b1 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs @@ -149,6 +149,34 @@ public sealed class ImportedConditionClassifierTests : IAsyncDisposable ProjectedNotificationRewriter.Project(message, republish: false, null).NotificationData.Count.ShouldBe(0); } + /// + /// Verification review r2: the rewriter never sees the queued instance — SDK 2.0.1 SentMessageQueue hands Publish + /// and Republish a CoreUtils.Clone of the stored message. The gate holds only because + /// is MemberwiseClone, which keeps the subclass, the marker and the handle. Pins + /// that dependency: an SDK that cloned through the activator (a stock list) would turn this red. + /// + [Fact] + public void Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker() + { + var marker = new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false); + var marked = new ProjectedEventFieldList(marker) { ClientHandle = 42 }; + + var direct = marked.Clone().ShouldBeOfType(); + direct.Marker.ShouldBeSameAs(marker); + direct.ClientHandle.ShouldBe(42u); + + var message = new NotificationMessage { SequenceNumber = 11, + NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] }; + var delivered = CoreUtils.Clone(message)!; // exactly what SentMessageQueue returns for Publish / Republish + delivered.NotificationData[0].TryGetValue(out var list).ShouldBeTrue(); + var events = list!.Events; + var cloned = events[0].ShouldBeOfType(); + cloned.ShouldNotBeSameAs(marked, "the SDK delivers a copy, not the queued instance"); + cloned.Marker.ShouldBeSameAs(marker); + ProjectedNotificationRewriter.Project(delivered, republish: false, null).NotificationData.Count + .ShouldBe(0, "the copy is still judged by its marker (and dropped when the re-check fails)"); + } + [Fact] public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs index b0bdb1821..4f8d42454 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataProjectedConditionAccessTests.cs @@ -461,6 +461,35 @@ public sealed class GrpcDataProjectedConditionAccessTests f.Sink.Live.ShouldBe([Key("y")], "x was handed over (not orphaned) and the new complete set removed it"); } + [Fact] + public async Task N1_demand_cycles_and_mapping_changes_do_not_chain_runners_so_an_old_runner_is_collectable() + { + // Verification review r2 N1: each runner kept its predecessor (and that one's record sets), so every linger expiry + // + re-subscribe or mapping change added a link R3 → R2 → R1 and memory grew without bound. + await using var f = new Fixture(("map-a", DataRealm.Raw, 10)); + var demand = f.Access.AcquireEventDemand(null)!; + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), 3)])); + var first = f.Access.RunnerReference(Connection)!; + var version = 3L; + for (var cycle = 0; cycle < 3; cycle++) + { + demand.Dispose(); + await f.WaitAsync(() => !f.Access.IsRunning(Connection)); // linger expired + demand = f.Access.AcquireEventDemand(null)!; + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)])); + } + for (var change = 0; change < 2; change++) + { + f.Mappings.Current[0].Mapping.MaxConditions++; // a changed signature ⇒ a new runner, a new stream + f.Mappings.Raise(); + await CompleteFirstAsync(f, ("map-a", [Record(Key("x"), ++version)])); + } + f.Sink.Live.ShouldBe([Key("x")], "the hand-over still works across every cycle"); + for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } + first.IsAlive.ShouldBeFalse("the current runner must not keep a chain of predecessors reachable"); + demand.Dispose(); + } + // --------------------------------------------------------------------------------------------------------------------- internal static string Key(string seed) =>